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
dain/memcached
src/main/java/org/iq80/memcached/Items.java
// Path: src/main/java/org/iq80/memory/Region.java // public interface Region // { // Allocator getAllocator(); // // ByteBuffer toByteBuffer(); // // long getAddress(); // // long size(); // // byte getByte(long offset); // // void putByte(long offset, byte value); // // byte[] getBytes(long srcOffset, int length); // // void getBytes(long srcOffset, byte[] target); // // void getBytes(long srcOffset, byte[] target, int targetOffset, int length); // // void putBytes(long targetOffset, byte[] src); // // void putBytes(long targetOffset, byte[] src, int srcOffset, int length); // // Region getRegion(long offset); // // Region getRegion(long offset, long length); // // short getShort(long offset); // // void putShort(long offset, short value); // // char getChar(long offset); // // void putChar(long offset, char value); // // int getInt(long offset); // // void putInt(long offset, int value); // // long getLong(long offset); // // void putLong(long offset, long value); // // float getFloat(long offset); // // void putFloat(long offset, float value); // // double getDouble(long offset); // // void putDouble(long offset, double value); // // void setMemory(byte value); // // void setMemory(long offset, long size, byte value); // // void copyMemory(long srcOffset, Region target); // // void copyMemory(long srcOffset, Region target, long targetOffset, long size); // // int compareMemory(long srcOffset, Region target, long targetOffset, long size); // // boolean isInBounds(long offset, long length); // // void checkBounds(long offset, long length); // // }
import org.iq80.memory.Region; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong;
// try to allocate again // maybe someone else freed some stuff item = Item.createItem(totalLength, slabManager, useCas); if (item != null) { return item; } // Last ditch effort. There is a very rare bug which causes // refcount leaks. We've fixed most of them, but it still happens, // and it may happen in the future. // We can reasonably assume no item can stay locked for more than // three hours, so if we find one in the tail which is that old, // free it anyway. item = lru.tryTailRepair(50, current_time); if (item != null) { // remove from hash assoc.delete(item.getKey()); return item; } item = Item.createItem(totalLength, slabManager, useCas); return item; } /** * Get with expiriation logic. wrapper around assoc_find which does the lazy * expiration logic */
// Path: src/main/java/org/iq80/memory/Region.java // public interface Region // { // Allocator getAllocator(); // // ByteBuffer toByteBuffer(); // // long getAddress(); // // long size(); // // byte getByte(long offset); // // void putByte(long offset, byte value); // // byte[] getBytes(long srcOffset, int length); // // void getBytes(long srcOffset, byte[] target); // // void getBytes(long srcOffset, byte[] target, int targetOffset, int length); // // void putBytes(long targetOffset, byte[] src); // // void putBytes(long targetOffset, byte[] src, int srcOffset, int length); // // Region getRegion(long offset); // // Region getRegion(long offset, long length); // // short getShort(long offset); // // void putShort(long offset, short value); // // char getChar(long offset); // // void putChar(long offset, char value); // // int getInt(long offset); // // void putInt(long offset, int value); // // long getLong(long offset); // // void putLong(long offset, long value); // // float getFloat(long offset); // // void putFloat(long offset, float value); // // double getDouble(long offset); // // void putDouble(long offset, double value); // // void setMemory(byte value); // // void setMemory(long offset, long size, byte value); // // void copyMemory(long srcOffset, Region target); // // void copyMemory(long srcOffset, Region target, long targetOffset, long size); // // int compareMemory(long srcOffset, Region target, long targetOffset, long size); // // boolean isInBounds(long offset, long length); // // void checkBounds(long offset, long length); // // } // Path: src/main/java/org/iq80/memcached/Items.java import org.iq80.memory.Region; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong; // try to allocate again // maybe someone else freed some stuff item = Item.createItem(totalLength, slabManager, useCas); if (item != null) { return item; } // Last ditch effort. There is a very rare bug which causes // refcount leaks. We've fixed most of them, but it still happens, // and it may happen in the future. // We can reasonably assume no item can stay locked for more than // three hours, so if we find one in the tail which is that old, // free it anyway. item = lru.tryTailRepair(50, current_time); if (item != null) { // remove from hash assoc.delete(item.getKey()); return item; } item = Item.createItem(totalLength, slabManager, useCas); return item; } /** * Get with expiriation logic. wrapper around assoc_find which does the lazy * expiration logic */
public Item get(Region key)
mappum/mercury
src/main/java/io/coinswap/swap/AtomicSwapController.java
// Path: src/main/java/io/coinswap/client/Currency.java // public class Currency { // private static final Logger log = LoggerFactory.getLogger(Currency.class); // private static final File checkpointDir = new File("./checkpoints"); // // private static final int MIN_BROADCAST_CONNECTIONS = 5; // private static final int CONNECTIONS = 8; // // protected NetworkParameters params; // protected File directory; // protected WalletAppKit wallet; // protected String name, id, symbol; // protected String[] pairs; // protected int index; // protected boolean hashlock; // whether or not this coin can be used on the Alice-side of a swap // protected int confirmationDepth; // protected List<InetSocketAddress> connectPeers; // // private boolean setup; // private SettableFuture<Object> setupFuture; // // public Currency(NetworkParameters params, File directory, // String name, String id, String symbol, String[] pairs, // int index, boolean hashlock, int confirmationDepth) { // // this.params = params; // this.directory = directory; // this.name = name; // this.id = id; // this.symbol = symbol; // this.pairs = pairs; // this.index = index; // this.hashlock = hashlock; // this.confirmationDepth = confirmationDepth; // this.connectPeers = new ArrayList<InetSocketAddress>(0); // // setupFuture = SettableFuture.create(); // // // create the AltcoinJ wallet to interface with the currency // wallet = new WalletAppKit(params, directory, name.toLowerCase()) { // @Override // protected void onSetupCompleted() { // makeBackup(); // // peerGroup().setMaxConnections(CONNECTIONS); // peerGroup().setMinBroadcastConnections(1); // only require 1 peer in case we are connected to local peer // peerGroup().setFastCatchupTimeSecs(wallet.wallet().getEarliestKeyCreationTime()); // // // remove the re-add the wallet to the peergroup, so we will broadcast waiting transactions with the // // peergroup settings set correctly // peerGroup().removeWallet(wallet()); // peerGroup().addWallet(wallet()); // // for(InetSocketAddress peer : connectPeers) { // peerGroup().connectTo(peer); // } // // setup = true; // setupFuture.set(null); // } // }; // wallet.setUserAgent(Main.APP_NAME, Main.APP_VERSION); // wallet.setBlockingStartup(false); // // // load a checkpoint file (if it exists) to speed up initial blockchain sync // InputStream checkpointStream = Main.class.getResourceAsStream("/checkpoints/"+name.toLowerCase()+".txt"); // if(checkpointStream != null) { // wallet.setCheckpoints(checkpointStream); // } else { // log.info("No checkpoints found for " + name); // } // } // // public void broadcastTransaction(final Transaction tx) { // wallet.wallet().receivePending(tx, null); // // // broadcast even if we only have 1 peer (in case we are connected to localhost peer) // wallet.peerGroup().broadcastTransaction(tx, 1); // // also wait until we have MIN_BROADCAST_CONNECTIONS, then rebroadcast // wallet.peerGroup().broadcastTransaction(tx, MIN_BROADCAST_CONNECTIONS); // } // // public void start() { // wallet.startAsync(); // wallet.awaitRunning(); // } // // public void stop() { // wallet.stopAsync(); // wallet.awaitTerminated(); // } // // public void addConnectPeers(List<InetSocketAddress> peers) { // checkNotNull(peers); // this.connectPeers.addAll(peers); // } // // private void makeBackup() { // File backupDir = new File(directory, "backup"); // if(!backupDir.exists()) { // boolean success = backupDir.mkdir(); // if(!success) throw new RuntimeException(); // } // // File backup = new File(backupDir, name.toLowerCase()+".wallet"); // if(!backup.exists()) { // try { // wallet.wallet().saveToFile(backup); // } catch(IOException e) { // throw new RuntimeException(); // } // } // } // // public String getId() { return id; } // // public int getIndex() { return index; } // // public boolean supportsHashlock() { return hashlock; } // // public int getConfirmationDepth() { return confirmationDepth; } // // public String[] getPairs() { return pairs; } // // public boolean isSetup() { return setup; } // // public WalletAppKit getWallet() { return wallet; } // // public NetworkParameters getParams() { return params; } // // public ListenableFuture<Object> getSetupFuture() { return setupFuture; } // }
import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.coinswap.client.Currency; import io.mappum.altcoinj.core.*; import io.mappum.altcoinj.crypto.TransactionSignature; import io.mappum.altcoinj.script.Script; import io.mappum.altcoinj.script.ScriptBuilder; import io.mappum.altcoinj.utils.Threading; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Base64; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.mappum.altcoinj.script.ScriptOpCodes.OP_NOP;
package io.coinswap.swap; public abstract class AtomicSwapController { public static final int VERSION = 0; protected final AtomicSwap swap;
// Path: src/main/java/io/coinswap/client/Currency.java // public class Currency { // private static final Logger log = LoggerFactory.getLogger(Currency.class); // private static final File checkpointDir = new File("./checkpoints"); // // private static final int MIN_BROADCAST_CONNECTIONS = 5; // private static final int CONNECTIONS = 8; // // protected NetworkParameters params; // protected File directory; // protected WalletAppKit wallet; // protected String name, id, symbol; // protected String[] pairs; // protected int index; // protected boolean hashlock; // whether or not this coin can be used on the Alice-side of a swap // protected int confirmationDepth; // protected List<InetSocketAddress> connectPeers; // // private boolean setup; // private SettableFuture<Object> setupFuture; // // public Currency(NetworkParameters params, File directory, // String name, String id, String symbol, String[] pairs, // int index, boolean hashlock, int confirmationDepth) { // // this.params = params; // this.directory = directory; // this.name = name; // this.id = id; // this.symbol = symbol; // this.pairs = pairs; // this.index = index; // this.hashlock = hashlock; // this.confirmationDepth = confirmationDepth; // this.connectPeers = new ArrayList<InetSocketAddress>(0); // // setupFuture = SettableFuture.create(); // // // create the AltcoinJ wallet to interface with the currency // wallet = new WalletAppKit(params, directory, name.toLowerCase()) { // @Override // protected void onSetupCompleted() { // makeBackup(); // // peerGroup().setMaxConnections(CONNECTIONS); // peerGroup().setMinBroadcastConnections(1); // only require 1 peer in case we are connected to local peer // peerGroup().setFastCatchupTimeSecs(wallet.wallet().getEarliestKeyCreationTime()); // // // remove the re-add the wallet to the peergroup, so we will broadcast waiting transactions with the // // peergroup settings set correctly // peerGroup().removeWallet(wallet()); // peerGroup().addWallet(wallet()); // // for(InetSocketAddress peer : connectPeers) { // peerGroup().connectTo(peer); // } // // setup = true; // setupFuture.set(null); // } // }; // wallet.setUserAgent(Main.APP_NAME, Main.APP_VERSION); // wallet.setBlockingStartup(false); // // // load a checkpoint file (if it exists) to speed up initial blockchain sync // InputStream checkpointStream = Main.class.getResourceAsStream("/checkpoints/"+name.toLowerCase()+".txt"); // if(checkpointStream != null) { // wallet.setCheckpoints(checkpointStream); // } else { // log.info("No checkpoints found for " + name); // } // } // // public void broadcastTransaction(final Transaction tx) { // wallet.wallet().receivePending(tx, null); // // // broadcast even if we only have 1 peer (in case we are connected to localhost peer) // wallet.peerGroup().broadcastTransaction(tx, 1); // // also wait until we have MIN_BROADCAST_CONNECTIONS, then rebroadcast // wallet.peerGroup().broadcastTransaction(tx, MIN_BROADCAST_CONNECTIONS); // } // // public void start() { // wallet.startAsync(); // wallet.awaitRunning(); // } // // public void stop() { // wallet.stopAsync(); // wallet.awaitTerminated(); // } // // public void addConnectPeers(List<InetSocketAddress> peers) { // checkNotNull(peers); // this.connectPeers.addAll(peers); // } // // private void makeBackup() { // File backupDir = new File(directory, "backup"); // if(!backupDir.exists()) { // boolean success = backupDir.mkdir(); // if(!success) throw new RuntimeException(); // } // // File backup = new File(backupDir, name.toLowerCase()+".wallet"); // if(!backup.exists()) { // try { // wallet.wallet().saveToFile(backup); // } catch(IOException e) { // throw new RuntimeException(); // } // } // } // // public String getId() { return id; } // // public int getIndex() { return index; } // // public boolean supportsHashlock() { return hashlock; } // // public int getConfirmationDepth() { return confirmationDepth; } // // public String[] getPairs() { return pairs; } // // public boolean isSetup() { return setup; } // // public WalletAppKit getWallet() { return wallet; } // // public NetworkParameters getParams() { return params; } // // public ListenableFuture<Object> getSetupFuture() { return setupFuture; } // } // Path: src/main/java/io/coinswap/swap/AtomicSwapController.java import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.coinswap.client.Currency; import io.mappum.altcoinj.core.*; import io.mappum.altcoinj.crypto.TransactionSignature; import io.mappum.altcoinj.script.Script; import io.mappum.altcoinj.script.ScriptBuilder; import io.mappum.altcoinj.utils.Threading; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Base64; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static io.mappum.altcoinj.script.ScriptOpCodes.OP_NOP; package io.coinswap.swap; public abstract class AtomicSwapController { public static final int VERSION = 0; protected final AtomicSwap swap;
protected Currency[] currencies;
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/PatientDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/Patient.java // @Entity // public class Patient { // @Id // @GeneratedValue // private Long id; // // @Column(unique=true) // @Index(name = "rgh_ndx") // private Integer rgh; // // // bidirectional relationship // @OneToMany(mappedBy="rgh") // private List<RHC> rhc; // // // bidirectional relationship // @OneToMany(mappedBy="rgh") // private List<DCE> dce; // // // bidirectional relationship // @OneToMany(mappedBy="rgh") // private List<SighReport> sighReport; // // public Patient() { // } // // public Patient(Integer rgh) { // // this.rgh = rgh; // } // // public void addRHC(RHC rhc) { // rhc.setRgh(this); // if (this.rhc == null) // this.rhc = new ArrayList<RHC>(); // this.rhc.add(rhc); // } // // public void addDCE(DCE dce) { // dce.setRgh(this); // if (this.dce == null) // this.dce = new ArrayList<DCE>(); // this.dce.add(dce); // } // // public void addSighReport(SighReport report) { // report.setRgh(this); // if (this.sighReport == null) // this.sighReport = new ArrayList<SighReport>(); // this.sighReport.add(report); // } // // public Long getId() { // return id; // } // // public Integer getRgh() { // return rgh; // } // // public List<RHC> getRhc() { // return rhc; // } // // public List<RHC> getDistinctRhc() { // List<RHC> ret = new ArrayList<RHC>(); // Set<String> control = new HashSet<String>(); // String code; // for (RHC r : rhc) { // code = r.getIcdClass().getCode(); // if (!control.contains(code)) { // control.add(code); // ret.add(r); // } // } // return ret; // } // // /** // * // * @return // * @deprecated use getTexts instead. // */ // public List<DCE> getDce() { // return dce; // } // // /** // * // * @return // * @deprecated use getTexts instead. // */ // public List<SighReport> getSighReport() { // return sighReport; // } // // public List getTexts() { // switch (Constants.CONFIG.getSource()) { // case SIGH_REPORT: // return sighReport; // case DCE_REPORT: // return dce; // case ALL: // List<Report> all = new ArrayList<Report>(sighReport); // all.addAll(dce); // return all; // case TOTLAUD_REPORT: // // TODO // default: // return null; // } // } // // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.Patient;
package br.usp.ime.icdc.dao; public class PatientDAO { private Session session; // public static final String USER_ENTITY = Patient.class.getName(); public PatientDAO(Session session) { this.session = session; }
// Path: src/main/java/br/usp/ime/icdc/model/Patient.java // @Entity // public class Patient { // @Id // @GeneratedValue // private Long id; // // @Column(unique=true) // @Index(name = "rgh_ndx") // private Integer rgh; // // // bidirectional relationship // @OneToMany(mappedBy="rgh") // private List<RHC> rhc; // // // bidirectional relationship // @OneToMany(mappedBy="rgh") // private List<DCE> dce; // // // bidirectional relationship // @OneToMany(mappedBy="rgh") // private List<SighReport> sighReport; // // public Patient() { // } // // public Patient(Integer rgh) { // // this.rgh = rgh; // } // // public void addRHC(RHC rhc) { // rhc.setRgh(this); // if (this.rhc == null) // this.rhc = new ArrayList<RHC>(); // this.rhc.add(rhc); // } // // public void addDCE(DCE dce) { // dce.setRgh(this); // if (this.dce == null) // this.dce = new ArrayList<DCE>(); // this.dce.add(dce); // } // // public void addSighReport(SighReport report) { // report.setRgh(this); // if (this.sighReport == null) // this.sighReport = new ArrayList<SighReport>(); // this.sighReport.add(report); // } // // public Long getId() { // return id; // } // // public Integer getRgh() { // return rgh; // } // // public List<RHC> getRhc() { // return rhc; // } // // public List<RHC> getDistinctRhc() { // List<RHC> ret = new ArrayList<RHC>(); // Set<String> control = new HashSet<String>(); // String code; // for (RHC r : rhc) { // code = r.getIcdClass().getCode(); // if (!control.contains(code)) { // control.add(code); // ret.add(r); // } // } // return ret; // } // // /** // * // * @return // * @deprecated use getTexts instead. // */ // public List<DCE> getDce() { // return dce; // } // // /** // * // * @return // * @deprecated use getTexts instead. // */ // public List<SighReport> getSighReport() { // return sighReport; // } // // public List getTexts() { // switch (Constants.CONFIG.getSource()) { // case SIGH_REPORT: // return sighReport; // case DCE_REPORT: // return dce; // case ALL: // List<Report> all = new ArrayList<Report>(sighReport); // all.addAll(dce); // return all; // case TOTLAUD_REPORT: // // TODO // default: // return null; // } // } // // } // Path: src/main/java/br/usp/ime/icdc/dao/PatientDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.Patient; package br.usp.ime.icdc.dao; public class PatientDAO { private Session session; // public static final String USER_ENTITY = Patient.class.getName(); public PatientDAO(Session session) { this.session = session; }
public void save(Patient p) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/TopographyDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Topography.java // @Entity // public class Topography implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name="category_fk") // private TopographyCategory category; // // public Topography() { // // } // // public Topography(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyCategory getCategory() { // return category; // } // // public void setCategory(TopographyCategory category) { // this.category = category; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyDAO topoDao = factory.getTopographyDAO(); // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // // topoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // if (code.length() == 3) // code = "0" + code; // // TopographyCategory topoCategory = categoryDao.locate(code.substring(0, code.lastIndexOf('.'))); // if (topoCategory == null) { // System.err.println("Topography category not found! Code: " + code); // continue; // } // Topography t = new Topography(code, entry[1]); // topoCategory.addTopography(t); // topoDao.save(t); // } // topoDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Topography;
package br.usp.ime.icdc.dao; public class TopographyDAO implements ClassifiableDAO { private Session session; public TopographyDAO(Session session) { this.session = session; }
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Topography.java // @Entity // public class Topography implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name="category_fk") // private TopographyCategory category; // // public Topography() { // // } // // public Topography(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyCategory getCategory() { // return category; // } // // public void setCategory(TopographyCategory category) { // this.category = category; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyDAO topoDao = factory.getTopographyDAO(); // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // // topoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // if (code.length() == 3) // code = "0" + code; // // TopographyCategory topoCategory = categoryDao.locate(code.substring(0, code.lastIndexOf('.'))); // if (topoCategory == null) { // System.err.println("Topography category not found! Code: " + code); // continue; // } // Topography t = new Topography(code, entry[1]); // topoCategory.addTopography(t); // topoDao.save(t); // } // topoDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/TopographyDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Topography; package br.usp.ime.icdc.dao; public class TopographyDAO implements ClassifiableDAO { private Session session; public TopographyDAO(Session session) { this.session = session; }
public void save(Topography t) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/TopographyDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Topography.java // @Entity // public class Topography implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name="category_fk") // private TopographyCategory category; // // public Topography() { // // } // // public Topography(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyCategory getCategory() { // return category; // } // // public void setCategory(TopographyCategory category) { // this.category = category; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyDAO topoDao = factory.getTopographyDAO(); // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // // topoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // if (code.length() == 3) // code = "0" + code; // // TopographyCategory topoCategory = categoryDao.locate(code.substring(0, code.lastIndexOf('.'))); // if (topoCategory == null) { // System.err.println("Topography category not found! Code: " + code); // continue; // } // Topography t = new Topography(code, entry[1]); // topoCategory.addTopography(t); // topoDao.save(t); // } // topoDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Topography;
this.session.delete(t); } public Topography load(Long id) { return (Topography) this.session.load(Topography.class, id); } public Topography locate(String code) { return (Topography) this.session.createCriteria(Topography.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(Topography t) { this.session.update(t); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Topography.java // @Entity // public class Topography implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name="category_fk") // private TopographyCategory category; // // public Topography() { // // } // // public Topography(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyCategory getCategory() { // return category; // } // // public void setCategory(TopographyCategory category) { // this.category = category; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyDAO topoDao = factory.getTopographyDAO(); // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // // topoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // if (code.length() == 3) // code = "0" + code; // // TopographyCategory topoCategory = categoryDao.locate(code.substring(0, code.lastIndexOf('.'))); // if (topoCategory == null) { // System.err.println("Topography category not found! Code: " + code); // continue; // } // Topography t = new Topography(code, entry[1]); // topoCategory.addTopography(t); // topoDao.save(t); // } // topoDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/TopographyDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Topography; this.session.delete(t); } public Topography load(Long id) { return (Topography) this.session.load(Topography.class, id); } public Topography locate(String code) { return (Topography) this.session.createCriteria(Topography.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(Topography t) { this.session.update(t); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
public List<Classifiable> list() {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/model/Patient.java
// Path: src/main/java/br/usp/ime/icdc/Constants.java // public class Constants { // // public static final int THREADS = 1; // public static final int CONNECTIONS = THREADS * 2; // // // TODO change to something better, maybe setting automatically on the main method. // public static final boolean RECREATE_DB = true; // public static final int BATCH_SIZE = 100; // // // TODO move to a config file // /** Root directory where reference tables are located. */ // public static final String REF_DIR = "src/ref/"; // // /** Directory containing large data files. */ // public static final String DATA_DIR = "src/data/"; // // // TODO defined in models.xml for CoGrOO implementation. May not be necessary. // /** Directory containing models (e.g. OpenNLP models). */ // public static final String MODEL_DIR = "src/models/"; // // /** Defines if a cache of instances is used or not. */ // public static final boolean CACHE = false; // // /** Indicates wheter to generate stats or not. */ // public static final boolean STATS = false; // // public static final float TEST_RATIO = 0.1f; // // public static final int THRESHOLD = 10; // // // TODO move to a class smoothing or something // public static final double ALPHA = 0.5d; // // public static Configuration CONFIG; // // }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import org.hibernate.annotations.Index; import br.usp.ime.icdc.Constants;
String code; for (RHC r : rhc) { code = r.getIcdClass().getCode(); if (!control.contains(code)) { control.add(code); ret.add(r); } } return ret; } /** * * @return * @deprecated use getTexts instead. */ public List<DCE> getDce() { return dce; } /** * * @return * @deprecated use getTexts instead. */ public List<SighReport> getSighReport() { return sighReport; } public List getTexts() {
// Path: src/main/java/br/usp/ime/icdc/Constants.java // public class Constants { // // public static final int THREADS = 1; // public static final int CONNECTIONS = THREADS * 2; // // // TODO change to something better, maybe setting automatically on the main method. // public static final boolean RECREATE_DB = true; // public static final int BATCH_SIZE = 100; // // // TODO move to a config file // /** Root directory where reference tables are located. */ // public static final String REF_DIR = "src/ref/"; // // /** Directory containing large data files. */ // public static final String DATA_DIR = "src/data/"; // // // TODO defined in models.xml for CoGrOO implementation. May not be necessary. // /** Directory containing models (e.g. OpenNLP models). */ // public static final String MODEL_DIR = "src/models/"; // // /** Defines if a cache of instances is used or not. */ // public static final boolean CACHE = false; // // /** Indicates wheter to generate stats or not. */ // public static final boolean STATS = false; // // public static final float TEST_RATIO = 0.1f; // // public static final int THRESHOLD = 10; // // // TODO move to a class smoothing or something // public static final double ALPHA = 0.5d; // // public static Configuration CONFIG; // // } // Path: src/main/java/br/usp/ime/icdc/model/Patient.java import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import org.hibernate.annotations.Index; import br.usp.ime.icdc.Constants; String code; for (RHC r : rhc) { code = r.getIcdClass().getCode(); if (!control.contains(code)) { control.add(code); ret.add(r); } } return ret; } /** * * @return * @deprecated use getTexts instead. */ public List<DCE> getDce() { return dce; } /** * * @return * @deprecated use getTexts instead. */ public List<SighReport> getSighReport() { return sighReport; } public List getTexts() {
switch (Constants.CONFIG.getSource()) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/MorphologyGroupDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/MorphologyGroup.java // @Entity // public class MorphologyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<Morphology> morphology; // // public MorphologyGroup() { // // } // // public MorphologyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addMorphology(Morphology m) { // m.setGroup(this); // if (this.morphology == null) // this.morphology = new ArrayList<Morphology>(); // this.morphology.add(m); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // String toStr = code.substring(hyphenIndex+1); // Integer to = Integer.parseInt(toStr + "9"); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(0, hyphenIndex) + "0"); // else // from = Integer.parseInt(toStr + "0"); // // MorphologyGroup m = new MorphologyGroup(code, entry[1], from, to); // groupDao.save(m); // } // groupDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.MorphologyGroup;
package br.usp.ime.icdc.dao; public class MorphologyGroupDAO implements ClassifiableDAO { private Session session; public MorphologyGroupDAO(Session session) { this.session = session; }
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/MorphologyGroup.java // @Entity // public class MorphologyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<Morphology> morphology; // // public MorphologyGroup() { // // } // // public MorphologyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addMorphology(Morphology m) { // m.setGroup(this); // if (this.morphology == null) // this.morphology = new ArrayList<Morphology>(); // this.morphology.add(m); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // String toStr = code.substring(hyphenIndex+1); // Integer to = Integer.parseInt(toStr + "9"); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(0, hyphenIndex) + "0"); // else // from = Integer.parseInt(toStr + "0"); // // MorphologyGroup m = new MorphologyGroup(code, entry[1], from, to); // groupDao.save(m); // } // groupDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/MorphologyGroupDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.MorphologyGroup; package br.usp.ime.icdc.dao; public class MorphologyGroupDAO implements ClassifiableDAO { private Session session; public MorphologyGroupDAO(Session session) { this.session = session; }
public void save(MorphologyGroup m) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/MorphologyGroupDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/MorphologyGroup.java // @Entity // public class MorphologyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<Morphology> morphology; // // public MorphologyGroup() { // // } // // public MorphologyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addMorphology(Morphology m) { // m.setGroup(this); // if (this.morphology == null) // this.morphology = new ArrayList<Morphology>(); // this.morphology.add(m); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // String toStr = code.substring(hyphenIndex+1); // Integer to = Integer.parseInt(toStr + "9"); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(0, hyphenIndex) + "0"); // else // from = Integer.parseInt(toStr + "0"); // // MorphologyGroup m = new MorphologyGroup(code, entry[1], from, to); // groupDao.save(m); // } // groupDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.MorphologyGroup;
return (MorphologyGroup) this.session .createCriteria(MorphologyGroup.class) .add(Restrictions.le("startCode", search)) .add(Restrictions.ge("endCode", search)).uniqueResult(); } public MorphologyGroup locateCode(String code) { return (MorphologyGroup) this.session .createCriteria(MorphologyGroup.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(MorphologyGroup m) { this.session.update(m); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/MorphologyGroup.java // @Entity // public class MorphologyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<Morphology> morphology; // // public MorphologyGroup() { // // } // // public MorphologyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addMorphology(Morphology m) { // m.setGroup(this); // if (this.morphology == null) // this.morphology = new ArrayList<Morphology>(); // this.morphology.add(m); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // String toStr = code.substring(hyphenIndex+1); // Integer to = Integer.parseInt(toStr + "9"); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(0, hyphenIndex) + "0"); // else // from = Integer.parseInt(toStr + "0"); // // MorphologyGroup m = new MorphologyGroup(code, entry[1], from, to); // groupDao.save(m); // } // groupDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/MorphologyGroupDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.MorphologyGroup; return (MorphologyGroup) this.session .createCriteria(MorphologyGroup.class) .add(Restrictions.le("startCode", search)) .add(Restrictions.ge("endCode", search)).uniqueResult(); } public MorphologyGroup locateCode(String code) { return (MorphologyGroup) this.session .createCriteria(MorphologyGroup.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(MorphologyGroup m) { this.session.update(m); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
public List<Classifiable> list() {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/TopographyCategoryDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyCategory.java // @Entity // public class TopographyCategory implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private TopographyGroup group; // // // bidirectional relationship // @OneToMany(mappedBy = "category") // private List<Topography> topography; // // public TopographyCategory() { // // } // // public TopographyCategory(String code, String description) { // this.code = code; // this.description = description; // } // // public void addTopography(Topography t) { // t.setCategory(this); // if (this.topography == null) // this.topography = new ArrayList<Topography>(); // this.topography.add(t); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyGroup getGroup() { // return group; // } // // public void setGroup(TopographyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // categoryDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // TopographyGroup topoGroup = groupDao.locate(code); // if (topoGroup == null) { // System.err.println("Topography group not found! Code: " + code); // continue; // } // TopographyCategory tc = new TopographyCategory(code, entry[1]); // topoGroup.addTopographyCategory(tc); // categoryDao.save(tc); // } // categoryDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyCategory;
package br.usp.ime.icdc.dao; public class TopographyCategoryDAO implements ClassifiableDAO { private Session session; public TopographyCategoryDAO(Session session) { this.session = session; }
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyCategory.java // @Entity // public class TopographyCategory implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private TopographyGroup group; // // // bidirectional relationship // @OneToMany(mappedBy = "category") // private List<Topography> topography; // // public TopographyCategory() { // // } // // public TopographyCategory(String code, String description) { // this.code = code; // this.description = description; // } // // public void addTopography(Topography t) { // t.setCategory(this); // if (this.topography == null) // this.topography = new ArrayList<Topography>(); // this.topography.add(t); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyGroup getGroup() { // return group; // } // // public void setGroup(TopographyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // categoryDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // TopographyGroup topoGroup = groupDao.locate(code); // if (topoGroup == null) { // System.err.println("Topography group not found! Code: " + code); // continue; // } // TopographyCategory tc = new TopographyCategory(code, entry[1]); // topoGroup.addTopographyCategory(tc); // categoryDao.save(tc); // } // categoryDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/TopographyCategoryDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyCategory; package br.usp.ime.icdc.dao; public class TopographyCategoryDAO implements ClassifiableDAO { private Session session; public TopographyCategoryDAO(Session session) { this.session = session; }
public void save(TopographyCategory t) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/TopographyCategoryDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyCategory.java // @Entity // public class TopographyCategory implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private TopographyGroup group; // // // bidirectional relationship // @OneToMany(mappedBy = "category") // private List<Topography> topography; // // public TopographyCategory() { // // } // // public TopographyCategory(String code, String description) { // this.code = code; // this.description = description; // } // // public void addTopography(Topography t) { // t.setCategory(this); // if (this.topography == null) // this.topography = new ArrayList<Topography>(); // this.topography.add(t); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyGroup getGroup() { // return group; // } // // public void setGroup(TopographyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // categoryDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // TopographyGroup topoGroup = groupDao.locate(code); // if (topoGroup == null) { // System.err.println("Topography group not found! Code: " + code); // continue; // } // TopographyCategory tc = new TopographyCategory(code, entry[1]); // topoGroup.addTopographyCategory(tc); // categoryDao.save(tc); // } // categoryDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyCategory;
this.session.delete(t); } public TopographyCategory load(Long id) { return (TopographyCategory) this.session.load(TopographyCategory.class, id); } public TopographyCategory locate(String code) { return (TopographyCategory) this.session.createCriteria(TopographyCategory.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(TopographyCategory t) { this.session.update(t); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyCategory.java // @Entity // public class TopographyCategory implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private TopographyGroup group; // // // bidirectional relationship // @OneToMany(mappedBy = "category") // private List<Topography> topography; // // public TopographyCategory() { // // } // // public TopographyCategory(String code, String description) { // this.code = code; // this.description = description; // } // // public void addTopography(Topography t) { // t.setCategory(this); // if (this.topography == null) // this.topography = new ArrayList<Topography>(); // this.topography.add(t); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public TopographyGroup getGroup() { // return group; // } // // public void setGroup(TopographyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyCategoryDAO categoryDao = factory.getTopographyCategoryDAO(); // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // categoryDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // TopographyGroup topoGroup = groupDao.locate(code); // if (topoGroup == null) { // System.err.println("Topography group not found! Code: " + code); // continue; // } // TopographyCategory tc = new TopographyCategory(code, entry[1]); // topoGroup.addTopographyCategory(tc); // categoryDao.save(tc); // } // categoryDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/TopographyCategoryDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyCategory; this.session.delete(t); } public TopographyCategory load(Long id) { return (TopographyCategory) this.session.load(TopographyCategory.class, id); } public TopographyCategory locate(String code) { return (TopographyCategory) this.session.createCriteria(TopographyCategory.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(TopographyCategory t) { this.session.update(t); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
public List<Classifiable> list() {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/MorphologyDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Morphology.java // @Entity // public class Morphology implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private MorphologyGroup group; // // public Morphology() { // // } // // public Morphology(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public MorphologyGroup getGroup() { // return group; // } // // public void setGroup(MorphologyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyDAO morphoDao = factory.getMorphologyDAO(); // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // // XXX no carregamento de morfologia, considerar apenas terceira revisão. ver se funciona com RHC. // // morphoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // MorphologyGroup morphoGroup = groupDao.locate(code); // if (morphoGroup == null) { // System.err.println("Morphology group not found! Code: " + code); // continue; // } // Morphology m = new Morphology(code, entry[1]); // morphoGroup.addMorphology(m); // morphoDao.save(m); // } // morphoDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Morphology;
package br.usp.ime.icdc.dao; public class MorphologyDAO implements ClassifiableDAO { private Session session; public MorphologyDAO(Session session) { this.session = session; }
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Morphology.java // @Entity // public class Morphology implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private MorphologyGroup group; // // public Morphology() { // // } // // public Morphology(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public MorphologyGroup getGroup() { // return group; // } // // public void setGroup(MorphologyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyDAO morphoDao = factory.getMorphologyDAO(); // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // // XXX no carregamento de morfologia, considerar apenas terceira revisão. ver se funciona com RHC. // // morphoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // MorphologyGroup morphoGroup = groupDao.locate(code); // if (morphoGroup == null) { // System.err.println("Morphology group not found! Code: " + code); // continue; // } // Morphology m = new Morphology(code, entry[1]); // morphoGroup.addMorphology(m); // morphoDao.save(m); // } // morphoDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/MorphologyDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Morphology; package br.usp.ime.icdc.dao; public class MorphologyDAO implements ClassifiableDAO { private Session session; public MorphologyDAO(Session session) { this.session = session; }
public void save(Morphology m) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/MorphologyDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Morphology.java // @Entity // public class Morphology implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private MorphologyGroup group; // // public Morphology() { // // } // // public Morphology(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public MorphologyGroup getGroup() { // return group; // } // // public void setGroup(MorphologyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyDAO morphoDao = factory.getMorphologyDAO(); // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // // XXX no carregamento de morfologia, considerar apenas terceira revisão. ver se funciona com RHC. // // morphoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // MorphologyGroup morphoGroup = groupDao.locate(code); // if (morphoGroup == null) { // System.err.println("Morphology group not found! Code: " + code); // continue; // } // Morphology m = new Morphology(code, entry[1]); // morphoGroup.addMorphology(m); // morphoDao.save(m); // } // morphoDao.commit(); // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Morphology;
this.session.delete(m); } public Morphology load(Long id) { return (Morphology) this.session.load(Morphology.class, id); } public Morphology locate(String code) { return (Morphology) this.session.createCriteria(Morphology.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(Morphology m) { this.session.update(m); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/Morphology.java // @Entity // public class Morphology implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // // bidirectional relationship // @ManyToOne // @JoinColumn(name = "group_fk") // private MorphologyGroup group; // // public Morphology() { // // } // // public Morphology(String code, String description) { // this.code = code; // this.description = description; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public MorphologyGroup getGroup() { // return group; // } // // public void setGroup(MorphologyGroup group) { // this.group = group; // } // // public static void loadFromFile(File file) { // // TODO use reflection to populate object fields accordingly? // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // MorphologyDAO morphoDao = factory.getMorphologyDAO(); // MorphologyGroupDAO groupDao = factory.getMorphologyGroupDAO(); // // // XXX no carregamento de morfologia, considerar apenas terceira revisão. ver se funciona com RHC. // // morphoDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // MorphologyGroup morphoGroup = groupDao.locate(code); // if (morphoGroup == null) { // System.err.println("Morphology group not found! Code: " + code); // continue; // } // Morphology m = new Morphology(code, entry[1]); // morphoGroup.addMorphology(m); // morphoDao.save(m); // } // morphoDao.commit(); // } // } // Path: src/main/java/br/usp/ime/icdc/dao/MorphologyDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.Morphology; this.session.delete(m); } public Morphology load(Long id) { return (Morphology) this.session.load(Morphology.class, id); } public Morphology locate(String code) { return (Morphology) this.session.createCriteria(Morphology.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(Morphology m) { this.session.update(m); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
public List<Classifiable> list() {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/logic/weka/nlp/OpenNLPTokenizer.java
// Path: src/main/java/br/usp/ime/icdc/Constants.java // public class Constants { // // public static final int THREADS = 1; // public static final int CONNECTIONS = THREADS * 2; // // // TODO change to something better, maybe setting automatically on the main method. // public static final boolean RECREATE_DB = true; // public static final int BATCH_SIZE = 100; // // // TODO move to a config file // /** Root directory where reference tables are located. */ // public static final String REF_DIR = "src/ref/"; // // /** Directory containing large data files. */ // public static final String DATA_DIR = "src/data/"; // // // TODO defined in models.xml for CoGrOO implementation. May not be necessary. // /** Directory containing models (e.g. OpenNLP models). */ // public static final String MODEL_DIR = "src/models/"; // // /** Defines if a cache of instances is used or not. */ // public static final boolean CACHE = false; // // /** Indicates wheter to generate stats or not. */ // public static final boolean STATS = false; // // public static final float TEST_RATIO = 0.1f; // // public static final int THRESHOLD = 10; // // // TODO move to a class smoothing or something // public static final double ALPHA = 0.5d; // // public static Configuration CONFIG; // // }
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import br.usp.ime.icdc.Constants; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.tokenize.TokenizerME; import opennlp.tools.tokenize.TokenizerModel;
package br.usp.ime.icdc.logic.weka.nlp; /** * * @author michel * @version 1.0 */ public class OpenNLPTokenizer extends weka.core.tokenizers.Tokenizer { private Tokenizer tokenizer = null; private String[] tokens = null; private int pos = 0; public OpenNLPTokenizer() {
// Path: src/main/java/br/usp/ime/icdc/Constants.java // public class Constants { // // public static final int THREADS = 1; // public static final int CONNECTIONS = THREADS * 2; // // // TODO change to something better, maybe setting automatically on the main method. // public static final boolean RECREATE_DB = true; // public static final int BATCH_SIZE = 100; // // // TODO move to a config file // /** Root directory where reference tables are located. */ // public static final String REF_DIR = "src/ref/"; // // /** Directory containing large data files. */ // public static final String DATA_DIR = "src/data/"; // // // TODO defined in models.xml for CoGrOO implementation. May not be necessary. // /** Directory containing models (e.g. OpenNLP models). */ // public static final String MODEL_DIR = "src/models/"; // // /** Defines if a cache of instances is used or not. */ // public static final boolean CACHE = false; // // /** Indicates wheter to generate stats or not. */ // public static final boolean STATS = false; // // public static final float TEST_RATIO = 0.1f; // // public static final int THRESHOLD = 10; // // // TODO move to a class smoothing or something // public static final double ALPHA = 0.5d; // // public static Configuration CONFIG; // // } // Path: src/main/java/br/usp/ime/icdc/logic/weka/nlp/OpenNLPTokenizer.java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import br.usp.ime.icdc.Constants; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.tokenize.TokenizerME; import opennlp.tools.tokenize.TokenizerModel; package br.usp.ime.icdc.logic.weka.nlp; /** * * @author michel * @version 1.0 */ public class OpenNLPTokenizer extends weka.core.tokenizers.Tokenizer { private Tokenizer tokenizer = null; private String[] tokens = null; private int pos = 0; public OpenNLPTokenizer() {
String modelsDir = Constants.MODEL_DIR;
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/TopographyGroupDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyGroup.java // @Entity // public class TopographyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<TopographyCategory> category; // // public TopographyGroup() { // // } // // public TopographyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addTopographyCategory(TopographyCategory tc) { // tc.setGroup(this); // if (this.category == null) // this.category = new ArrayList<TopographyCategory>(); // this.category.add(tc); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // Integer to = Integer.parseInt(code.substring(hyphenIndex+2)); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(1, hyphenIndex)); // else // from = to; // // TopographyGroup t = new TopographyGroup(code, entry[1], from, to); // groupDao.save(t); // } // groupDao.commit(); // } // // @Override // public String toString() { // return "TopographyGroup [id=" + id + ", code=" + code // + ", description=" + description + ", startCode=" + startCode // + ", endCode=" + endCode + "]"; // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyGroup;
package br.usp.ime.icdc.dao; public class TopographyGroupDAO implements ClassifiableDAO { private Session session; public TopographyGroupDAO(Session session) { this.session = session; }
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyGroup.java // @Entity // public class TopographyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<TopographyCategory> category; // // public TopographyGroup() { // // } // // public TopographyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addTopographyCategory(TopographyCategory tc) { // tc.setGroup(this); // if (this.category == null) // this.category = new ArrayList<TopographyCategory>(); // this.category.add(tc); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // Integer to = Integer.parseInt(code.substring(hyphenIndex+2)); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(1, hyphenIndex)); // else // from = to; // // TopographyGroup t = new TopographyGroup(code, entry[1], from, to); // groupDao.save(t); // } // groupDao.commit(); // } // // @Override // public String toString() { // return "TopographyGroup [id=" + id + ", code=" + code // + ", description=" + description + ", startCode=" + startCode // + ", endCode=" + endCode + "]"; // } // } // Path: src/main/java/br/usp/ime/icdc/dao/TopographyGroupDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyGroup; package br.usp.ime.icdc.dao; public class TopographyGroupDAO implements ClassifiableDAO { private Session session; public TopographyGroupDAO(Session session) { this.session = session; }
public void save(TopographyGroup t) {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/dao/TopographyGroupDAO.java
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyGroup.java // @Entity // public class TopographyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<TopographyCategory> category; // // public TopographyGroup() { // // } // // public TopographyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addTopographyCategory(TopographyCategory tc) { // tc.setGroup(this); // if (this.category == null) // this.category = new ArrayList<TopographyCategory>(); // this.category.add(tc); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // Integer to = Integer.parseInt(code.substring(hyphenIndex+2)); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(1, hyphenIndex)); // else // from = to; // // TopographyGroup t = new TopographyGroup(code, entry[1], from, to); // groupDao.save(t); // } // groupDao.commit(); // } // // @Override // public String toString() { // return "TopographyGroup [id=" + id + ", code=" + code // + ", description=" + description + ", startCode=" + startCode // + ", endCode=" + endCode + "]"; // } // }
import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyGroup;
return (TopographyGroup) this.session .createCriteria(TopographyGroup.class) .add(Restrictions.le("startCode", search)) .add(Restrictions.ge("endCode", search)).uniqueResult(); } public TopographyGroup locateCode(String code) { return (TopographyGroup) this.session .createCriteria(TopographyGroup.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(TopographyGroup t) { this.session.update(t); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
// Path: src/main/java/br/usp/ime/icdc/model/icd/Classifiable.java // public interface Classifiable { // public String getCode(); // } // // Path: src/main/java/br/usp/ime/icdc/model/icd/TopographyGroup.java // @Entity // public class TopographyGroup implements Classifiable { // @Id // @GeneratedValue // private Long id; // // @Column // @Index(name = "code_ndx") // private String code; // // @Column // private String description; // // @Column // @Index(name = "startcode_ndx") // private Integer startCode; // // @Column // @Index(name = "endcode_ndx") // private Integer endCode; // // // bidirectional relationship // @OneToMany(mappedBy="group") // private List<TopographyCategory> category; // // public TopographyGroup() { // // } // // public TopographyGroup(String code, String description, Integer from, Integer to) { // this.code = code; // this.description = description; // this.startCode = from; // this.endCode = to; // } // // public void addTopographyCategory(TopographyCategory tc) { // tc.setGroup(this); // if (this.category == null) // this.category = new ArrayList<TopographyCategory>(); // this.category.add(tc); // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public static void loadFromFile(File file) { // List<String[]> myEntries = null; // try { // CSVReader reader = new CSVReader(new InputStreamReader( // new FileInputStream(file), "UTF-8")); // myEntries = reader.readAll(); // reader.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // Iterator<String[]> iter = myEntries.iterator(); // iter.next(); // // DAOFactory factory = DAOFactory.getDAOFactory(); // // TopographyGroupDAO groupDao = factory.getTopographyGroupDAO(); // // groupDao.beginTransaction(); // while (iter.hasNext()) { // String[] entry = iter.next(); // String code = entry[0]; // // int hyphenIndex = code.lastIndexOf('-'); // Integer from = null; // Integer to = Integer.parseInt(code.substring(hyphenIndex+2)); // if (hyphenIndex != -1) // from = Integer.parseInt(code.substring(1, hyphenIndex)); // else // from = to; // // TopographyGroup t = new TopographyGroup(code, entry[1], from, to); // groupDao.save(t); // } // groupDao.commit(); // } // // @Override // public String toString() { // return "TopographyGroup [id=" + id + ", code=" + code // + ", description=" + description + ", startCode=" + startCode // + ", endCode=" + endCode + "]"; // } // } // Path: src/main/java/br/usp/ime/icdc/dao/TopographyGroupDAO.java import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import br.usp.ime.icdc.model.icd.Classifiable; import br.usp.ime.icdc.model.icd.TopographyGroup; return (TopographyGroup) this.session .createCriteria(TopographyGroup.class) .add(Restrictions.le("startCode", search)) .add(Restrictions.ge("endCode", search)).uniqueResult(); } public TopographyGroup locateCode(String code) { return (TopographyGroup) this.session .createCriteria(TopographyGroup.class) .add(Restrictions.eq("code", code)).uniqueResult(); } public void update(TopographyGroup t) { this.session.update(t); } public void beginTransaction() { this.session.beginTransaction(); } public void commit() { this.session.getTransaction().commit(); } public void flushAndClear() { this.session.flush(); this.session.clear(); } @SuppressWarnings("unchecked")
public List<Classifiable> list() {
michelole/ICDClassifier
src/main/java/br/usp/ime/icdc/logic/weka/nlp/OpenNLPSentenceDetector.java
// Path: src/main/java/br/usp/ime/icdc/Constants.java // public class Constants { // // public static final int THREADS = 1; // public static final int CONNECTIONS = THREADS * 2; // // // TODO change to something better, maybe setting automatically on the main method. // public static final boolean RECREATE_DB = true; // public static final int BATCH_SIZE = 100; // // // TODO move to a config file // /** Root directory where reference tables are located. */ // public static final String REF_DIR = "src/ref/"; // // /** Directory containing large data files. */ // public static final String DATA_DIR = "src/data/"; // // // TODO defined in models.xml for CoGrOO implementation. May not be necessary. // /** Directory containing models (e.g. OpenNLP models). */ // public static final String MODEL_DIR = "src/models/"; // // /** Defines if a cache of instances is used or not. */ // public static final boolean CACHE = false; // // /** Indicates wheter to generate stats or not. */ // public static final boolean STATS = false; // // public static final float TEST_RATIO = 0.1f; // // public static final int THRESHOLD = 10; // // // TODO move to a class smoothing or something // public static final double ALPHA = 0.5d; // // public static Configuration CONFIG; // // }
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import br.usp.ime.icdc.Constants; import opennlp.tools.sentdetect.SentenceDetector; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel;
package br.usp.ime.icdc.logic.weka.nlp; /** * OpenNLP sentence detector wrapper compatible with Weka API. * * @author michel * */ public class OpenNLPSentenceDetector extends br.usp.ime.icdc.logic.weka.nlp.SentenceDetector { private SentenceDetector sentenceDetector = null; private String[] sentences = null; private int pos = 0; public OpenNLPSentenceDetector() {
// Path: src/main/java/br/usp/ime/icdc/Constants.java // public class Constants { // // public static final int THREADS = 1; // public static final int CONNECTIONS = THREADS * 2; // // // TODO change to something better, maybe setting automatically on the main method. // public static final boolean RECREATE_DB = true; // public static final int BATCH_SIZE = 100; // // // TODO move to a config file // /** Root directory where reference tables are located. */ // public static final String REF_DIR = "src/ref/"; // // /** Directory containing large data files. */ // public static final String DATA_DIR = "src/data/"; // // // TODO defined in models.xml for CoGrOO implementation. May not be necessary. // /** Directory containing models (e.g. OpenNLP models). */ // public static final String MODEL_DIR = "src/models/"; // // /** Defines if a cache of instances is used or not. */ // public static final boolean CACHE = false; // // /** Indicates wheter to generate stats or not. */ // public static final boolean STATS = false; // // public static final float TEST_RATIO = 0.1f; // // public static final int THRESHOLD = 10; // // // TODO move to a class smoothing or something // public static final double ALPHA = 0.5d; // // public static Configuration CONFIG; // // } // Path: src/main/java/br/usp/ime/icdc/logic/weka/nlp/OpenNLPSentenceDetector.java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import br.usp.ime.icdc.Constants; import opennlp.tools.sentdetect.SentenceDetector; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; package br.usp.ime.icdc.logic.weka.nlp; /** * OpenNLP sentence detector wrapper compatible with Weka API. * * @author michel * */ public class OpenNLPSentenceDetector extends br.usp.ime.icdc.logic.weka.nlp.SentenceDetector { private SentenceDetector sentenceDetector = null; private String[] sentences = null; private int pos = 0; public OpenNLPSentenceDetector() {
String modelsDir = Constants.MODEL_DIR;
mmlevin/secu3droid
secu3droid/src/org/secu3/android/ParamActivity.java
// Path: secu3droid/src/org/secu3/android/api/io/Secu3Manager.java // public enum SECU3_TASK { // SECU3_NONE, SECU3_READ_SENSORS, SECU3_RAW_SENSORS, SECU3_READ_PARAMS, SECU3_READ_ERRORS, SECU3_READ_FW_INFO, SECU3_START_SENSOR_LOGGING, SECU3_STOP_SENSOR_LOGGING, SECU3_START_RAW_LOGGING, SECU3_STOP_RAW_LOGGING, SECU3_SET_LOG_MARKER_1, SECU3_SET_LOG_MARKER_2, SECU3_SET_LOG_MARKER_3 // } // // Path: secu3droid/src/org/secu3/android/api/utils/CustomNumberPickerDialog.java // public interface OnNumberPickerDialogAcceptListener { // void onNumberPickerDialogAccept (int itemId); // } // // Path: secu3droid/src/org/secu3/android/parameters/items/BaseParamItem.java // public interface OnParamItemChangeListener { // void onParamItemChange (BaseParamItem item); // }
import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import org.secu3.android.api.io.*; import org.secu3.android.api.io.Secu3Manager.SECU3_TASK; import org.secu3.android.api.utils.*; import org.secu3.android.api.utils.CustomNumberPickerDialog.OnNumberPickerDialogAcceptListener; import org.secu3.android.parameters.*; import org.secu3.android.parameters.items.*; import org.secu3.android.parameters.items.BaseParamItem.OnParamItemChangeListener; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener;
private CustomNumberPickerDialog dialog = null; private ReceiveMessages receiver = null; private SparseArray<Secu3Packet> Skeletons = null; private PacketUtils packetUtils = null; private int protocol_version = SettingsActivity.PROTOCOL_UNKNOWN; public class ReceiveMessages extends BroadcastReceiver { public IntentFilter intentFilter = null; public ReceiveMessages() { intentFilter = new IntentFilter(); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_STATUS_ONLINE); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_PROGRESS); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_PACKET); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_PARAMETER); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_SKELETON_PACKET); } @Override public void onReceive(Context context, Intent intent) { update(intent); } } private void paramsRead() { progressBar.setVisibility(ProgressBar.VISIBLE);
// Path: secu3droid/src/org/secu3/android/api/io/Secu3Manager.java // public enum SECU3_TASK { // SECU3_NONE, SECU3_READ_SENSORS, SECU3_RAW_SENSORS, SECU3_READ_PARAMS, SECU3_READ_ERRORS, SECU3_READ_FW_INFO, SECU3_START_SENSOR_LOGGING, SECU3_STOP_SENSOR_LOGGING, SECU3_START_RAW_LOGGING, SECU3_STOP_RAW_LOGGING, SECU3_SET_LOG_MARKER_1, SECU3_SET_LOG_MARKER_2, SECU3_SET_LOG_MARKER_3 // } // // Path: secu3droid/src/org/secu3/android/api/utils/CustomNumberPickerDialog.java // public interface OnNumberPickerDialogAcceptListener { // void onNumberPickerDialogAccept (int itemId); // } // // Path: secu3droid/src/org/secu3/android/parameters/items/BaseParamItem.java // public interface OnParamItemChangeListener { // void onParamItemChange (BaseParamItem item); // } // Path: secu3droid/src/org/secu3/android/ParamActivity.java import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import org.secu3.android.api.io.*; import org.secu3.android.api.io.Secu3Manager.SECU3_TASK; import org.secu3.android.api.utils.*; import org.secu3.android.api.utils.CustomNumberPickerDialog.OnNumberPickerDialogAcceptListener; import org.secu3.android.parameters.*; import org.secu3.android.parameters.items.*; import org.secu3.android.parameters.items.BaseParamItem.OnParamItemChangeListener; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; private CustomNumberPickerDialog dialog = null; private ReceiveMessages receiver = null; private SparseArray<Secu3Packet> Skeletons = null; private PacketUtils packetUtils = null; private int protocol_version = SettingsActivity.PROTOCOL_UNKNOWN; public class ReceiveMessages extends BroadcastReceiver { public IntentFilter intentFilter = null; public ReceiveMessages() { intentFilter = new IntentFilter(); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_STATUS_ONLINE); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_PROGRESS); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_PACKET); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_PARAMETER); intentFilter.addAction(Secu3Service.EVENT_SECU3_SERVICE_RECEIVE_SKELETON_PACKET); } @Override public void onReceive(Context context, Intent intent) { update(intent); } } private void paramsRead() { progressBar.setVisibility(ProgressBar.VISIBLE);
startService(new Intent (Secu3Service.ACTION_SECU3_SERVICE_SET_TASK,Uri.EMPTY,this,Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM, SECU3_TASK.SECU3_READ_PARAMS.ordinal()));
mmlevin/secu3droid
secu3droid/src/org/secu3/android/api/io/Secu3ProtoWrapper.java
// Path: secu3droid/src/org/secu3/android/api/utils/ResourcesUtils.java // public class ResourcesUtils { // public static boolean isResource (String name) { // return name != null && name.matches("[@]\\d+"); // } // // public static int referenceToInt (String reference) { // if (reference == null) return 0; // return Integer.parseInt(reference.replace("@","")); // } // // public static String getReferenceString (Context context,String reference) { // if (reference == null) return null; // return context.getString(Integer.parseInt(reference.replace("@",""))); // } // // public static int getReferenceInt (Context context,String reference) { // if (reference == null) return 0; // return context.getResources().getInteger(Integer.parseInt(reference.replace("@",""))); // } // }
import org.secu3.android.R; import org.secu3.android.api.utils.ResourcesUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import java.io.IOException; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale;
String attrValue; NumberFormat format = NumberFormat.getInstance(Locale.US); try { XmlPullParser xpp = getContext().getResources().getXml(xmlId); inputPackets = new SparseArray<> (); outputPackets = new SparseArray<> (); while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { switch (xpp.getEventType()) { case XmlPullParser.START_TAG: name = xpp.getName(); if (name.equalsIgnoreCase(PROTOCOL)) { if (inputPackets.size() != 0) throw new IllegalArgumentException("Pages adapter is non empty, probably nested Protocol element"); if (outputPackets.size() != 0) throw new IllegalArgumentException("Pages adapter is non empty, probably nested Protocol element"); } else // Found new packet element if (name.equalsIgnoreCase(PACKET)) { String packetId = null; String packetName = null; String packetDir = null; int minVersion = protocolVersion; int maxVersion = protocolVersion; int count = xpp.getAttributeCount(); if (count > 0) { for (int i = 0; i != count; i++) { attr = xpp.getAttributeName(i); attrValue = xpp.getAttributeValue(i); switch (attr) { case NAME:
// Path: secu3droid/src/org/secu3/android/api/utils/ResourcesUtils.java // public class ResourcesUtils { // public static boolean isResource (String name) { // return name != null && name.matches("[@]\\d+"); // } // // public static int referenceToInt (String reference) { // if (reference == null) return 0; // return Integer.parseInt(reference.replace("@","")); // } // // public static String getReferenceString (Context context,String reference) { // if (reference == null) return null; // return context.getString(Integer.parseInt(reference.replace("@",""))); // } // // public static int getReferenceInt (Context context,String reference) { // if (reference == null) return 0; // return context.getResources().getInteger(Integer.parseInt(reference.replace("@",""))); // } // } // Path: secu3droid/src/org/secu3/android/api/io/Secu3ProtoWrapper.java import org.secu3.android.R; import org.secu3.android.api.utils.ResourcesUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import java.io.IOException; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; String attrValue; NumberFormat format = NumberFormat.getInstance(Locale.US); try { XmlPullParser xpp = getContext().getResources().getXml(xmlId); inputPackets = new SparseArray<> (); outputPackets = new SparseArray<> (); while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) { switch (xpp.getEventType()) { case XmlPullParser.START_TAG: name = xpp.getName(); if (name.equalsIgnoreCase(PROTOCOL)) { if (inputPackets.size() != 0) throw new IllegalArgumentException("Pages adapter is non empty, probably nested Protocol element"); if (outputPackets.size() != 0) throw new IllegalArgumentException("Pages adapter is non empty, probably nested Protocol element"); } else // Found new packet element if (name.equalsIgnoreCase(PACKET)) { String packetId = null; String packetName = null; String packetDir = null; int minVersion = protocolVersion; int maxVersion = protocolVersion; int count = xpp.getAttributeCount(); if (count > 0) { for (int i = 0; i != count; i++) { attr = xpp.getAttributeName(i); attrValue = xpp.getAttributeValue(i); switch (attr) { case NAME:
if (!ResourcesUtils.isResource(attrValue))
mmlevin/secu3droid
secu3droid/src/org/secu3/android/SettingsActivity.java
// Path: secu3droid/src/org/secu3/android/api/io/Secu3Logger.java // public abstract class Secu3Logger { // private static final String LOG_TAG = "Secu3Logger"; // // private GregorianCalendar time = null; // private BufferedWriter logWriter = null; // private boolean started = false; // private String path = null; // int protocol_version; // // void log (String log) { // try { // logWriter.write(log); // logWriter.flush(); // } catch (IOException e) { // Log.e(LOG_TAG,e.getMessage()); // } // } // // Secu3Logger() { // time = new GregorianCalendar(); // } // protected abstract String getFileName(); // // public void beginLogging (int protocol_version) { // this.protocol_version = protocol_version; // if (!isStarted()) try { // logWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path+File.separator+getFileName()),"ISO-8859-1")); // started = true; // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void endLogging() { // if (isStarted()) try { // logWriter.flush(); // logWriter.close(); // started = false; // } catch (IOException e) { // e.printStackTrace(); // } // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // if ((path == null) || (path.length() == 0)) path = Secu3Logger.getDefaultPath(); // this.path = path; // } // // public static String getDefaultPath() { // return Environment.getExternalStorageDirectory().getPath(); // } // // boolean isStarted() { // return started; // } // // GregorianCalendar getTime() { // return time; // } // // public void setTime(GregorianCalendar time) { // this.time = time; // } // }
import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.View; import android.widget.TextView; import java.util.HashSet; import java.util.Set; import org.secu3.android.api.io.Secu3Logger;
} catch (NullPointerException e) { e.printStackTrace(); } return ";"; } public static boolean isKeepScreenAliveActive (Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); return sharedPreferences.getBoolean(ctx.getString(R.string.pref_keep_screen_key), false); } public static boolean isWakeLockEnabled (Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); return sharedPreferences.getBoolean(ctx.getString(R.string.pref_wakelock_key), false); } @SuppressWarnings("deprecation") private void updatePreferenceSummary(){ String deviceName = ""; ListPreference prefDevices = (ListPreference)findPreference(getString(R.string.pref_bluetooth_device_key)); String deviceAddress = sharedPref.getString(getString(R.string.pref_bluetooth_device_key), null); if (BluetoothAdapter.checkBluetoothAddress(deviceAddress)){ deviceName = bluetoothAdapter.getRemoteDevice(deviceAddress).getName(); } prefDevices.setSummary(getString(R.string.pref_bluetooth_device_summary, deviceName)); String protocolVersion = versions[getProtocolVersion(this)-1]; ListPreference prefVersions = (ListPreference)findPreference(getString(R.string.pref_protocol_version_key)); prefVersions.setSummary(protocolVersion);
// Path: secu3droid/src/org/secu3/android/api/io/Secu3Logger.java // public abstract class Secu3Logger { // private static final String LOG_TAG = "Secu3Logger"; // // private GregorianCalendar time = null; // private BufferedWriter logWriter = null; // private boolean started = false; // private String path = null; // int protocol_version; // // void log (String log) { // try { // logWriter.write(log); // logWriter.flush(); // } catch (IOException e) { // Log.e(LOG_TAG,e.getMessage()); // } // } // // Secu3Logger() { // time = new GregorianCalendar(); // } // protected abstract String getFileName(); // // public void beginLogging (int protocol_version) { // this.protocol_version = protocol_version; // if (!isStarted()) try { // logWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path+File.separator+getFileName()),"ISO-8859-1")); // started = true; // } catch (IOException e) { // e.printStackTrace(); // } // } // // public void endLogging() { // if (isStarted()) try { // logWriter.flush(); // logWriter.close(); // started = false; // } catch (IOException e) { // e.printStackTrace(); // } // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // if ((path == null) || (path.length() == 0)) path = Secu3Logger.getDefaultPath(); // this.path = path; // } // // public static String getDefaultPath() { // return Environment.getExternalStorageDirectory().getPath(); // } // // boolean isStarted() { // return started; // } // // GregorianCalendar getTime() { // return time; // } // // public void setTime(GregorianCalendar time) { // this.time = time; // } // } // Path: secu3droid/src/org/secu3/android/SettingsActivity.java import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageInfo; import android.os.Build; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.View; import android.widget.TextView; import java.util.HashSet; import java.util.Set; import org.secu3.android.api.io.Secu3Logger; } catch (NullPointerException e) { e.printStackTrace(); } return ";"; } public static boolean isKeepScreenAliveActive (Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); return sharedPreferences.getBoolean(ctx.getString(R.string.pref_keep_screen_key), false); } public static boolean isWakeLockEnabled (Context ctx) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ctx); return sharedPreferences.getBoolean(ctx.getString(R.string.pref_wakelock_key), false); } @SuppressWarnings("deprecation") private void updatePreferenceSummary(){ String deviceName = ""; ListPreference prefDevices = (ListPreference)findPreference(getString(R.string.pref_bluetooth_device_key)); String deviceAddress = sharedPref.getString(getString(R.string.pref_bluetooth_device_key), null); if (BluetoothAdapter.checkBluetoothAddress(deviceAddress)){ deviceName = bluetoothAdapter.getRemoteDevice(deviceAddress).getName(); } prefDevices.setSummary(getString(R.string.pref_bluetooth_device_summary, deviceName)); String protocolVersion = versions[getProtocolVersion(this)-1]; ListPreference prefVersions = (ListPreference)findPreference(getString(R.string.pref_protocol_version_key)); prefVersions.setSummary(protocolVersion);
findPreference(getString(R.string.pref_write_log_path)).setSummary(String.format(getString(R.string.pref_write_log_path_summary), Secu3Logger.getDefaultPath()));
mmlevin/secu3droid
secu3droid/src/org/secu3/android/api/io/Secu3Service.java
// Path: secu3droid/src/org/secu3/android/api/io/Secu3Manager.java // public enum SECU3_TASK { // SECU3_NONE, SECU3_READ_SENSORS, SECU3_RAW_SENSORS, SECU3_READ_PARAMS, SECU3_READ_ERRORS, SECU3_READ_FW_INFO, SECU3_START_SENSOR_LOGGING, SECU3_STOP_SENSOR_LOGGING, SECU3_START_RAW_LOGGING, SECU3_STOP_RAW_LOGGING, SECU3_SET_LOG_MARKER_1, SECU3_SET_LOG_MARKER_2, SECU3_SET_LOG_MARKER_3 // }
import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import org.secu3.android.R; import org.secu3.android.api.io.Secu3Manager.SECU3_TASK; import android.app.NotificationManager; import android.app.Service;
stopSelf(); } } else { stopSelf(); } } else { secu3Notification.toast(R.string.msg_service_already_started); sendBroadcast(intent); } } else { secu3Notification.toast(R.string.msg_bluetooth_unsupported); stopSelf(); } } else if (ACTION_SECU3_SERVICE_STOP.equals(intent.getAction())){ Log.d(LOG_TAG, "Stopping service"); secu3Notification.notificationManager.cancelAll(); Secu3Manager manager = secu3Manager; secu3Manager = null; if (manager != null){ if (manager.getDisableReason() != 0){ secu3Notification.notifyServiceStopped(manager.getDisableReason()); secu3Notification.toast(getString(R.string.msg_service_stopped_by_problem, getString(manager.getDisableReason()))); } else { secu3Notification.toast(R.string.msg_service_stopped); } manager.disable(); } stopSelf(); System.exit(0); } else if (ACTION_SECU3_SERVICE_SET_TASK.equals(intent.getAction())) {
// Path: secu3droid/src/org/secu3/android/api/io/Secu3Manager.java // public enum SECU3_TASK { // SECU3_NONE, SECU3_READ_SENSORS, SECU3_RAW_SENSORS, SECU3_READ_PARAMS, SECU3_READ_ERRORS, SECU3_READ_FW_INFO, SECU3_START_SENSOR_LOGGING, SECU3_STOP_SENSOR_LOGGING, SECU3_START_RAW_LOGGING, SECU3_STOP_RAW_LOGGING, SECU3_SET_LOG_MARKER_1, SECU3_SET_LOG_MARKER_2, SECU3_SET_LOG_MARKER_3 // } // Path: secu3droid/src/org/secu3/android/api/io/Secu3Service.java import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import org.secu3.android.R; import org.secu3.android.api.io.Secu3Manager.SECU3_TASK; import android.app.NotificationManager; import android.app.Service; stopSelf(); } } else { stopSelf(); } } else { secu3Notification.toast(R.string.msg_service_already_started); sendBroadcast(intent); } } else { secu3Notification.toast(R.string.msg_bluetooth_unsupported); stopSelf(); } } else if (ACTION_SECU3_SERVICE_STOP.equals(intent.getAction())){ Log.d(LOG_TAG, "Stopping service"); secu3Notification.notificationManager.cancelAll(); Secu3Manager manager = secu3Manager; secu3Manager = null; if (manager != null){ if (manager.getDisableReason() != 0){ secu3Notification.notifyServiceStopped(manager.getDisableReason()); secu3Notification.toast(getString(R.string.msg_service_stopped_by_problem, getString(manager.getDisableReason()))); } else { secu3Notification.toast(R.string.msg_service_stopped); } manager.disable(); } stopSelf(); System.exit(0); } else if (ACTION_SECU3_SERVICE_SET_TASK.equals(intent.getAction())) {
SECU3_TASK task = SECU3_TASK.values()[intent.getIntExtra(ACTION_SECU3_SERVICE_SET_TASK_PARAM, SECU3_TASK.SECU3_NONE.ordinal())];
mmlevin/secu3droid
secu3droid/src/org/secu3/android/parameters/ParamsPage.java
// Path: secu3droid/src/org/secu3/android/parameters/items/BaseParamItem.java // public abstract class BaseParamItem { // private Context context = null; // private String name = null; // private int nameId = 0; // private String units = null; // private int unitsId = 0; // private String summary = null; // private int summaryId = 0; // private boolean enabled = true; // private int pageId = 0; // // public interface OnParamItemChangeListener { // void onParamItemChange (BaseParamItem item); // } // // protected OnParamItemChangeListener listener; // // protected View getView(int resourceID) { // LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // return inflater.inflate(resourceID, null); // } // // abstract public View getView(); // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUnits() { // return units; // } // // public void setUnits(String units) { // this.units = units; // } // // public String getSummary() { // return summary; // } // // public void setSummary(String summary) { // this.summary = summary; // } // // public int getNameId() { // return nameId; // } // // public void setNameId(int nameId) { // this.nameId = nameId; // } // // public int getUnitsId() { // return unitsId; // } // // public void setUnitsId(int unitsId) { // this.unitsId = unitsId; // } // // public int getSummaryId() { // return summaryId; // } // // public void setSummaryId(int summaryId) { // this.summaryId = summaryId; // } // // public void setOnParamItemChangeListener(OnParamItemChangeListener listener) { // this.listener = listener; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public int getPageId() { // return pageId; // } // // public void setPageId(int pageId) { // this.pageId = pageId; // } // }
import java.util.ArrayList; import org.secu3.android.parameters.items.BaseParamItem;
/* Secu3Droid - An open source, free manager for SECU-3 engine * control unit * Copyright (C) 2013 Maksim M. Levin. Russia, Voronezh * * SECU-3 - An open source, free engine control unit * Copyright (C) 2007 Alexey A. Shabelnikov. Ukraine, Gorlovka * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * contacts: * http://secu-3.org * email: mmlevin@mail.ru */ package org.secu3.android.parameters; public class ParamsPage { private int nameId = 0;
// Path: secu3droid/src/org/secu3/android/parameters/items/BaseParamItem.java // public abstract class BaseParamItem { // private Context context = null; // private String name = null; // private int nameId = 0; // private String units = null; // private int unitsId = 0; // private String summary = null; // private int summaryId = 0; // private boolean enabled = true; // private int pageId = 0; // // public interface OnParamItemChangeListener { // void onParamItemChange (BaseParamItem item); // } // // protected OnParamItemChangeListener listener; // // protected View getView(int resourceID) { // LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // return inflater.inflate(resourceID, null); // } // // abstract public View getView(); // // public Context getContext() { // return context; // } // // public void setContext(Context context) { // this.context = context; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUnits() { // return units; // } // // public void setUnits(String units) { // this.units = units; // } // // public String getSummary() { // return summary; // } // // public void setSummary(String summary) { // this.summary = summary; // } // // public int getNameId() { // return nameId; // } // // public void setNameId(int nameId) { // this.nameId = nameId; // } // // public int getUnitsId() { // return unitsId; // } // // public void setUnitsId(int unitsId) { // this.unitsId = unitsId; // } // // public int getSummaryId() { // return summaryId; // } // // public void setSummaryId(int summaryId) { // this.summaryId = summaryId; // } // // public void setOnParamItemChangeListener(OnParamItemChangeListener listener) { // this.listener = listener; // } // // public boolean isEnabled() { // return enabled; // } // // public void setEnabled(boolean enabled) { // this.enabled = enabled; // } // // public int getPageId() { // return pageId; // } // // public void setPageId(int pageId) { // this.pageId = pageId; // } // } // Path: secu3droid/src/org/secu3/android/parameters/ParamsPage.java import java.util.ArrayList; import org.secu3.android.parameters.items.BaseParamItem; /* Secu3Droid - An open source, free manager for SECU-3 engine * control unit * Copyright (C) 2013 Maksim M. Levin. Russia, Voronezh * * SECU-3 - An open source, free engine control unit * Copyright (C) 2007 Alexey A. Shabelnikov. Ukraine, Gorlovka * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * contacts: * http://secu-3.org * email: mmlevin@mail.ru */ package org.secu3.android.parameters; public class ParamsPage { private int nameId = 0;
private ArrayList<BaseParamItem> items = null;
packetpirate/Generic-Zombie-Shooter
GenericZombieShooter/src/genericzombieshooter/structures/Message.java
// Path: GenericZombieShooter/src/genericzombieshooter/misc/Globals.java // public class Globals { // // Game Information // public static final String VERSION = "1.0"; // public static final int W_WIDTH = 800; // The width of the game window. // public static final int W_HEIGHT = 640; // The height of the game window. // public static final long SLEEP_TIME = 20; // The sleep time of the animation thread. // public static final long WAVE_BREAK_TIME = 30 * 1000; // public static final Random r = new Random(); // public static List<Message> GAME_MESSAGES = new ArrayList<Message>(); // // // Zombie Information // public static final int ZOMBIE_REGULAR_TYPE = 1; // public static final long ZOMBIE_REGULAR_SPAWN = 1000; // public static final int ZOMBIE_DOG_TYPE = 2; // public static final long ZOMBIE_DOG_SPAWN = 10000; // public static final int ZOMBIE_ACID_TYPE = 3; // public static final long ZOMBIE_ACID_SPAWN = 30000; // public static final int ZOMBIE_POISONFOG_TYPE = 4; // public static final long ZOMBIE_POISONFOG_SPAWN = 20000; // public static final int ZOMBIE_MATRON_TYPE = 5; // public static final long ZOMBIE_MATRON_SPAWN = 50000; // public static final int ZOMBIE_TINY_TYPE = 6; // // // Boss Information // public static final int ZOMBIE_BOSS_ABERRATION_TYPE = 7; // public static final int ZOMBIE_BOSS_ZOMBAT_TYPE = 8; // public static final int ZOMBIE_BOSS_STITCHES_TYPE = 9; // // // Game-State Related // public static Runnable animation; // The primary animation thread. // public static GameTime gameTime; // Used to keep track of the time. // // public static boolean running; // Whether or not the game is currently running. // public static boolean started; // public static boolean crashed; // Tells the game whether or not there was a crash. // public static boolean paused; // public static boolean storeOpen; // public static boolean levelScreenOpen; // public static boolean deathScreen; // public static boolean waveInProgress; // Whether the player is fighting or waiting for another wave. // public static long nextWave; // // // Input Related // public static boolean [] keys; // The state of the game key controls. // public static boolean [] buttons; // The state of the game mouse button controls. // public static Point mousePos; // The current position of the mouse on the screen. // // // Static Weapons // public static Handgun HANDGUN = new Handgun(); // public static AssaultRifle ASSAULT_RIFLE = new AssaultRifle(); // public static Shotgun SHOTGUN = new Shotgun(); // public static Flamethrower FLAMETHROWER = new Flamethrower(); // public static Grenade GRENADE = new Grenade(); // public static Landmine LANDMINE = new Landmine(); // public static Flare FLARE = new Flare(); // public static LaserWire LASERWIRE = new LaserWire(); // public static TurretWeapon TURRETWEAPON = new TurretWeapon(); // public static Teleporter TELEPORTER = new Teleporter(); // // public static Weapon getWeaponByName(String name) { // if(name.equals(Globals.HANDGUN.getName())) return Globals.HANDGUN; // else if(name.equals(Globals.ASSAULT_RIFLE.getName())) return Globals.ASSAULT_RIFLE; // else if(name.equals(Globals.SHOTGUN.getName())) return Globals.SHOTGUN; // else if(name.equals(Globals.FLAMETHROWER.getName())) return Globals.FLAMETHROWER; // else if(name.equals(Globals.GRENADE.getName())) return Globals.GRENADE; // else if(name.equals(Globals.LANDMINE.getName())) return Globals.LANDMINE; // else if(name.equals(Globals.FLARE.getName())) return Globals.FLARE; // else if(name.equals(Globals.LASERWIRE.getName())) return Globals.LASERWIRE; // else if(name.equals(Globals.TURRETWEAPON.getName())) return Globals.TURRETWEAPON; // else if(name.equals(Globals.TELEPORTER.getName())) return Globals.TELEPORTER; // else return null; // } // // public static void resetWeapons() { // Globals.HANDGUN.resetAmmo(); // Globals.ASSAULT_RIFLE.resetAmmo(); // Globals.SHOTGUN.resetAmmo(); // Globals.FLAMETHROWER.resetAmmo(); // Globals.GRENADE.resetAmmo(); // Globals.LANDMINE.resetAmmo(); // Globals.FLARE.resetAmmo(); // Globals.LASERWIRE.resetAmmo(); // Globals.TURRETWEAPON.resetAmmo(); // Globals.TELEPORTER.resetAmmo(); // } // }
import genericzombieshooter.misc.Globals; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.geom.Point2D;
/** This file is part of Generic Zombie Shooter. Generic Zombie Shooter is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Generic Zombie Shooter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Generic Zombie Shooter. If not, see <http://www.gnu.org/licenses/>. **/ package genericzombieshooter.structures; /** * Used to display messages above the weapons loadout. * @author Darin Beaudreau */ public class Message { // Member Variables private String text; public String getText() { return this.text; } private long expirationTime; public Message(String text, long duration) { this.text = text;
// Path: GenericZombieShooter/src/genericzombieshooter/misc/Globals.java // public class Globals { // // Game Information // public static final String VERSION = "1.0"; // public static final int W_WIDTH = 800; // The width of the game window. // public static final int W_HEIGHT = 640; // The height of the game window. // public static final long SLEEP_TIME = 20; // The sleep time of the animation thread. // public static final long WAVE_BREAK_TIME = 30 * 1000; // public static final Random r = new Random(); // public static List<Message> GAME_MESSAGES = new ArrayList<Message>(); // // // Zombie Information // public static final int ZOMBIE_REGULAR_TYPE = 1; // public static final long ZOMBIE_REGULAR_SPAWN = 1000; // public static final int ZOMBIE_DOG_TYPE = 2; // public static final long ZOMBIE_DOG_SPAWN = 10000; // public static final int ZOMBIE_ACID_TYPE = 3; // public static final long ZOMBIE_ACID_SPAWN = 30000; // public static final int ZOMBIE_POISONFOG_TYPE = 4; // public static final long ZOMBIE_POISONFOG_SPAWN = 20000; // public static final int ZOMBIE_MATRON_TYPE = 5; // public static final long ZOMBIE_MATRON_SPAWN = 50000; // public static final int ZOMBIE_TINY_TYPE = 6; // // // Boss Information // public static final int ZOMBIE_BOSS_ABERRATION_TYPE = 7; // public static final int ZOMBIE_BOSS_ZOMBAT_TYPE = 8; // public static final int ZOMBIE_BOSS_STITCHES_TYPE = 9; // // // Game-State Related // public static Runnable animation; // The primary animation thread. // public static GameTime gameTime; // Used to keep track of the time. // // public static boolean running; // Whether or not the game is currently running. // public static boolean started; // public static boolean crashed; // Tells the game whether or not there was a crash. // public static boolean paused; // public static boolean storeOpen; // public static boolean levelScreenOpen; // public static boolean deathScreen; // public static boolean waveInProgress; // Whether the player is fighting or waiting for another wave. // public static long nextWave; // // // Input Related // public static boolean [] keys; // The state of the game key controls. // public static boolean [] buttons; // The state of the game mouse button controls. // public static Point mousePos; // The current position of the mouse on the screen. // // // Static Weapons // public static Handgun HANDGUN = new Handgun(); // public static AssaultRifle ASSAULT_RIFLE = new AssaultRifle(); // public static Shotgun SHOTGUN = new Shotgun(); // public static Flamethrower FLAMETHROWER = new Flamethrower(); // public static Grenade GRENADE = new Grenade(); // public static Landmine LANDMINE = new Landmine(); // public static Flare FLARE = new Flare(); // public static LaserWire LASERWIRE = new LaserWire(); // public static TurretWeapon TURRETWEAPON = new TurretWeapon(); // public static Teleporter TELEPORTER = new Teleporter(); // // public static Weapon getWeaponByName(String name) { // if(name.equals(Globals.HANDGUN.getName())) return Globals.HANDGUN; // else if(name.equals(Globals.ASSAULT_RIFLE.getName())) return Globals.ASSAULT_RIFLE; // else if(name.equals(Globals.SHOTGUN.getName())) return Globals.SHOTGUN; // else if(name.equals(Globals.FLAMETHROWER.getName())) return Globals.FLAMETHROWER; // else if(name.equals(Globals.GRENADE.getName())) return Globals.GRENADE; // else if(name.equals(Globals.LANDMINE.getName())) return Globals.LANDMINE; // else if(name.equals(Globals.FLARE.getName())) return Globals.FLARE; // else if(name.equals(Globals.LASERWIRE.getName())) return Globals.LASERWIRE; // else if(name.equals(Globals.TURRETWEAPON.getName())) return Globals.TURRETWEAPON; // else if(name.equals(Globals.TELEPORTER.getName())) return Globals.TELEPORTER; // else return null; // } // // public static void resetWeapons() { // Globals.HANDGUN.resetAmmo(); // Globals.ASSAULT_RIFLE.resetAmmo(); // Globals.SHOTGUN.resetAmmo(); // Globals.FLAMETHROWER.resetAmmo(); // Globals.GRENADE.resetAmmo(); // Globals.LANDMINE.resetAmmo(); // Globals.FLARE.resetAmmo(); // Globals.LASERWIRE.resetAmmo(); // Globals.TURRETWEAPON.resetAmmo(); // Globals.TELEPORTER.resetAmmo(); // } // } // Path: GenericZombieShooter/src/genericzombieshooter/structures/Message.java import genericzombieshooter.misc.Globals; import java.awt.AlphaComposite; import java.awt.Composite; import java.awt.Graphics2D; import java.awt.geom.Point2D; /** This file is part of Generic Zombie Shooter. Generic Zombie Shooter is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Generic Zombie Shooter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Generic Zombie Shooter. If not, see <http://www.gnu.org/licenses/>. **/ package genericzombieshooter.structures; /** * Used to display messages above the weapons loadout. * @author Darin Beaudreau */ public class Message { // Member Variables private String text; public String getText() { return this.text; } private long expirationTime; public Message(String text, long duration) { this.text = text;
this.expirationTime = Globals.gameTime.getElapsedMillis() + duration;
packetpirate/Generic-Zombie-Shooter
GenericZombieShooter/src/genericzombieshooter/structures/StatusEffect.java
// Path: GenericZombieShooter/src/genericzombieshooter/misc/Globals.java // public class Globals { // // Game Information // public static final String VERSION = "1.0"; // public static final int W_WIDTH = 800; // The width of the game window. // public static final int W_HEIGHT = 640; // The height of the game window. // public static final long SLEEP_TIME = 20; // The sleep time of the animation thread. // public static final long WAVE_BREAK_TIME = 30 * 1000; // public static final Random r = new Random(); // public static List<Message> GAME_MESSAGES = new ArrayList<Message>(); // // // Zombie Information // public static final int ZOMBIE_REGULAR_TYPE = 1; // public static final long ZOMBIE_REGULAR_SPAWN = 1000; // public static final int ZOMBIE_DOG_TYPE = 2; // public static final long ZOMBIE_DOG_SPAWN = 10000; // public static final int ZOMBIE_ACID_TYPE = 3; // public static final long ZOMBIE_ACID_SPAWN = 30000; // public static final int ZOMBIE_POISONFOG_TYPE = 4; // public static final long ZOMBIE_POISONFOG_SPAWN = 20000; // public static final int ZOMBIE_MATRON_TYPE = 5; // public static final long ZOMBIE_MATRON_SPAWN = 50000; // public static final int ZOMBIE_TINY_TYPE = 6; // // // Boss Information // public static final int ZOMBIE_BOSS_ABERRATION_TYPE = 7; // public static final int ZOMBIE_BOSS_ZOMBAT_TYPE = 8; // public static final int ZOMBIE_BOSS_STITCHES_TYPE = 9; // // // Game-State Related // public static Runnable animation; // The primary animation thread. // public static GameTime gameTime; // Used to keep track of the time. // // public static boolean running; // Whether or not the game is currently running. // public static boolean started; // public static boolean crashed; // Tells the game whether or not there was a crash. // public static boolean paused; // public static boolean storeOpen; // public static boolean levelScreenOpen; // public static boolean deathScreen; // public static boolean waveInProgress; // Whether the player is fighting or waiting for another wave. // public static long nextWave; // // // Input Related // public static boolean [] keys; // The state of the game key controls. // public static boolean [] buttons; // The state of the game mouse button controls. // public static Point mousePos; // The current position of the mouse on the screen. // // // Static Weapons // public static Handgun HANDGUN = new Handgun(); // public static AssaultRifle ASSAULT_RIFLE = new AssaultRifle(); // public static Shotgun SHOTGUN = new Shotgun(); // public static Flamethrower FLAMETHROWER = new Flamethrower(); // public static Grenade GRENADE = new Grenade(); // public static Landmine LANDMINE = new Landmine(); // public static Flare FLARE = new Flare(); // public static LaserWire LASERWIRE = new LaserWire(); // public static TurretWeapon TURRETWEAPON = new TurretWeapon(); // public static Teleporter TELEPORTER = new Teleporter(); // // public static Weapon getWeaponByName(String name) { // if(name.equals(Globals.HANDGUN.getName())) return Globals.HANDGUN; // else if(name.equals(Globals.ASSAULT_RIFLE.getName())) return Globals.ASSAULT_RIFLE; // else if(name.equals(Globals.SHOTGUN.getName())) return Globals.SHOTGUN; // else if(name.equals(Globals.FLAMETHROWER.getName())) return Globals.FLAMETHROWER; // else if(name.equals(Globals.GRENADE.getName())) return Globals.GRENADE; // else if(name.equals(Globals.LANDMINE.getName())) return Globals.LANDMINE; // else if(name.equals(Globals.FLARE.getName())) return Globals.FLARE; // else if(name.equals(Globals.LASERWIRE.getName())) return Globals.LASERWIRE; // else if(name.equals(Globals.TURRETWEAPON.getName())) return Globals.TURRETWEAPON; // else if(name.equals(Globals.TELEPORTER.getName())) return Globals.TELEPORTER; // else return null; // } // // public static void resetWeapons() { // Globals.HANDGUN.resetAmmo(); // Globals.ASSAULT_RIFLE.resetAmmo(); // Globals.SHOTGUN.resetAmmo(); // Globals.FLAMETHROWER.resetAmmo(); // Globals.GRENADE.resetAmmo(); // Globals.LANDMINE.resetAmmo(); // Globals.FLARE.resetAmmo(); // Globals.LASERWIRE.resetAmmo(); // Globals.TURRETWEAPON.resetAmmo(); // Globals.TELEPORTER.resetAmmo(); // } // }
import genericzombieshooter.misc.Globals; import java.awt.image.BufferedImage;
/** This file is part of Generic Zombie Shooter. Generic Zombie Shooter is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Generic Zombie Shooter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Generic Zombie Shooter. If not, see <http://www.gnu.org/licenses/>. **/ package genericzombieshooter.structures; /** * Used to manage status effects on the player. * @author Darin Beaudreau */ public class StatusEffect { // Member Variables private BufferedImage img; public BufferedImage getImage() { return this.img; } private long endTime; public long getEndTime() { return this.endTime; }
// Path: GenericZombieShooter/src/genericzombieshooter/misc/Globals.java // public class Globals { // // Game Information // public static final String VERSION = "1.0"; // public static final int W_WIDTH = 800; // The width of the game window. // public static final int W_HEIGHT = 640; // The height of the game window. // public static final long SLEEP_TIME = 20; // The sleep time of the animation thread. // public static final long WAVE_BREAK_TIME = 30 * 1000; // public static final Random r = new Random(); // public static List<Message> GAME_MESSAGES = new ArrayList<Message>(); // // // Zombie Information // public static final int ZOMBIE_REGULAR_TYPE = 1; // public static final long ZOMBIE_REGULAR_SPAWN = 1000; // public static final int ZOMBIE_DOG_TYPE = 2; // public static final long ZOMBIE_DOG_SPAWN = 10000; // public static final int ZOMBIE_ACID_TYPE = 3; // public static final long ZOMBIE_ACID_SPAWN = 30000; // public static final int ZOMBIE_POISONFOG_TYPE = 4; // public static final long ZOMBIE_POISONFOG_SPAWN = 20000; // public static final int ZOMBIE_MATRON_TYPE = 5; // public static final long ZOMBIE_MATRON_SPAWN = 50000; // public static final int ZOMBIE_TINY_TYPE = 6; // // // Boss Information // public static final int ZOMBIE_BOSS_ABERRATION_TYPE = 7; // public static final int ZOMBIE_BOSS_ZOMBAT_TYPE = 8; // public static final int ZOMBIE_BOSS_STITCHES_TYPE = 9; // // // Game-State Related // public static Runnable animation; // The primary animation thread. // public static GameTime gameTime; // Used to keep track of the time. // // public static boolean running; // Whether or not the game is currently running. // public static boolean started; // public static boolean crashed; // Tells the game whether or not there was a crash. // public static boolean paused; // public static boolean storeOpen; // public static boolean levelScreenOpen; // public static boolean deathScreen; // public static boolean waveInProgress; // Whether the player is fighting or waiting for another wave. // public static long nextWave; // // // Input Related // public static boolean [] keys; // The state of the game key controls. // public static boolean [] buttons; // The state of the game mouse button controls. // public static Point mousePos; // The current position of the mouse on the screen. // // // Static Weapons // public static Handgun HANDGUN = new Handgun(); // public static AssaultRifle ASSAULT_RIFLE = new AssaultRifle(); // public static Shotgun SHOTGUN = new Shotgun(); // public static Flamethrower FLAMETHROWER = new Flamethrower(); // public static Grenade GRENADE = new Grenade(); // public static Landmine LANDMINE = new Landmine(); // public static Flare FLARE = new Flare(); // public static LaserWire LASERWIRE = new LaserWire(); // public static TurretWeapon TURRETWEAPON = new TurretWeapon(); // public static Teleporter TELEPORTER = new Teleporter(); // // public static Weapon getWeaponByName(String name) { // if(name.equals(Globals.HANDGUN.getName())) return Globals.HANDGUN; // else if(name.equals(Globals.ASSAULT_RIFLE.getName())) return Globals.ASSAULT_RIFLE; // else if(name.equals(Globals.SHOTGUN.getName())) return Globals.SHOTGUN; // else if(name.equals(Globals.FLAMETHROWER.getName())) return Globals.FLAMETHROWER; // else if(name.equals(Globals.GRENADE.getName())) return Globals.GRENADE; // else if(name.equals(Globals.LANDMINE.getName())) return Globals.LANDMINE; // else if(name.equals(Globals.FLARE.getName())) return Globals.FLARE; // else if(name.equals(Globals.LASERWIRE.getName())) return Globals.LASERWIRE; // else if(name.equals(Globals.TURRETWEAPON.getName())) return Globals.TURRETWEAPON; // else if(name.equals(Globals.TELEPORTER.getName())) return Globals.TELEPORTER; // else return null; // } // // public static void resetWeapons() { // Globals.HANDGUN.resetAmmo(); // Globals.ASSAULT_RIFLE.resetAmmo(); // Globals.SHOTGUN.resetAmmo(); // Globals.FLAMETHROWER.resetAmmo(); // Globals.GRENADE.resetAmmo(); // Globals.LANDMINE.resetAmmo(); // Globals.FLARE.resetAmmo(); // Globals.LASERWIRE.resetAmmo(); // Globals.TURRETWEAPON.resetAmmo(); // Globals.TELEPORTER.resetAmmo(); // } // } // Path: GenericZombieShooter/src/genericzombieshooter/structures/StatusEffect.java import genericzombieshooter.misc.Globals; import java.awt.image.BufferedImage; /** This file is part of Generic Zombie Shooter. Generic Zombie Shooter is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Generic Zombie Shooter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Generic Zombie Shooter. If not, see <http://www.gnu.org/licenses/>. **/ package genericzombieshooter.structures; /** * Used to manage status effects on the player. * @author Darin Beaudreau */ public class StatusEffect { // Member Variables private BufferedImage img; public BufferedImage getImage() { return this.img; } private long endTime; public long getEndTime() { return this.endTime; }
public void refresh(long duration) { this.endTime = Globals.gameTime.getElapsedMillis() + duration; }
Malkierian/PlasmaCraft
src/main/java/untouchedwagons/minecraft/plasmacraft/client/renderers/RenderMutantCow.java
// Path: src/main/java/untouchedwagons/minecraft/plasmacraft/entity/EntityMutantCow.java // public class EntityMutantCow extends EntityAnimal // { // public EntityMutantCow(World world) // { // super(world); // setSize(0.9F, 1.3F); // } // // public EntityMutantCow(World world, double d, double d1, double d2) // { // super(world); // setPosition(d, d1, d2); // } // // public void writeEntityToNBT(NBTTagCompound nbttagcompound) // { // super.writeEntityToNBT(nbttagcompound); // } // // public void readEntityFromNBT(NBTTagCompound nbttagcompound) // { // super.readEntityFromNBT(nbttagcompound); // } // // protected String getLivingSound() // { // return "mob.cow"; // } // // protected String getHurtSound() // { // return "mob.cowhurt"; // } // // protected String getDeathSound() // { // return "mob.cowhurt"; // } // // protected float getSoundVolume() // { // return 0.4F; // } // // protected Item getDropItem() // { // return PlasmaCraft.items.plasmaLeather; // } // // public boolean interact(EntityPlayer entityplayer) // { // ItemStack itemstack = entityplayer.inventory.getCurrentItem(); // if(itemstack != null && itemstack.getItem() == PlasmaCraft.items.vial) // { // entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, new ItemStack(PlasmaCraft.items.vial, 1, ItemVial.ACID_DAMAGE)); // return true; // } // else // { // return super.interact(entityplayer); // } // } // // protected EntityAnimal func_40145_a(EntityAnimal entityanimal) // { // return new EntityMutantCow(worldObj); // } // // public EntityAnimal spawnBabyAnimal(EntityAnimal entityanimal) { // // TODO Auto-generated method stub // return null; // } // // @Override // public EntityAgeable createChild(EntityAgeable var1) { // // TODO Auto-generated method stub // return null; // } // }
import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import untouchedwagons.minecraft.plasmacraft.entity.EntityMutantCow;
package untouchedwagons.minecraft.plasmacraft.client.renderers; public class RenderMutantCow extends RenderLiving { public RenderMutantCow(ModelBase modelbase, float f) { super(modelbase, f); }
// Path: src/main/java/untouchedwagons/minecraft/plasmacraft/entity/EntityMutantCow.java // public class EntityMutantCow extends EntityAnimal // { // public EntityMutantCow(World world) // { // super(world); // setSize(0.9F, 1.3F); // } // // public EntityMutantCow(World world, double d, double d1, double d2) // { // super(world); // setPosition(d, d1, d2); // } // // public void writeEntityToNBT(NBTTagCompound nbttagcompound) // { // super.writeEntityToNBT(nbttagcompound); // } // // public void readEntityFromNBT(NBTTagCompound nbttagcompound) // { // super.readEntityFromNBT(nbttagcompound); // } // // protected String getLivingSound() // { // return "mob.cow"; // } // // protected String getHurtSound() // { // return "mob.cowhurt"; // } // // protected String getDeathSound() // { // return "mob.cowhurt"; // } // // protected float getSoundVolume() // { // return 0.4F; // } // // protected Item getDropItem() // { // return PlasmaCraft.items.plasmaLeather; // } // // public boolean interact(EntityPlayer entityplayer) // { // ItemStack itemstack = entityplayer.inventory.getCurrentItem(); // if(itemstack != null && itemstack.getItem() == PlasmaCraft.items.vial) // { // entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, new ItemStack(PlasmaCraft.items.vial, 1, ItemVial.ACID_DAMAGE)); // return true; // } // else // { // return super.interact(entityplayer); // } // } // // protected EntityAnimal func_40145_a(EntityAnimal entityanimal) // { // return new EntityMutantCow(worldObj); // } // // public EntityAnimal spawnBabyAnimal(EntityAnimal entityanimal) { // // TODO Auto-generated method stub // return null; // } // // @Override // public EntityAgeable createChild(EntityAgeable var1) { // // TODO Auto-generated method stub // return null; // } // } // Path: src/main/java/untouchedwagons/minecraft/plasmacraft/client/renderers/RenderMutantCow.java import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; import untouchedwagons.minecraft.plasmacraft.entity.EntityMutantCow; package untouchedwagons.minecraft.plasmacraft.client.renderers; public class RenderMutantCow extends RenderLiving { public RenderMutantCow(ModelBase modelbase, float f) { super(modelbase, f); }
public void renderCow(EntityMutantCow smentitymutantcow, double d, double d1, double d2,
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/requests/CacheableRequest.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/http/HttpRequestsManager.java // @Beta // public interface HttpRequestsManager { // // /** // * Returns the default request factory from which you can execute HTTP requests. Base settings, // * such as timeouts and user agent, are already set for you within each {@link HttpRequest} // * created. // */ // public HttpRequestFactory getRequestFactory(); // // /** // * Returns a new request factory which uses the passed {@link HttpTransport} and whose generated // * {@link HttpRequest}s are initialised with default parameters. // * // * @param transport The HttpTransport to be used for this factory // * @return The created {@link HttpRequestFactory} // */ // public HttpRequestFactory createRequestFactory(@NonNull HttpTransport transport); // // /** // * Shortcut method for the {@link HttpRequest} builder. See {@link // * HttpRequestFactory#buildRequest(String, GenericUrl, HttpContent)}. // * // * @param method HTTP request method string as per {@link HttpMethods} // * @param urlString HTTP request url String // * @param content HTTP request content or null // * @return The built HttpRequest // * @throws IOException If an exception occurred while building the request // * @throws IllegalArgumentException If the passed url has a syntax error // */ // public HttpRequest buildRequest(@NonNull String method, @NonNull String urlString, // @Nullable HttpContent content) throws IOException; // // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.github.marcosalis.kraken.utils.http.HttpRequestsManager; import com.google.common.annotations.Beta; import java.util.concurrent.Callable;
/* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.requests; /** * Interface for an HTTP request which returns a cacheable item and can be used to compute its cache * key. It implements {@link Callable} so that in can be directly executed in an executor without * wrapping it. * * Support for use in caches: a content can be stored in a cache map by using an hashed * representation of its URL (or other suitable cache key) by calling {@link #hash()}. * * <b>Thread-safety:</b> Implementations must be thread-safe. * * @param <E> The response object type that this request will be returning. * @author Marco Salis * @since 1.0 */ @Beta public interface CacheableRequest<E> extends Callable<E> { /** * Returns the request's URL. Override this in subclasses if the request URL cannot be generated * at object instantiation. */ @Nullable public abstract String getRequestUrl(); /** * Synchronously executes the request. * * @return The response object if it can be retrieved or null * @throws Exception If something went wrong */ @Nullable public abstract E execute() throws Exception; /** * Synchronously executes the request using the passed {@link HttpRequestsManager} * * @see {@link #execute()} */ @Nullable
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/http/HttpRequestsManager.java // @Beta // public interface HttpRequestsManager { // // /** // * Returns the default request factory from which you can execute HTTP requests. Base settings, // * such as timeouts and user agent, are already set for you within each {@link HttpRequest} // * created. // */ // public HttpRequestFactory getRequestFactory(); // // /** // * Returns a new request factory which uses the passed {@link HttpTransport} and whose generated // * {@link HttpRequest}s are initialised with default parameters. // * // * @param transport The HttpTransport to be used for this factory // * @return The created {@link HttpRequestFactory} // */ // public HttpRequestFactory createRequestFactory(@NonNull HttpTransport transport); // // /** // * Shortcut method for the {@link HttpRequest} builder. See {@link // * HttpRequestFactory#buildRequest(String, GenericUrl, HttpContent)}. // * // * @param method HTTP request method string as per {@link HttpMethods} // * @param urlString HTTP request url String // * @param content HTTP request content or null // * @return The built HttpRequest // * @throws IOException If an exception occurred while building the request // * @throws IllegalArgumentException If the passed url has a syntax error // */ // public HttpRequest buildRequest(@NonNull String method, @NonNull String urlString, // @Nullable HttpContent content) throws IOException; // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/requests/CacheableRequest.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.github.marcosalis.kraken.utils.http.HttpRequestsManager; import com.google.common.annotations.Beta; import java.util.concurrent.Callable; /* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.requests; /** * Interface for an HTTP request which returns a cacheable item and can be used to compute its cache * key. It implements {@link Callable} so that in can be directly executed in an executor without * wrapping it. * * Support for use in caches: a content can be stored in a cache map by using an hashed * representation of its URL (or other suitable cache key) by calling {@link #hash()}. * * <b>Thread-safety:</b> Implementations must be thread-safe. * * @param <E> The response object type that this request will be returning. * @author Marco Salis * @since 1.0 */ @Beta public interface CacheableRequest<E> extends Callable<E> { /** * Returns the request's URL. Override this in subclasses if the request URL cannot be generated * at object instantiation. */ @Nullable public abstract String getRequestUrl(); /** * Synchronously executes the request. * * @return The response object if it can be retrieved or null * @throws Exception If something went wrong */ @Nullable public abstract E execute() throws Exception; /** * Synchronously executes the request using the passed {@link HttpRequestsManager} * * @see {@link #execute()} */ @Nullable
public abstract E execute(@NonNull HttpRequestsManager connManager) throws Exception;
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/NetworkReceiver.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/NetworkBroadcastReceiver.java // static class NetworkIntent extends Intent { // // private static final String NETWORK_TYPE = "NETWORK_TYPE"; // // /** // * {@inheritDoc} // */ // NetworkIntent(String action) { // super(action); // } // // /** // * @param type The type of an active network connection // * @see Intent#Intent(String) // */ // NetworkIntent(String action, int type) { // super(action); // setNetworkType(type); // } // // /** // * Get the intent's connection type, if set. Can be one of those listed in {@link // * ConnectionManager} or -1 if not set // */ // int getNetworkType() { // return getIntExtra(NETWORK_TYPE, -1); // } // // private void setNetworkType(int type) { // putExtra(NETWORK_TYPE, type); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import com.github.marcosalis.kraken.utils.network.NetworkBroadcastReceiver.NetworkIntent; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.utils.network; /** * Network connectivity changes notifier. Clients must register to get connection updates through * the application's {@link LocalBroadcastManager} and passing an anonymous extension of this class * as shown below: * * <pre> * LocalBroadcastManager.getInstance(context).registerReceiver(new NetworkReceiver() { * &#064;Override * public void onConnectionActive(int type) { * // do your stuff here * } * * &#064;Override * public void onConnectionGone() { * // do your stuff here * } * }, NetworkReceiver.getFilter()); * </pre> * * Do <b>NOT</b> forget to unregister the receiver by calling the unregisterReceiver() method of the * {@link LocalBroadcastManager}. * * For activities, the recommended way to register and unregister the receiver is in the onResume() * and onPause() methods. * * <b>Note:</b> due to an Android issue, in several cases a connection change gets notified more * than once by the BroadcastReceiver. Use your own state control when performing atomic operations * inside the receiver callbacks. * * @author Marco Salis * @since 1.0 */ @Beta public abstract class NetworkReceiver extends BroadcastReceiver { /** * Return the {@link IntentFilter} to subscribe to network connectivity changes */ public static IntentFilter getFilter() { final IntentFilter filter = new IntentFilter(); filter.addAction(NetworkBroadcastReceiver.ACTION_NETWORK_ACTIVE); filter.addAction(NetworkBroadcastReceiver.ACTION_NETWORK_GONE); return filter; } @Override public final void onReceive(Context context, Intent intent) {
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/NetworkBroadcastReceiver.java // static class NetworkIntent extends Intent { // // private static final String NETWORK_TYPE = "NETWORK_TYPE"; // // /** // * {@inheritDoc} // */ // NetworkIntent(String action) { // super(action); // } // // /** // * @param type The type of an active network connection // * @see Intent#Intent(String) // */ // NetworkIntent(String action, int type) { // super(action); // setNetworkType(type); // } // // /** // * Get the intent's connection type, if set. Can be one of those listed in {@link // * ConnectionManager} or -1 if not set // */ // int getNetworkType() { // return getIntExtra(NETWORK_TYPE, -1); // } // // private void setNetworkType(int type) { // putExtra(NETWORK_TYPE, type); // } // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/NetworkReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import com.github.marcosalis.kraken.utils.network.NetworkBroadcastReceiver.NetworkIntent; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.utils.network; /** * Network connectivity changes notifier. Clients must register to get connection updates through * the application's {@link LocalBroadcastManager} and passing an anonymous extension of this class * as shown below: * * <pre> * LocalBroadcastManager.getInstance(context).registerReceiver(new NetworkReceiver() { * &#064;Override * public void onConnectionActive(int type) { * // do your stuff here * } * * &#064;Override * public void onConnectionGone() { * // do your stuff here * } * }, NetworkReceiver.getFilter()); * </pre> * * Do <b>NOT</b> forget to unregister the receiver by calling the unregisterReceiver() method of the * {@link LocalBroadcastManager}. * * For activities, the recommended way to register and unregister the receiver is in the onResume() * and onPause() methods. * * <b>Note:</b> due to an Android issue, in several cases a connection change gets notified more * than once by the BroadcastReceiver. Use your own state control when performing atomic operations * inside the receiver callbacks. * * @author Marco Salis * @since 1.0 */ @Beta public abstract class NetworkReceiver extends BroadcastReceiver { /** * Return the {@link IntentFilter} to subscribe to network connectivity changes */ public static IntentFilter getFilter() { final IntentFilter filter = new IntentFilter(); filter.addAction(NetworkBroadcastReceiver.ACTION_NETWORK_ACTIVE); filter.addAction(NetworkBroadcastReceiver.ACTION_NETWORK_GONE); return filter; } @Override public final void onReceive(Context context, Intent intent) {
if (intent instanceof NetworkIntent) {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // }
import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in;
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in;
protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // }
import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in; protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY protected final int mCustomAnimationId; /* Constructors from superclass */
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in; protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY protected final int mCustomAnimationId; /* Constructors from superclass */
public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView) {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // }
import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in; protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY protected final int mCustomAnimationId; /* Constructors from superclass */ public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView) { this(key, imgView, AnimationMode.NOT_IN_MEMORY, null, -1); } public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView,
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in; protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY protected final int mCustomAnimationId; /* Constructors from superclass */ public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView) { this(key, imgView, AnimationMode.NOT_IN_MEMORY, null, -1); } public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView,
@Nullable OnBitmapSetListener listener) {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // }
import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in; protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY protected final int mCustomAnimationId; /* Constructors from superclass */ public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView) { this(key, imgView, AnimationMode.NOT_IN_MEMORY, null, -1); } public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView, @Nullable OnBitmapSetListener listener) { this(key, imgView, AnimationMode.NOT_IN_MEMORY, listener, -1); } /** * @param key The {@link CacheUrlKey} for the bitmap * @param mode The {@link AnimationMode} to use * @param customAnimationId The ID of a custom animation to load, or -1 to use the default * Android fade-in animation. * @see BitmapAsyncSetter#BitmapAsyncSetter(ImageView, BitmapAsyncSetter#OnBitmapImageSetListener) */ public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView, @NonNull AnimationMode mode, @Nullable OnBitmapSetListener listener, int customAnimationId) { super(key, imgView, listener); mAnimationMode = mode; mCustomAnimationId = customAnimationId; } /** * Method that effectively sets a bitmap image for the passed {@link ImageView}. The default * implementation just calls {@link ImageView#setImageBitmap(Bitmap)}, override to provide * custom behavior or animations when setting the bitmap. * * @param imageView The {@link ImageView} to set the bitmap into * @param bitmap The {@link Bitmap} to set * @param source The {@link CacheSource} from where the bitmap was loaded */ protected void setImageBitmap(@NonNull final ImageView imageView, @NonNull Bitmap bitmap,
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/AnimationMode.java // @Beta // public enum AnimationMode { // /** // * Use no animation (same as using a normal {@link BitmapAsyncSetter}) // */ // NEVER, // /** // * Animate only if the bitmap is not already in the memory caches // */ // NOT_IN_MEMORY, // /** // * Animate only if the bitmap was loaded from network // */ // FROM_NETWORK, // /** // * Always animate (use with care: the performance impact can be noticeable when scrolling long // * lists of bitmaps) // */ // ALWAYS; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java // @Beta // public interface OnBitmapSetListener { // // /** // * Called from the UI thread when the retrieved bitmap image has been set into the {@link // * ImageView} // * // * @param key The {@link CacheUrlKey} of the bitmap // * @param bitmap The set {@link Bitmap} // * @param source The {@link CacheSource} of the bitmap // */ // public void onBitmapSet(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap, // @NonNull CacheSource source); // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/internal/BitmapAnimatedAsyncSetter.java import javax.annotation.concurrent.ThreadSafe; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.bitmap.AnimationMode; import com.github.marcosalis.kraken.cache.bitmap.BitmapCache.OnBitmapSetListener; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap.internal; /** * Extension of {@link BitmapAsyncSetter} that starts a fade-in animation right after setting the * image bitmap when this is loaded from the disk or network. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public class BitmapAnimatedAsyncSetter extends BitmapAsyncSetter { private static final String TAG = BitmapAnimatedAsyncSetter.class.getSimpleName(); protected static final int DEFAULT_ANIM_ID = android.R.anim.fade_in; protected final AnimationMode mAnimationMode; // defaults to NOT_IN_MEMORY protected final int mCustomAnimationId; /* Constructors from superclass */ public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView) { this(key, imgView, AnimationMode.NOT_IN_MEMORY, null, -1); } public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView, @Nullable OnBitmapSetListener listener) { this(key, imgView, AnimationMode.NOT_IN_MEMORY, listener, -1); } /** * @param key The {@link CacheUrlKey} for the bitmap * @param mode The {@link AnimationMode} to use * @param customAnimationId The ID of a custom animation to load, or -1 to use the default * Android fade-in animation. * @see BitmapAsyncSetter#BitmapAsyncSetter(ImageView, BitmapAsyncSetter#OnBitmapImageSetListener) */ public BitmapAnimatedAsyncSetter(@NonNull CacheUrlKey key, @NonNull ImageView imgView, @NonNull AnimationMode mode, @Nullable OnBitmapSetListener listener, int customAnimationId) { super(key, imgView, listener); mAnimationMode = mode; mCustomAnimationId = customAnimationId; } /** * Method that effectively sets a bitmap image for the passed {@link ImageView}. The default * implementation just calls {@link ImageView#setImageBitmap(Bitmap)}, override to provide * custom behavior or animations when setting the bitmap. * * @param imageView The {@link ImageView} to set the bitmap into * @param bitmap The {@link Bitmap} to set * @param source The {@link CacheSource} from where the bitmap was loaded */ protected void setImageBitmap(@NonNull final ImageView imageView, @NonNull Bitmap bitmap,
@NonNull CacheSource source) {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/json/ArrayToListDeserializer.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // }
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.common.annotations.Beta; import java.io.IOException; import java.util.List;
/* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.utils.json; /** * Abstract generic {@link JsonDeserializer} that deserializes a JSON array to a list. * * @param <M> The model object type * @author Marco Salis * @since 1.0 */ @Beta public abstract class ArrayToListDeserializer<M> extends JsonDeserializer<List<M>> { @Override public List<M> deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException { try { List<M> list = jsonparser.readValueAs(getTypeReference()); return list; } catch (JsonProcessingException e) {
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/json/ArrayToListDeserializer.java import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.common.annotations.Beta; import java.io.IOException; import java.util.List; /* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.utils.json; /** * Abstract generic {@link JsonDeserializer} that deserializes a JSON array to a list. * * @param <M> The model object type * @author Marco Salis * @since 1.0 */ @Beta public abstract class ArrayToListDeserializer<M> extends JsonDeserializer<List<M>> { @Override public List<M> deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException { try { List<M> list = jsonparser.readValueAs(getTypeReference()); return list; } catch (JsonProcessingException e) {
LogUtils.logException(e);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/managers/CachesManager.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/SecondLevelCache.java // public enum ClearMode { // ALL, // EVICT_OLD // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // }
import android.app.Application; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.cache.SecondLevelCache.ClearMode; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.managers; /** * General interface for an application global contents manager.<br> Provides methods to put and get * global content managers from a single endpoint, and utility functionalities to clear and manage * their caches. * * Can be used to allow dependencies injection when accessing a content manager. * * @param <E> The content identificator * @author Marco Salis * @since 1.0 */ @Beta public interface CachesManager<E> { /** * Register a content proxy into the manager.<br> This should only be done once, preferably in * the {@link Application#onCreate()} method. * * @param contentId The content proxy identificator object (preferably a String or an enum * type) * @param content The content proxy instance * @return true if the content proxy was successfully added, false if another cache is already * registered with the same ID */
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/SecondLevelCache.java // public enum ClearMode { // ALL, // EVICT_OLD // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/managers/CachesManager.java import android.app.Application; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.cache.SecondLevelCache.ClearMode; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.managers; /** * General interface for an application global contents manager.<br> Provides methods to put and get * global content managers from a single endpoint, and utility functionalities to clear and manage * their caches. * * Can be used to allow dependencies injection when accessing a content manager. * * @param <E> The content identificator * @author Marco Salis * @since 1.0 */ @Beta public interface CachesManager<E> { /** * Register a content proxy into the manager.<br> This should only be done once, preferably in * the {@link Application#onCreate()} method. * * @param contentId The content proxy identificator object (preferably a String or an enum * type) * @param content The content proxy instance * @return true if the content proxy was successfully added, false if another cache is already * registered with the same ID */
public boolean registerContent(@NonNull E contentId, @NonNull ContentProxy content);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/managers/CachesManager.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/SecondLevelCache.java // public enum ClearMode { // ALL, // EVICT_OLD // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // }
import android.app.Application; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.cache.SecondLevelCache.ClearMode; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.managers; /** * General interface for an application global contents manager.<br> Provides methods to put and get * global content managers from a single endpoint, and utility functionalities to clear and manage * their caches. * * Can be used to allow dependencies injection when accessing a content manager. * * @param <E> The content identificator * @author Marco Salis * @since 1.0 */ @Beta public interface CachesManager<E> { /** * Register a content proxy into the manager.<br> This should only be done once, preferably in * the {@link Application#onCreate()} method. * * @param contentId The content proxy identificator object (preferably a String or an enum * type) * @param content The content proxy instance * @return true if the content proxy was successfully added, false if another cache is already * registered with the same ID */ public boolean registerContent(@NonNull E contentId, @NonNull ContentProxy content); /** * Gets a previously registered content proxy from the manager. * * @param contentId The content proxy identification string * @return The required content proxy instance, or null if it doesn't exist */ public ContentProxy getContent(@NonNull E contentId); /** * Clears all the registered caches contents. */ public void clearAllCaches(); /** * Clears all the registered memory caches contents.<br> <strong>Warning:</strong> use this only * on extreme low memory situations. */ public void clearMemoryCaches(); /** * Clears all the registered disk caches contents. */ public void scheduleClearDiskCaches(); /** * Synchronously clears all the registered disk caches contents using the passed {@link * ClearMode}. */
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/SecondLevelCache.java // public enum ClearMode { // ALL, // EVICT_OLD // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/managers/CachesManager.java import android.app.Application; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.cache.SecondLevelCache.ClearMode; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.managers; /** * General interface for an application global contents manager.<br> Provides methods to put and get * global content managers from a single endpoint, and utility functionalities to clear and manage * their caches. * * Can be used to allow dependencies injection when accessing a content manager. * * @param <E> The content identificator * @author Marco Salis * @since 1.0 */ @Beta public interface CachesManager<E> { /** * Register a content proxy into the manager.<br> This should only be done once, preferably in * the {@link Application#onCreate()} method. * * @param contentId The content proxy identificator object (preferably a String or an enum * type) * @param content The content proxy instance * @return true if the content proxy was successfully added, false if another cache is already * registered with the same ID */ public boolean registerContent(@NonNull E contentId, @NonNull ContentProxy content); /** * Gets a previously registered content proxy from the manager. * * @param contentId The content proxy identification string * @return The required content proxy instance, or null if it doesn't exist */ public ContentProxy getContent(@NonNull E contentId); /** * Clears all the registered caches contents. */ public void clearAllCaches(); /** * Clears all the registered memory caches contents.<br> <strong>Warning:</strong> use this only * on extreme low memory situations. */ public void clearMemoryCaches(); /** * Clears all the registered disk caches contents. */ public void scheduleClearDiskCaches(); /** * Synchronously clears all the registered disk caches contents using the passed {@link * ClearMode}. */
public void clearDiskCaches(@NonNull ClearMode mode);
marcosalis/kraken
kraken_lib/src/androidTest/java/com/github/marcosalis/kraken/testing/mock/MockConnectionMonitor.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/ConnectionMonitor.java // @Beta // public interface ConnectionMonitor { // // /** // * Checks if the connection monitor has already been registered. // * // * @return true if it is already registered, false otherwise // */ // public boolean isRegistered(); // // /** // * Checks the current device's network connection state. // * // * @return true if there is an active network connection or the monitor hasn't been initialized, // * false otherwise // */ // public boolean isNetworkActive(); // // }
import javax.annotation.concurrent.ThreadSafe; import com.github.marcosalis.kraken.utils.network.ConnectionMonitor; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.testing.mock; /** * Mock implementation of {@link ConnectionMonitor} for testing. * * All methods return true. * * @since 1.0 * @author Marco Salis */ @Beta @ThreadSafe
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/ConnectionMonitor.java // @Beta // public interface ConnectionMonitor { // // /** // * Checks if the connection monitor has already been registered. // * // * @return true if it is already registered, false otherwise // */ // public boolean isRegistered(); // // /** // * Checks the current device's network connection state. // * // * @return true if there is an active network connection or the monitor hasn't been initialized, // * false otherwise // */ // public boolean isNetworkActive(); // // } // Path: kraken_lib/src/androidTest/java/com/github/marcosalis/kraken/testing/mock/MockConnectionMonitor.java import javax.annotation.concurrent.ThreadSafe; import com.github.marcosalis.kraken.utils.network.ConnectionMonitor; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.testing.mock; /** * Mock implementation of {@link ConnectionMonitor} for testing. * * All methods return true. * * @since 1.0 * @author Marco Salis */ @Beta @ThreadSafe
public class MockConnectionMonitor implements ConnectionMonitor {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/HashUtils.java // public interface CacheKey { // // public String hash(); // }
import android.annotation.SuppressLint; import android.os.Parcelable; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.utils.HashUtils.CacheKey; import com.google.common.annotations.Beta;
/* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.keys; /** * Interface for objects that hold either a String key and a URL representing the resource (or * value), to be used as cache key entries. * * Implementations <b>must</b> implement {@link Parcelable} * * @author Marco Salis * @since 1.0 */ @Beta @SuppressLint("ParcelCreator")
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/HashUtils.java // public interface CacheKey { // // public String hash(); // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java import android.annotation.SuppressLint; import android.os.Parcelable; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.utils.HashUtils.CacheKey; import com.google.common.annotations.Beta; /* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.keys; /** * Interface for objects that hold either a String key and a URL representing the resource (or * value), to be used as cache key entries. * * Implementations <b>must</b> implement {@link Parcelable} * * @author Marco Salis * @since 1.0 */ @Beta @SuppressLint("ParcelCreator")
public interface CacheUrlKey extends CacheKey, Parcelable {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/URICacheUrlKey.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/HashUtils.java // public final class HashUtils { // // private static final HashFunction DEFAULT_HASH = Hashing.murmur3_128(); // // private HashUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Gets a String hash generated using the default hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getDefaultHash(@NonNull String... strings) { // return getHash(DEFAULT_HASH, strings); // } // // /** // * Gets a String hash generated using the MD5 hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getMD5Hash(@NonNull String... strings) { // return getHash(Hashing.md5(), strings); // } // // /** // * Gets a String hash generated using the passed hashing algorithm. // */ // @NonNull // public static String getHash(@NonNull HashFunction hash, @NonNull String... strings) { // final Hasher hasher = hash.newHasher(); // for (String input : strings) { // hasher.putString(input); // } // return hasher.hash().toString(); // } // // /** // * Interface that represent any suitable object that can be used as a String cache key. The key // * itself retrieved by calling the hash() method. // * // * TODO: move this // */ // public interface CacheKey { // // public String hash(); // } // // }
import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.utils.HashUtils; import com.google.common.annotations.Beta; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import java.net.URI; import javax.annotation.concurrent.Immutable;
@Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mUri.toString()); } /** * Gets the generated key for this object */ @Override public String hash() { return mKey; } /** * Gets the full URL for GET requests */ @Override public String getUrl() { return mUri.toString(); } /** * Generate an unique identifier for the cache key from the path part of the given URI. */ private String hashUri() throws IllegalArgumentException { String path = mUri.getPath(); if (path == null || path.length() < MIN_KEY_SOURCE) { throw new IllegalArgumentException("Unsuitable URI"); }
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/HashUtils.java // public final class HashUtils { // // private static final HashFunction DEFAULT_HASH = Hashing.murmur3_128(); // // private HashUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Gets a String hash generated using the default hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getDefaultHash(@NonNull String... strings) { // return getHash(DEFAULT_HASH, strings); // } // // /** // * Gets a String hash generated using the MD5 hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getMD5Hash(@NonNull String... strings) { // return getHash(Hashing.md5(), strings); // } // // /** // * Gets a String hash generated using the passed hashing algorithm. // */ // @NonNull // public static String getHash(@NonNull HashFunction hash, @NonNull String... strings) { // final Hasher hasher = hash.newHasher(); // for (String input : strings) { // hasher.putString(input); // } // return hasher.hash().toString(); // } // // /** // * Interface that represent any suitable object that can be used as a String cache key. The key // * itself retrieved by calling the hash() method. // * // * TODO: move this // */ // public interface CacheKey { // // public String hash(); // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/URICacheUrlKey.java import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.utils.HashUtils; import com.google.common.annotations.Beta; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import java.net.URI; import javax.annotation.concurrent.Immutable; @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mUri.toString()); } /** * Gets the generated key for this object */ @Override public String hash() { return mKey; } /** * Gets the full URL for GET requests */ @Override public String getUrl() { return mUri.toString(); } /** * Generate an unique identifier for the cache key from the path part of the given URI. */ private String hashUri() throws IllegalArgumentException { String path = mUri.getPath(); if (path == null || path.length() < MIN_KEY_SOURCE) { throw new IllegalArgumentException("Unsuitable URI"); }
return HashUtils.getHash(HASH_FUNCTION, path);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/json/JacksonJsonManager.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.api.client.util.ObjectParser; import com.google.common.annotations.Beta; import java.io.IOException; import javax.annotation.concurrent.Immutable;
* * @return The {@link ObjectMapper} */ @NonNull public static ObjectMapper getObjectMapper() { return INSTANCE.mMapper; } /** * Builds a new {@link JacksonHttpContent} from the source object. * * @param source The source object (keys must be specified for the mapping to work) * @return The built {@link JacksonHttpContent} */ public static JacksonHttpContent buildHttpContent(@NonNull Object source) { return new JacksonHttpContent(source); } /** * Shortcut method to parse a POJO object into a JSON string * * @param data The object to parse * @return The string representation of that object (or null if the parse failed for an * IOException) */ @Nullable public static String toJsonString(Object data) { try { return INSTANCE.mMapper.writeValueAsString(data); } catch (IOException e) {
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/json/JacksonJsonManager.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.api.client.util.ObjectParser; import com.google.common.annotations.Beta; import java.io.IOException; import javax.annotation.concurrent.Immutable; * * @return The {@link ObjectMapper} */ @NonNull public static ObjectMapper getObjectMapper() { return INSTANCE.mMapper; } /** * Builds a new {@link JacksonHttpContent} from the source object. * * @param source The source object (keys must be specified for the mapping to work) * @return The built {@link JacksonHttpContent} */ public static JacksonHttpContent buildHttpContent(@NonNull Object source) { return new JacksonHttpContent(source); } /** * Shortcut method to parse a POJO object into a JSON string * * @param data The object to parse * @return The string representation of that object (or null if the parse failed for an * IOException) */ @Nullable public static String toJsonString(Object data) { try { return INSTANCE.mMapper.writeValueAsString(data); } catch (IOException e) {
LogUtils.logException(e);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/SimpleCacheUrlKey.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/HashUtils.java // public final class HashUtils { // // private static final HashFunction DEFAULT_HASH = Hashing.murmur3_128(); // // private HashUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Gets a String hash generated using the default hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getDefaultHash(@NonNull String... strings) { // return getHash(DEFAULT_HASH, strings); // } // // /** // * Gets a String hash generated using the MD5 hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getMD5Hash(@NonNull String... strings) { // return getHash(Hashing.md5(), strings); // } // // /** // * Gets a String hash generated using the passed hashing algorithm. // */ // @NonNull // public static String getHash(@NonNull HashFunction hash, @NonNull String... strings) { // final Hasher hasher = hash.newHasher(); // for (String input : strings) { // hasher.putString(input); // } // return hasher.hash().toString(); // } // // /** // * Interface that represent any suitable object that can be used as a String cache key. The key // * itself retrieved by calling the hash() method. // * // * TODO: move this // */ // public interface CacheKey { // // public String hash(); // } // // }
import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.utils.HashUtils; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import javax.annotation.concurrent.Immutable;
/* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.keys; /** * Simple class that holds either a URL string and generates a shorter file system friendly String * key to be used for memory and disk caches. * * Prefer to {@link URICacheUrlKey} when there is no URL parameter striping needed. * * It implements {@link Parcelable}, so that it can be passed into Bundles. * * @author Marco Salis * @since 1.0 */ @Beta @Immutable public class SimpleCacheUrlKey implements CacheUrlKey { /** * Currently used hash function (murmur3 128 bit algorithm) */ protected static final HashFunction HASH_FUNCTION = Hashing.murmur3_128(); @NonNull private final String mKey; @NonNull private final String mUrl; /** * Generate a unique key from the passed URL, ignoring any query parameters or URL fragments. * * @param url The URL to be cached * @throws NullPointerException if the passed string URL is null */ public SimpleCacheUrlKey(@NonNull String url) { Preconditions.checkNotNull(url); mUrl = url; // process URI
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/HashUtils.java // public final class HashUtils { // // private static final HashFunction DEFAULT_HASH = Hashing.murmur3_128(); // // private HashUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Gets a String hash generated using the default hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getDefaultHash(@NonNull String... strings) { // return getHash(DEFAULT_HASH, strings); // } // // /** // * Gets a String hash generated using the MD5 hashing algorithm with the passed strings as // * input. // */ // @NonNull // public static String getMD5Hash(@NonNull String... strings) { // return getHash(Hashing.md5(), strings); // } // // /** // * Gets a String hash generated using the passed hashing algorithm. // */ // @NonNull // public static String getHash(@NonNull HashFunction hash, @NonNull String... strings) { // final Hasher hasher = hash.newHasher(); // for (String input : strings) { // hasher.putString(input); // } // return hasher.hash().toString(); // } // // /** // * Interface that represent any suitable object that can be used as a String cache key. The key // * itself retrieved by calling the hash() method. // * // * TODO: move this // */ // public interface CacheKey { // // public String hash(); // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/SimpleCacheUrlKey.java import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import com.github.marcosalis.kraken.utils.HashUtils; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import javax.annotation.concurrent.Immutable; /* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.keys; /** * Simple class that holds either a URL string and generates a shorter file system friendly String * key to be used for memory and disk caches. * * Prefer to {@link URICacheUrlKey} when there is no URL parameter striping needed. * * It implements {@link Parcelable}, so that it can be passed into Bundles. * * @author Marco Salis * @since 1.0 */ @Beta @Immutable public class SimpleCacheUrlKey implements CacheUrlKey { /** * Currently used hash function (murmur3 128 bit algorithm) */ protected static final HashFunction HASH_FUNCTION = Hashing.murmur3_128(); @NonNull private final String mKey; @NonNull private final String mUrl; /** * Generate a unique key from the passed URL, ignoring any query parameters or URL fragments. * * @param url The URL to be cached * @throws NullPointerException if the passed string URL is null */ public SimpleCacheUrlKey(@NonNull String url) { Preconditions.checkNotNull(url); mUrl = url; // process URI
mKey = HashUtils.getHash(HASH_FUNCTION, url);
marcosalis/kraken
kraken_lib/src/androidTest/java/com/github/marcosalis/kraken/cache/EmptyMemoryCacheTest.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public interface OnEntryRemovedListener<K, V> { // // /** // * Called when a cache entry has been removed. // * // * @param evicted true if the item has been removed for space constraints, false otherwise // * (because it's been explicitly removed or replaced) // * @param key the cache key of the removed element // * @param value the removed element // */ // public void onEntryRemoved(boolean evicted, @NonNull K key, @NonNull V value); // }
import java.util.concurrent.CountDownLatch; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import com.github.marcosalis.kraken.cache.ContentCache.OnEntryRemovedListener;
/* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache; /** * Unit tests for the {@link EmptyMemoryCache} class. * * @since 1.0 * @author Marco Salis */ @SmallTest public class EmptyMemoryCacheTest extends AndroidTestCase { private EmptyMemoryCache<String, String> mCache; protected void setUp() throws Exception { super.setUp(); mCache = new EmptyMemoryCache<String, String>("test_empty_cache"); } protected void tearDown() throws Exception { super.tearDown(); } public void testGet() { assertNull(mCache.get("key")); mCache.put("key", "value"); assertNull(mCache.get("key")); } public void testPut() throws InterruptedException { mCache.put("key", "value"); final CountDownLatch latch = new CountDownLatch(1);
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public interface OnEntryRemovedListener<K, V> { // // /** // * Called when a cache entry has been removed. // * // * @param evicted true if the item has been removed for space constraints, false otherwise // * (because it's been explicitly removed or replaced) // * @param key the cache key of the removed element // * @param value the removed element // */ // public void onEntryRemoved(boolean evicted, @NonNull K key, @NonNull V value); // } // Path: kraken_lib/src/androidTest/java/com/github/marcosalis/kraken/cache/EmptyMemoryCacheTest.java import java.util.concurrent.CountDownLatch; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.SmallTest; import com.github.marcosalis.kraken.cache.ContentCache.OnEntryRemovedListener; /* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache; /** * Unit tests for the {@link EmptyMemoryCache} class. * * @since 1.0 * @author Marco Salis */ @SmallTest public class EmptyMemoryCacheTest extends AndroidTestCase { private EmptyMemoryCache<String, String> mCache; protected void setUp() throws Exception { super.setUp(); mCache = new EmptyMemoryCache<String, String>("test_empty_cache"); } protected void tearDown() throws Exception { super.tearDown(); } public void testGet() { assertNull(mCache.get("key")); mCache.put("key", "value"); assertNull(mCache.get("key")); } public void testPut() throws InterruptedException { mCache.put("key", "value"); final CountDownLatch latch = new CountDownLatch(1);
mCache.setOnEntryRemovedListener(new OnEntryRemovedListener<String, String>() {
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/http/ByteArrayDownloader.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // }
import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Callable; import javax.annotation.concurrent.Immutable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.github.marcosalis.kraken.DroidConfig; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.github.marcosalis.kraken.utils.annotations.NotForUIThread; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.common.annotations.Beta; import com.google.common.io.ByteStreams;
@Nullable @NotForUIThread public static byte[] downloadByteArray(@NonNull HttpRequestFactory factory, @NonNull String url) throws IOException, IllegalArgumentException { HttpRequest request = null; HttpResponse response = null; byte[] bytes = null; if (DroidConfig.DEBUG) { Log.d(TAG, "Executing GET request to: " + url); } try { request = factory.buildRequest(HttpMethods.GET, new GenericUrl(url), null); response = request.execute(); if (response.isSuccessStatusCode()) { // get input stream and converts it to byte array InputStream stream = new BufferedInputStream(response.getContent()); bytes = ByteStreams.toByteArray(stream); if (DroidConfig.DEBUG && bytes != null) { Log.v(TAG, "GET request successful to: " + url); } } } finally { if (response != null) { try { response.disconnect(); } catch (IOException e) { // just an attempt to close the stream
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/http/ByteArrayDownloader.java import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Callable; import javax.annotation.concurrent.Immutable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.github.marcosalis.kraken.DroidConfig; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.github.marcosalis.kraken.utils.annotations.NotForUIThread; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpMethods; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.common.annotations.Beta; import com.google.common.io.ByteStreams; @Nullable @NotForUIThread public static byte[] downloadByteArray(@NonNull HttpRequestFactory factory, @NonNull String url) throws IOException, IllegalArgumentException { HttpRequest request = null; HttpResponse response = null; byte[] bytes = null; if (DroidConfig.DEBUG) { Log.d(TAG, "Executing GET request to: " + url); } try { request = factory.buildRequest(HttpMethods.GET, new GenericUrl(url), null); response = request.execute(); if (response.isSuccessStatusCode()) { // get input stream and converts it to byte array InputStream stream = new BufferedInputStream(response.getContent()); bytes = ByteStreams.toByteArray(stream); if (DroidConfig.DEBUG && bytes != null) { Log.v(TAG, "GET request successful to: " + url); } } } finally { if (response != null) { try { response.disconnect(); } catch (IOException e) { // just an attempt to close the stream
LogUtils.logException(e);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ModelDiskCache.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/StorageUtils.java // public enum CacheLocation { // INTERNAL, // EXTERNAL // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // }
import java.io.File; import java.io.IOException; import javax.annotation.concurrent.NotThreadSafe; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.marcosalis.kraken.DroidConfig; import com.github.marcosalis.kraken.utils.StorageUtils.CacheLocation; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.github.marcosalis.kraken.utils.annotations.NotForUIThread; import com.google.api.client.util.ObjectParser; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions;
/* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache; /** * Disk cache that stores a POJO/DTO object into its JSON representation in text files. * * TODO: use {@link JsonFactory} instead of Jackson's {@link ObjectMapper} * * @author Marco Salis * @since 1.0 */ @Beta @NotThreadSafe public class ModelDiskCache<V> extends SimpleDiskCache<V> { private static final String TAG = ModelDiskCache.class.getSimpleName(); private static final String PATH = "model"; private static final long PURGE_AFTER = MIN_EXPIRE_IN_SEC * 2; private final Class<V> mModelClass; private final ObjectMapper mObjectMapper; /** * Builds a {@link ModelDiskCache} that stores POJO/DTO objects as (plain) text into the passed * sub-folder, using the passed {@link ObjectParser}. * * Note that the {@link CacheLocation#INTERNAL} cache is always used. If no internal caches are * present, it falls back to the external one. * * TODO: allow choosing whether to store in ext storage for failover? * * @param context The {@link Context} to use * @param mapper The {@link ObjectMapper} to use for model de/serialization * @param subFolder The relative path to the cache folder where to store the cache (if it * doesn't exist, the folder is created) * @param modelClass The POJO object to store class type * @throws IOException */ public ModelDiskCache(@NonNull Context context, @NonNull ObjectMapper mapper, @NonNull String subFolder, @NonNull Class<V> modelClass) throws IOException {
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/StorageUtils.java // public enum CacheLocation { // INTERNAL, // EXTERNAL // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ModelDiskCache.java import java.io.File; import java.io.IOException; import javax.annotation.concurrent.NotThreadSafe; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.marcosalis.kraken.DroidConfig; import com.github.marcosalis.kraken.utils.StorageUtils.CacheLocation; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.github.marcosalis.kraken.utils.annotations.NotForUIThread; import com.google.api.client.util.ObjectParser; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; /* * Copyright 2013 Luluvise Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache; /** * Disk cache that stores a POJO/DTO object into its JSON representation in text files. * * TODO: use {@link JsonFactory} instead of Jackson's {@link ObjectMapper} * * @author Marco Salis * @since 1.0 */ @Beta @NotThreadSafe public class ModelDiskCache<V> extends SimpleDiskCache<V> { private static final String TAG = ModelDiskCache.class.getSimpleName(); private static final String PATH = "model"; private static final long PURGE_AFTER = MIN_EXPIRE_IN_SEC * 2; private final Class<V> mModelClass; private final ObjectMapper mObjectMapper; /** * Builds a {@link ModelDiskCache} that stores POJO/DTO objects as (plain) text into the passed * sub-folder, using the passed {@link ObjectParser}. * * Note that the {@link CacheLocation#INTERNAL} cache is always used. If no internal caches are * present, it falls back to the external one. * * TODO: allow choosing whether to store in ext storage for failover? * * @param context The {@link Context} to use * @param mapper The {@link ObjectMapper} to use for model de/serialization * @param subFolder The relative path to the cache folder where to store the cache (if it * doesn't exist, the folder is created) * @param modelClass The POJO object to store class type * @throws IOException */ public ModelDiskCache(@NonNull Context context, @NonNull ObjectMapper mapper, @NonNull String subFolder, @NonNull Class<V> modelClass) throws IOException {
super(context, CacheLocation.INTERNAL, PATH + File.separator + subFolder, true);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/ConnectionDefaultMonitor.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // }
import android.app.Application; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.support.annotation.NonNull; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.common.annotations.Beta; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.concurrent.ThreadSafe;
/* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.utils.network; /** * Application global network connection monitor.<br> Useful to easily retrieve the device's current * connection status without querying the {@link ConnectivityManager}. * * Must be initialized by calling {@link #register(Application)} within the {@link * Application#onCreate()} method. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public enum ConnectionDefaultMonitor implements ConnectionMonitor { INSTANCE; /** * Shortcut method to return the {@link ConnectionDefaultMonitor} singleton instance. */ public static ConnectionDefaultMonitor get() { return INSTANCE; } private final static String TAG = ConnectionDefaultMonitor.class.getSimpleName(); private final AtomicBoolean mConnectionActive; private final AtomicBoolean mIsRegistered; private final NetworkReceiver mNetReceiver = new NetworkReceiver() { @Override public void onConnectionActive(int type) { mConnectionActive.compareAndSet(false, true); } @Override public void onConnectionGone() { mConnectionActive.compareAndSet(true, false); } }; private ConnectionDefaultMonitor() { // defaults to true to avoid issue at initialization mConnectionActive = new AtomicBoolean(true); mIsRegistered = new AtomicBoolean(false); } /** * Initializes the {@link ConnectionDefaultMonitor}. It registers a {@link NetworkReceiver} in * order to be notified about network state changes. * * @param application The {@link Application} object */ public void register(@NonNull Application application) { if (mIsRegistered.compareAndSet(false, true)) { // permanently register the listener using the application context final IntentFilter filter = NetworkReceiver.getFilter(); LocalBroadcastManager.getInstance(application).registerReceiver(mNetReceiver, filter); } else {
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/network/ConnectionDefaultMonitor.java import android.app.Application; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.support.annotation.NonNull; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.common.annotations.Beta; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.concurrent.ThreadSafe; /* * Copyright 2013 Luluvise Ltd * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.utils.network; /** * Application global network connection monitor.<br> Useful to easily retrieve the device's current * connection status without querying the {@link ConnectivityManager}. * * Must be initialized by calling {@link #register(Application)} within the {@link * Application#onCreate()} method. * * @author Marco Salis * @since 1.0 */ @Beta @ThreadSafe public enum ConnectionDefaultMonitor implements ConnectionMonitor { INSTANCE; /** * Shortcut method to return the {@link ConnectionDefaultMonitor} singleton instance. */ public static ConnectionDefaultMonitor get() { return INSTANCE; } private final static String TAG = ConnectionDefaultMonitor.class.getSimpleName(); private final AtomicBoolean mConnectionActive; private final AtomicBoolean mIsRegistered; private final NetworkReceiver mNetReceiver = new NetworkReceiver() { @Override public void onConnectionActive(int type) { mConnectionActive.compareAndSet(false, true); } @Override public void onConnectionGone() { mConnectionActive.compareAndSet(true, false); } }; private ConnectionDefaultMonitor() { // defaults to true to avoid issue at initialization mConnectionActive = new AtomicBoolean(true); mIsRegistered = new AtomicBoolean(false); } /** * Initializes the {@link ConnectionDefaultMonitor}. It registers a {@link NetworkReceiver} in * order to be notified about network state changes. * * @param application The {@link Application} object */ public void register(@NonNull Application application) { if (mIsRegistered.compareAndSet(false, true)) { // permanently register the listener using the application context final IntentFilter filter = NetworkReceiver.getFilter(); LocalBroadcastManager.getInstance(application).registerReceiver(mNetReceiver, filter); } else {
LogUtils.log(Log.WARN, TAG, "ConnectionMonitor multiple initialization attempt");
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/BitmapUtils.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // }
import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.io.IOException;
matrix.setRotate(rotateValue); final Bitmap originalBitmap = bitmap; bitmap = Bitmap.createBitmap(originalBitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false); originalBitmap.recycle(); } } return bitmap; } @TargetApi(11) private static Bitmap decodeMutableBitmap(@NonNull String picturePath, @NonNull BitmapFactory.Options options) { options.inMutable = true; return BitmapFactory.decodeFile(picturePath, options); } /** * Gets the orientation of a JPEG file with EXIF attributes * * @param path The path of the JPEG to analyse * @return The orientation constant, see {@link ExifInterface} * @throws IOException */ public static int getExifOrientation(@NonNull String path) { ExifInterface exif = null; final int defOrientation = ExifInterface.ORIENTATION_NORMAL; try { exif = new ExifInterface(path); } catch (IOException e) {
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/android/LogUtils.java // @Beta // public class LogUtils { // // @SuppressWarnings("unused") // private static final String TAG = LogUtils.class.getSimpleName(); // // private LogUtils() { // // hidden constructor, no instantiation needed // } // // /** // * Logs a message in LogCat, only if library debugging is active. // * // * @param logLevel The log level to use: must be one of the level constants provided by the // * {@link Log} class. // * @param logTag // * @param logMessage // */ // public static void log(int logLevel, String logTag, String logMessage) { // if (DroidConfig.DEBUG) { // switch (logLevel) { // case Log.ASSERT: // case Log.VERBOSE: // Log.v(logTag, logMessage); // break; // case Log.DEBUG: // Log.d(logTag, logMessage); // break; // case Log.INFO: // Log.i(logTag, logMessage); // break; // case Log.WARN: // Log.w(logTag, logMessage); // break; // case Log.ERROR: // Log.e(logTag, logMessage); // break; // } // } // } // // /** // * Prints on LogCat a stack track of an exception, only if library debugging is active. // * // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // t.printStackTrace(); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception stack, only if library debugging is // * active. // * // * @param logTag // * @param logMessage // * @param t The {@link Throwable} to get the stack trace from // */ // public static void logException(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, logMessage, t); // } // } // } // // /** // * Prints on LogCat a log warning message with the exception's message string, only if library // * debugging is active. // * // * @param t The {@link Throwable} to get the message from // */ // public static void logExceptionMessage(String logTag, String logMessage, Throwable t) { // if (DroidConfig.DEBUG) { // if (t != null) { // Log.w(logTag, // logMessage + "\n" + t.getClass().getSimpleName() + " message: " // + t.getMessage()); // } // } // } // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/utils/BitmapUtils.java import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.ContentResolver; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.github.marcosalis.kraken.utils.android.LogUtils; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.io.IOException; matrix.setRotate(rotateValue); final Bitmap originalBitmap = bitmap; bitmap = Bitmap.createBitmap(originalBitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false); originalBitmap.recycle(); } } return bitmap; } @TargetApi(11) private static Bitmap decodeMutableBitmap(@NonNull String picturePath, @NonNull BitmapFactory.Options options) { options.inMutable = true; return BitmapFactory.decodeFile(picturePath, options); } /** * Gets the orientation of a JPEG file with EXIF attributes * * @param path The path of the JPEG to analyse * @return The orientation constant, see {@link ExifInterface} * @throws IOException */ public static int getExifOrientation(@NonNull String path) { ExifInterface exif = null; final int defOrientation = ExifInterface.ORIENTATION_NORMAL; try { exif = new ExifInterface(path); } catch (IOException e) {
LogUtils.logException(e);
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/AccessPolicy.java // @Beta // public enum AccessPolicy { // // /** // * Normal content fetching: passes through all levels of cache, if there is a cache miss, // * download the content from the server. // */ // NORMAL, // // /** // * Attempt a cache only content fetching.<br> If there is a total cache miss, do nothing. // */ // CACHE_ONLY, // // /** // * Pre-fetch data that could be needed soon.<br> If the data is not available in cache, schedule // * a content download. // */ // PRE_FETCH, // // /** // * Refresh the cache data, and return the updated content if any. // */ // REFRESH; // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // }
import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.AccessPolicy; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta;
/* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap; /** * Public interface to access a {@link Bitmap}s cache. * * All the methods implementations are asynchronous and must be executed from the UI thread. * * @author Marco Salis * @since 1.0 */ @Beta public interface BitmapCache extends ContentProxy { /** * Callback interface to retrieve the result of a Bitmap loading from a {@link BitmapCache}. * * The callback methods can be executed in an internal pool thread, not in the caller thread. * Make sure you are handling this when dealing with UI and non-thread safe code. */ @Beta public interface OnBitmapRetrievalListener { /** * Called when a Bitmap has been retrieved from the cache. * * @param key The {@link CacheUrlKey} of the bitmap * @param bitmap The retrieved Bitmap * @param source The {@link CacheSource} from where the bitmap has been retrieved */
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/AccessPolicy.java // @Beta // public enum AccessPolicy { // // /** // * Normal content fetching: passes through all levels of cache, if there is a cache miss, // * download the content from the server. // */ // NORMAL, // // /** // * Attempt a cache only content fetching.<br> If there is a total cache miss, do nothing. // */ // CACHE_ONLY, // // /** // * Pre-fetch data that could be needed soon.<br> If the data is not available in cache, schedule // * a content download. // */ // PRE_FETCH, // // /** // * Refresh the cache data, and return the updated content if any. // */ // REFRESH; // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.AccessPolicy; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta; /* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap; /** * Public interface to access a {@link Bitmap}s cache. * * All the methods implementations are asynchronous and must be executed from the UI thread. * * @author Marco Salis * @since 1.0 */ @Beta public interface BitmapCache extends ContentProxy { /** * Callback interface to retrieve the result of a Bitmap loading from a {@link BitmapCache}. * * The callback methods can be executed in an internal pool thread, not in the caller thread. * Make sure you are handling this when dealing with UI and non-thread safe code. */ @Beta public interface OnBitmapRetrievalListener { /** * Called when a Bitmap has been retrieved from the cache. * * @param key The {@link CacheUrlKey} of the bitmap * @param bitmap The retrieved Bitmap * @param source The {@link CacheSource} from where the bitmap has been retrieved */
public void onBitmapRetrieved(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap,
marcosalis/kraken
kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/AccessPolicy.java // @Beta // public enum AccessPolicy { // // /** // * Normal content fetching: passes through all levels of cache, if there is a cache miss, // * download the content from the server. // */ // NORMAL, // // /** // * Attempt a cache only content fetching.<br> If there is a total cache miss, do nothing. // */ // CACHE_ONLY, // // /** // * Pre-fetch data that could be needed soon.<br> If the data is not available in cache, schedule // * a content download. // */ // PRE_FETCH, // // /** // * Refresh the cache data, and return the updated content if any. // */ // REFRESH; // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // }
import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.AccessPolicy; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta;
/* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap; /** * Public interface to access a {@link Bitmap}s cache. * * All the methods implementations are asynchronous and must be executed from the UI thread. * * @author Marco Salis * @since 1.0 */ @Beta public interface BitmapCache extends ContentProxy { /** * Callback interface to retrieve the result of a Bitmap loading from a {@link BitmapCache}. * * The callback methods can be executed in an internal pool thread, not in the caller thread. * Make sure you are handling this when dealing with UI and non-thread safe code. */ @Beta public interface OnBitmapRetrievalListener { /** * Called when a Bitmap has been retrieved from the cache. * * @param key The {@link CacheUrlKey} of the bitmap * @param bitmap The retrieved Bitmap * @param source The {@link CacheSource} from where the bitmap has been retrieved */ public void onBitmapRetrieved(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap,
// Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/AccessPolicy.java // @Beta // public enum AccessPolicy { // // /** // * Normal content fetching: passes through all levels of cache, if there is a cache miss, // * download the content from the server. // */ // NORMAL, // // /** // * Attempt a cache only content fetching.<br> If there is a total cache miss, do nothing. // */ // CACHE_ONLY, // // /** // * Pre-fetch data that could be needed soon.<br> If the data is not available in cache, schedule // * a content download. // */ // PRE_FETCH, // // /** // * Refresh the cache data, and return the updated content if any. // */ // REFRESH; // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/ContentCache.java // @Beta // public enum CacheSource { // MEMORY, // DISK, // NETWORK; // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/keys/CacheUrlKey.java // @Beta // @SuppressLint("ParcelCreator") // public interface CacheUrlKey extends CacheKey, Parcelable { // // /** // * Gets the hash string used as a key // */ // @NonNull // public String hash(); // // /** // * Gets the string URL hold by this {@link CacheUrlKey} // */ // @NonNull // public String getUrl(); // // } // // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/proxies/ContentProxy.java // @Beta // public interface ContentProxy { // // /** // * Completely clears the memory cache of this content manager. // */ // public void clearMemoryCache(); // // /** // * Synchronously clears permanent storage (DB or flash disk) cache items of this content proxy // * according to the passed {@link SimpleDiskCache.ClearMode} // */ // public void clearDiskCache(SimpleDiskCache.ClearMode mode); // // /** // * Completely wipes any permanent storage (DB or flash disk) cache for this content proxy. // * // * Note: implementations must be asynchronous and non-blocking. // */ // public void scheduleClearDiskCache(); // // /** // * Synchronously wipe any kind of cache for this content proxy. // */ // public void clearCache(); // // } // Path: kraken_lib/src/main/java/com/github/marcosalis/kraken/cache/bitmap/BitmapCache.java import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.ImageView; import com.github.marcosalis.kraken.cache.AccessPolicy; import com.github.marcosalis.kraken.cache.ContentCache.CacheSource; import com.github.marcosalis.kraken.cache.keys.CacheUrlKey; import com.github.marcosalis.kraken.cache.proxies.ContentProxy; import com.google.common.annotations.Beta; /* * Copyright 2013 Marco Salis - fast3r(at)gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.marcosalis.kraken.cache.bitmap; /** * Public interface to access a {@link Bitmap}s cache. * * All the methods implementations are asynchronous and must be executed from the UI thread. * * @author Marco Salis * @since 1.0 */ @Beta public interface BitmapCache extends ContentProxy { /** * Callback interface to retrieve the result of a Bitmap loading from a {@link BitmapCache}. * * The callback methods can be executed in an internal pool thread, not in the caller thread. * Make sure you are handling this when dealing with UI and non-thread safe code. */ @Beta public interface OnBitmapRetrievalListener { /** * Called when a Bitmap has been retrieved from the cache. * * @param key The {@link CacheUrlKey} of the bitmap * @param bitmap The retrieved Bitmap * @param source The {@link CacheSource} from where the bitmap has been retrieved */ public void onBitmapRetrieved(@NonNull CacheUrlKey key, @NonNull Bitmap bitmap,
@NonNull CacheSource source);
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSortedSet.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/SortedSet.java // public interface SortedSet<E> extends Set<E> { // /** // * Returns the first element in the set or {@code null} of the set is empty. // */ // @Nullable // E first(); // // /** // * Returns the last element in the set or {@code null} of the set is empty. // */ // @Nullable // E last(); // // /** // * Returns a set containing all elements in this set, excluding the first {@code number} of elements. // */ // @NotNull // SortedSet<E> drop(int number); // // /** // * Returns a set containing the first {@code number} of elements from this set. // */ // @NotNull // SortedSet<E> take(int number); // // @Override // @NotNull // SortedSet<E> add(E value); // // @Override // @NotNull // SortedSet<E> remove(E value); // // /** // * Returns the comparator associated with this map, or {@code null} if the default ordering is used. // */ // Comparator<? super E> comparator(); // // /** // * Returns the bottom of the set starting from the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedSet<E> from(@NotNull E value, boolean inclusive); // // /** // * Returns the top of the set up until the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedSet<E> to(@NotNull E value, boolean inclusive); // // /** // * Returns a subset of the set between the {@code from} and {@code to} keys specified. // * // * @param fromInclusive if true, the key will be included in the result, otherwise it will be excluded // * @param toInclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedSet<E> range(@NotNull E from, boolean fromInclusive, @NotNull E to, boolean toInclusive); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.SortedSet}. // */ // @NotNull // java.util.SortedSet<E> asSortedSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/SortedSetAdapter.java // public class SortedSetAdapter<E> extends SetAdapater<E> implements java.util.SortedSet<E> { // private SortedSet<E> set; // // public SortedSetAdapter(SortedSet<E> set) { // super(set); // this.set = set; // } // // @NotNull // @Override // public Comparator<? super E> comparator() { // return set.comparator(); // } // // @NotNull // @Override // public java.util.SortedSet<E> subSet(E fromElement, E toElement) { // return new SortedSetAdapter<E>(set.range(fromElement, true, toElement, false)); // } // // @NotNull // @Override // public java.util.SortedSet<E> headSet(E toElement) { // return new SortedSetAdapter<E>(set.to(toElement, false)); // } // // @NotNull // @Override // public java.util.SortedSet<E> tailSet(E fromElement) { // return new SortedSetAdapter<E>(set.from(fromElement, true)); // } // // @Override // public E first() { // if (set.isEmpty()) throw new NoSuchElementException("Empty set"); // return set.first(); // } // // @Override // public E last() { // if (set.isEmpty()) throw new NoSuchElementException("Empty set"); // return set.last(); // } // }
import com.github.andrewoma.dexx.collection.SortedSet; import com.github.andrewoma.dexx.collection.internal.adapter.SortedSetAdapter; import org.jetbrains.annotations.NotNull;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.base; /** * */ public abstract class AbstractSortedSet<E> extends AbstractSet<E> implements SortedSet<E> { @SuppressWarnings("ConstantConditions") @NotNull @Override public SortedSet<E> from(@NotNull E value, boolean inclusive) { if (isEmpty()) return this; return range(value, inclusive, last(), true); } @SuppressWarnings("ConstantConditions") @NotNull @Override public SortedSet<E> to(@NotNull E value, boolean inclusive) { if (isEmpty()) return this; return range(first(), true, value, inclusive); } @NotNull @Override public java.util.SortedSet<E> asSortedSet() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/SortedSet.java // public interface SortedSet<E> extends Set<E> { // /** // * Returns the first element in the set or {@code null} of the set is empty. // */ // @Nullable // E first(); // // /** // * Returns the last element in the set or {@code null} of the set is empty. // */ // @Nullable // E last(); // // /** // * Returns a set containing all elements in this set, excluding the first {@code number} of elements. // */ // @NotNull // SortedSet<E> drop(int number); // // /** // * Returns a set containing the first {@code number} of elements from this set. // */ // @NotNull // SortedSet<E> take(int number); // // @Override // @NotNull // SortedSet<E> add(E value); // // @Override // @NotNull // SortedSet<E> remove(E value); // // /** // * Returns the comparator associated with this map, or {@code null} if the default ordering is used. // */ // Comparator<? super E> comparator(); // // /** // * Returns the bottom of the set starting from the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedSet<E> from(@NotNull E value, boolean inclusive); // // /** // * Returns the top of the set up until the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedSet<E> to(@NotNull E value, boolean inclusive); // // /** // * Returns a subset of the set between the {@code from} and {@code to} keys specified. // * // * @param fromInclusive if true, the key will be included in the result, otherwise it will be excluded // * @param toInclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedSet<E> range(@NotNull E from, boolean fromInclusive, @NotNull E to, boolean toInclusive); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.SortedSet}. // */ // @NotNull // java.util.SortedSet<E> asSortedSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/SortedSetAdapter.java // public class SortedSetAdapter<E> extends SetAdapater<E> implements java.util.SortedSet<E> { // private SortedSet<E> set; // // public SortedSetAdapter(SortedSet<E> set) { // super(set); // this.set = set; // } // // @NotNull // @Override // public Comparator<? super E> comparator() { // return set.comparator(); // } // // @NotNull // @Override // public java.util.SortedSet<E> subSet(E fromElement, E toElement) { // return new SortedSetAdapter<E>(set.range(fromElement, true, toElement, false)); // } // // @NotNull // @Override // public java.util.SortedSet<E> headSet(E toElement) { // return new SortedSetAdapter<E>(set.to(toElement, false)); // } // // @NotNull // @Override // public java.util.SortedSet<E> tailSet(E fromElement) { // return new SortedSetAdapter<E>(set.from(fromElement, true)); // } // // @Override // public E first() { // if (set.isEmpty()) throw new NoSuchElementException("Empty set"); // return set.first(); // } // // @Override // public E last() { // if (set.isEmpty()) throw new NoSuchElementException("Empty set"); // return set.last(); // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSortedSet.java import com.github.andrewoma.dexx.collection.SortedSet; import com.github.andrewoma.dexx.collection.internal.adapter.SortedSetAdapter; import org.jetbrains.annotations.NotNull; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.base; /** * */ public abstract class AbstractSortedSet<E> extends AbstractSet<E> implements SortedSet<E> { @SuppressWarnings("ConstantConditions") @NotNull @Override public SortedSet<E> from(@NotNull E value, boolean inclusive) { if (isEmpty()) return this; return range(value, inclusive, last(), true); } @SuppressWarnings("ConstantConditions") @NotNull @Override public SortedSet<E> to(@NotNull E value, boolean inclusive) { if (isEmpty()) return this; return range(first(), true, value, inclusive); } @NotNull @Override public java.util.SortedSet<E> asSortedSet() {
return new SortedSetAdapter<E>(this);
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/Adapters.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/Break.java // public final class Break extends RuntimeException { // public static final Break instance = new Break(); // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import com.github.andrewoma.dexx.collection.internal.base.Break; import org.jetbrains.annotations.NotNull; import java.util.Collection;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.adapter; /** * */ public class Adapters { public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) { for (Object e : c) { if (!contains(traversable, e)) { return false; } } return true; } @SuppressWarnings("unchecked") public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) { try {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/Break.java // public final class Break extends RuntimeException { // public static final Break instance = new Break(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/Adapters.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import com.github.andrewoma.dexx.collection.internal.base.Break; import org.jetbrains.annotations.NotNull; import java.util.Collection; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.adapter; /** * */ public class Adapters { public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) { for (Object e : c) { if (!contains(traversable, e)) { return false; } } return true; } @SuppressWarnings("unchecked") public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) { try {
traversable.forEach(new Function<E, Object>() {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/Adapters.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/Break.java // public final class Break extends RuntimeException { // public static final Break instance = new Break(); // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import com.github.andrewoma.dexx.collection.internal.base.Break; import org.jetbrains.annotations.NotNull; import java.util.Collection;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.adapter; /** * */ public class Adapters { public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) { for (Object e : c) { if (!contains(traversable, e)) { return false; } } return true; } @SuppressWarnings("unchecked") public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) { try { traversable.forEach(new Function<E, Object>() { @Override public Object invoke(E e) { if (e.equals(o)) {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/Break.java // public final class Break extends RuntimeException { // public static final Break instance = new Break(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/Adapters.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import com.github.andrewoma.dexx.collection.internal.base.Break; import org.jetbrains.annotations.NotNull; import java.util.Collection; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.adapter; /** * */ public class Adapters { public static <E> boolean containsAll(@NotNull Traversable<E> traversable, @NotNull Collection<?> c) { for (Object e : c) { if (!contains(traversable, e)) { return false; } } return true; } @SuppressWarnings("unchecked") public static <E> boolean contains(@NotNull Traversable<E> traversable, final Object o) { try { traversable.forEach(new Function<E, Object>() { @Override public Object invoke(E e) { if (e.equals(o)) {
throw Break.instance;
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/AbstractDerivedKeyTree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // }
import com.github.andrewoma.dexx.collection.KeyFunction;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; public abstract class AbstractDerivedKeyTree<K, V> extends AbstractTree<K, V> { protected AbstractDerivedKeyTree(Tree<K, V> left, Tree<K, V> right, V value) { super(left, right, value); } public int count() { return 1 + RedBlackTree.count(getLeft()) + RedBlackTree.count(getRight()); } @Override
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/AbstractDerivedKeyTree.java import com.github.andrewoma.dexx.collection.KeyFunction; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; public abstract class AbstractDerivedKeyTree<K, V> extends AbstractTree<K, V> { protected AbstractDerivedKeyTree(Tree<K, V> left, Tree<K, V> right, V value) { super(left, right, value); } public int count() { return 1 + RedBlackTree.count(getLeft()) + RedBlackTree.count(getRight()); } @Override
public K getKey(KeyFunction<K, V> keyFunction) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/ConsList.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractLinkedList.java // public abstract class AbstractLinkedList<E> extends AbstractList<E> implements LinkedList<E> { // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // }
import com.github.andrewoma.dexx.collection.internal.base.AbstractLinkedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection; /** * {@code ConsList} is a functional {@link com.github.andrewoma.dexx.collection.LinkedList} implementation * that constructs a list by prepending an element to another list. * <p/> * <p><b>WARNING:</b> Appending to a {@code ConsList} results in copying the entire list - always * use a {@link com.github.andrewoma.dexx.collection.Builder} when appending. Likewise, * operations like {@link #set(int, Object)} will result in copying portions of the list. * <p/> * <p>If there is any doubt as to the access patterns for using a {@code List}, use a {@link com.github.andrewoma.dexx.collection.Vector} * instead. */ public abstract class ConsList<E> extends AbstractLinkedList<E> { private static final ConsList<Object> EMPTY = new Nil<Object>(); @NotNull public static <E> BuilderFactory<E, ConsList<E>> factory() { return new BuilderFactory<E, ConsList<E>>() { @NotNull @Override public Builder<E, ConsList<E>> newBuilder() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractLinkedList.java // public abstract class AbstractLinkedList<E> extends AbstractList<E> implements LinkedList<E> { // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/ConsList.java import com.github.andrewoma.dexx.collection.internal.base.AbstractLinkedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection; /** * {@code ConsList} is a functional {@link com.github.andrewoma.dexx.collection.LinkedList} implementation * that constructs a list by prepending an element to another list. * <p/> * <p><b>WARNING:</b> Appending to a {@code ConsList} results in copying the entire list - always * use a {@link com.github.andrewoma.dexx.collection.Builder} when appending. Likewise, * operations like {@link #set(int, Object)} will result in copying portions of the list. * <p/> * <p>If there is any doubt as to the access patterns for using a {@code List}, use a {@link com.github.andrewoma.dexx.collection.Vector} * instead. */ public abstract class ConsList<E> extends AbstractLinkedList<E> { private static final ConsList<Object> EMPTY = new Nil<Object>(); @NotNull public static <E> BuilderFactory<E, ConsList<E>> factory() { return new BuilderFactory<E, ConsList<E>>() { @NotNull @Override public Builder<E, ConsList<E>> newBuilder() {
return new AbstractBuilder<E, ConsList<E>>() {
andrewoma/dexx
collection/src/test/java/com/github/andrewoma/dexx/collection/mutable/MutableHashSet.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/BuilderFactory.java // public interface BuilderFactory<E, R> { // @NotNull // Builder<E, R> newBuilder(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Set.java // public interface Set<E> extends Iterable<E> { // /** // * Returns a set that adds the specified value if it doesn't already exist in this set. // */ // @NotNull // Set<E> add(E value); // // /** // * Removes the specified value from the set if it exists. // */ // @NotNull // Set<E> remove(E value); // // /** // * Returns true if the value exists in this set. // */ // boolean contains(E value); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.Set}. // */ // @NotNull // java.util.Set<E> asSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSet.java // public abstract class AbstractSet<E> extends AbstractIterable<E> implements Set<E> { // @Override // @SuppressWarnings("unchecked") // public boolean equals(Object o) { // if (o == this) // return true; // // if (!(o instanceof Set)) // return false; // // final Set other = (Set) o; // if (other.size() != size()) // return false; // // for (E a : this) { // try { // if (!other.contains(a)) { // return false; // } // } catch (NullPointerException e) { // return false; // } catch (ClassCastException e) { // return false; // } // } // // return true; // } // // @Override // public int hashCode() { // int hashCode = 0; // for (E e : this) { // hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); // } // // return hashCode; // } // // @Override // @NotNull // public java.util.Set<E> asSet() { // return new SetAdapater<E>(this); // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // }
import java.util.Iterator; import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.BuilderFactory; import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.internal.base.AbstractSet; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import java.util.HashSet;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.mutable; /** * */ public class MutableHashSet<A> extends AbstractSet<A> { private java.util.Set<A> underlying = new HashSet<A>(); @NotNull
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/BuilderFactory.java // public interface BuilderFactory<E, R> { // @NotNull // Builder<E, R> newBuilder(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Set.java // public interface Set<E> extends Iterable<E> { // /** // * Returns a set that adds the specified value if it doesn't already exist in this set. // */ // @NotNull // Set<E> add(E value); // // /** // * Removes the specified value from the set if it exists. // */ // @NotNull // Set<E> remove(E value); // // /** // * Returns true if the value exists in this set. // */ // boolean contains(E value); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.Set}. // */ // @NotNull // java.util.Set<E> asSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSet.java // public abstract class AbstractSet<E> extends AbstractIterable<E> implements Set<E> { // @Override // @SuppressWarnings("unchecked") // public boolean equals(Object o) { // if (o == this) // return true; // // if (!(o instanceof Set)) // return false; // // final Set other = (Set) o; // if (other.size() != size()) // return false; // // for (E a : this) { // try { // if (!other.contains(a)) { // return false; // } // } catch (NullPointerException e) { // return false; // } catch (ClassCastException e) { // return false; // } // } // // return true; // } // // @Override // public int hashCode() { // int hashCode = 0; // for (E e : this) { // hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); // } // // return hashCode; // } // // @Override // @NotNull // public java.util.Set<E> asSet() { // return new SetAdapater<E>(this); // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // } // Path: collection/src/test/java/com/github/andrewoma/dexx/collection/mutable/MutableHashSet.java import java.util.Iterator; import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.BuilderFactory; import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.internal.base.AbstractSet; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import java.util.HashSet; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.mutable; /** * */ public class MutableHashSet<A> extends AbstractSet<A> { private java.util.Set<A> underlying = new HashSet<A>(); @NotNull
public static <A> BuilderFactory<A, Set<A>> factory() {
andrewoma/dexx
collection/src/test/java/com/github/andrewoma/dexx/collection/mutable/MutableHashSet.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/BuilderFactory.java // public interface BuilderFactory<E, R> { // @NotNull // Builder<E, R> newBuilder(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Set.java // public interface Set<E> extends Iterable<E> { // /** // * Returns a set that adds the specified value if it doesn't already exist in this set. // */ // @NotNull // Set<E> add(E value); // // /** // * Removes the specified value from the set if it exists. // */ // @NotNull // Set<E> remove(E value); // // /** // * Returns true if the value exists in this set. // */ // boolean contains(E value); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.Set}. // */ // @NotNull // java.util.Set<E> asSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSet.java // public abstract class AbstractSet<E> extends AbstractIterable<E> implements Set<E> { // @Override // @SuppressWarnings("unchecked") // public boolean equals(Object o) { // if (o == this) // return true; // // if (!(o instanceof Set)) // return false; // // final Set other = (Set) o; // if (other.size() != size()) // return false; // // for (E a : this) { // try { // if (!other.contains(a)) { // return false; // } // } catch (NullPointerException e) { // return false; // } catch (ClassCastException e) { // return false; // } // } // // return true; // } // // @Override // public int hashCode() { // int hashCode = 0; // for (E e : this) { // hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); // } // // return hashCode; // } // // @Override // @NotNull // public java.util.Set<E> asSet() { // return new SetAdapater<E>(this); // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // }
import java.util.Iterator; import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.BuilderFactory; import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.internal.base.AbstractSet; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import java.util.HashSet;
@NotNull @Override public Set<A> add(A value) { underlying.add(value); return this; } @NotNull @Override public Set<A> remove(A value) { underlying.remove(value); return this; } @Override public int size() { return underlying.size(); } @Override public boolean contains(A value) { return underlying.contains(value); } @NotNull @Override public Iterator<A> iterator() { return underlying.iterator(); }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/BuilderFactory.java // public interface BuilderFactory<E, R> { // @NotNull // Builder<E, R> newBuilder(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Set.java // public interface Set<E> extends Iterable<E> { // /** // * Returns a set that adds the specified value if it doesn't already exist in this set. // */ // @NotNull // Set<E> add(E value); // // /** // * Removes the specified value from the set if it exists. // */ // @NotNull // Set<E> remove(E value); // // /** // * Returns true if the value exists in this set. // */ // boolean contains(E value); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.Set}. // */ // @NotNull // java.util.Set<E> asSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSet.java // public abstract class AbstractSet<E> extends AbstractIterable<E> implements Set<E> { // @Override // @SuppressWarnings("unchecked") // public boolean equals(Object o) { // if (o == this) // return true; // // if (!(o instanceof Set)) // return false; // // final Set other = (Set) o; // if (other.size() != size()) // return false; // // for (E a : this) { // try { // if (!other.contains(a)) { // return false; // } // } catch (NullPointerException e) { // return false; // } catch (ClassCastException e) { // return false; // } // } // // return true; // } // // @Override // public int hashCode() { // int hashCode = 0; // for (E e : this) { // hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); // } // // return hashCode; // } // // @Override // @NotNull // public java.util.Set<E> asSet() { // return new SetAdapater<E>(this); // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // } // Path: collection/src/test/java/com/github/andrewoma/dexx/collection/mutable/MutableHashSet.java import java.util.Iterator; import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.BuilderFactory; import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.internal.base.AbstractSet; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import java.util.HashSet; @NotNull @Override public Set<A> add(A value) { underlying.add(value); return this; } @NotNull @Override public Set<A> remove(A value) { underlying.remove(value); return this; } @Override public int size() { return underlying.size(); } @Override public boolean contains(A value) { return underlying.contains(value); } @NotNull @Override public Iterator<A> iterator() { return underlying.iterator(); }
static class MutableHashSetBuilder<A> extends AbstractBuilder<A, Set<A>> implements Builder<A, Set<A>> {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Iterable.java // public interface Iterable<E> extends Traversable<E>, java.lang.Iterable<E> { // @NotNull // Iterator<E> iterator(); // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Iterable; import org.jetbrains.annotations.NotNull; import java.util.Iterator;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.base; public class MappedIterable<T, F> extends AbstractIterable<T> { private final Function<F, T> mapFunction;
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Iterable.java // public interface Iterable<E> extends Traversable<E>, java.lang.Iterable<E> { // @NotNull // Iterator<E> iterator(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Iterable; import org.jetbrains.annotations.NotNull; import java.util.Iterator; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.base; public class MappedIterable<T, F> extends AbstractIterable<T> { private final Function<F, T> mapFunction;
private final com.github.andrewoma.dexx.collection.Iterable<F> from;
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSet.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Set.java // public interface Set<E> extends Iterable<E> { // /** // * Returns a set that adds the specified value if it doesn't already exist in this set. // */ // @NotNull // Set<E> add(E value); // // /** // * Removes the specified value from the set if it exists. // */ // @NotNull // Set<E> remove(E value); // // /** // * Returns true if the value exists in this set. // */ // boolean contains(E value); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.Set}. // */ // @NotNull // java.util.Set<E> asSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/SetAdapater.java // public class SetAdapater<E> extends java.util.AbstractSet<E> { // private Set<E> set; // // public SetAdapater(Set<E> set) { // this.set = set; // } // // @Override // public int size() { // return set.size(); // } // // @Override // public boolean isEmpty() { // return set.isEmpty(); // } // // @Override // public boolean contains(Object o) { // return Adapters.contains(set, o); // } // // @NotNull // @Override // public Iterator<E> iterator() { // return set.iterator(); // } // // @NotNull // @Override // public Object[] toArray() { // return set.toArray(); // } // // @NotNull // @Override // public <T> T[] toArray(@NotNull T[] a) { // return Adapters.toArray(set, a); // } // // @Override // public boolean add(E e) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean remove(Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean containsAll(@NotNull Collection<?> c) { // return Adapters.containsAll(set, c); // } // // @Override // public boolean addAll(@NotNull Collection<? extends E> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean retainAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean removeAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public void clear() { // throw new UnsupportedOperationException(); // } // }
import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.internal.adapter.SetAdapater; import org.jetbrains.annotations.NotNull;
return false; for (E a : this) { try { if (!other.contains(a)) { return false; } } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } return true; } @Override public int hashCode() { int hashCode = 0; for (E e : this) { hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); } return hashCode; } @Override @NotNull public java.util.Set<E> asSet() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Set.java // public interface Set<E> extends Iterable<E> { // /** // * Returns a set that adds the specified value if it doesn't already exist in this set. // */ // @NotNull // Set<E> add(E value); // // /** // * Removes the specified value from the set if it exists. // */ // @NotNull // Set<E> remove(E value); // // /** // * Returns true if the value exists in this set. // */ // boolean contains(E value); // // /** // * Returns an immutable view of this set as an instance of {@code java.util.Set}. // */ // @NotNull // java.util.Set<E> asSet(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/SetAdapater.java // public class SetAdapater<E> extends java.util.AbstractSet<E> { // private Set<E> set; // // public SetAdapater(Set<E> set) { // this.set = set; // } // // @Override // public int size() { // return set.size(); // } // // @Override // public boolean isEmpty() { // return set.isEmpty(); // } // // @Override // public boolean contains(Object o) { // return Adapters.contains(set, o); // } // // @NotNull // @Override // public Iterator<E> iterator() { // return set.iterator(); // } // // @NotNull // @Override // public Object[] toArray() { // return set.toArray(); // } // // @NotNull // @Override // public <T> T[] toArray(@NotNull T[] a) { // return Adapters.toArray(set, a); // } // // @Override // public boolean add(E e) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean remove(Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean containsAll(@NotNull Collection<?> c) { // return Adapters.containsAll(set, c); // } // // @Override // public boolean addAll(@NotNull Collection<? extends E> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean retainAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean removeAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public void clear() { // throw new UnsupportedOperationException(); // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractSet.java import com.github.andrewoma.dexx.collection.Set; import com.github.andrewoma.dexx.collection.internal.adapter.SetAdapater; import org.jetbrains.annotations.NotNull; return false; for (E a : this) { try { if (!other.contains(a)) { return false; } } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } return true; } @Override public int hashCode() { int hashCode = 0; for (E e : this) { hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode()); } return hashCode; } @Override @NotNull public java.util.Set<E> asSet() {
return new SetAdapater<E>(this);
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/AbstractTree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // }
import com.github.andrewoma.dexx.collection.KeyFunction;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; public abstract class AbstractTree<K, V> implements Tree<K, V> { private final Tree<K, V> left; private final Tree<K, V> right; private final V value; protected AbstractTree(Tree<K, V> left, Tree<K, V> right, V value) { this.left = left; this.right = right; this.value = value; } public int count() { return 1 + RedBlackTree.count(getLeft()) + RedBlackTree.count(getRight()); }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/AbstractTree.java import com.github.andrewoma.dexx.collection.KeyFunction; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; public abstract class AbstractTree<K, V> implements Tree<K, V> { private final Tree<K, V> left; private final Tree<K, V> right; private final V value; protected AbstractTree(Tree<K, V> left, Tree<K, V> right, V value) { this.left = left; this.right = right; this.value = value; } public int count() { return 1 + RedBlackTree.count(getLeft()) + RedBlackTree.count(getRight()); }
public abstract K getKey(KeyFunction<K, V> keyFunction);
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/SortedMapAdapter.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/SortedMap.java // public interface SortedMap<K, V> extends Map<K, V> { // @NotNull // SortedMap<K, V> put(@NotNull K key, V value); // // @NotNull // SortedMap<K, V> remove(@NotNull K key); // // /** // * Returns the bottom of the map starting from the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedMap<K, V> from(@NotNull K key, boolean inclusive); // // /** // * Returns the top of the map up until the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedMap<K, V> to(@NotNull K key, boolean inclusive); // // /** // * Returns a subset of the map between the {@code from} and {@code to} keys specified. // * // * @param fromInclusive if true, the key will be included in the result, otherwise it will be excluded // * @param toInclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedMap<K, V> range(@NotNull K from, boolean fromInclusive, @NotNull K to, boolean toInclusive); // // /** // * Returns the comparator associated with this map, or {@code null} if the default ordering is used. // */ // Comparator<? super K> comparator(); // // /** // * Returns the first entry in the map or {@code null} if the map is empty. // */ // @Nullable // Pair<K, V> first(); // // /** // * Returns the last entry in the map or {@code null} if the map is empty. // */ // @Nullable // Pair<K, V> last(); // // /** // * Returns a map containing all elements in this map, excluding the first {@code number} of elements. // */ // @NotNull // SortedMap<K, V> drop(int number); // // /** // * Returns a list containing the first {@code number} of elements from this list. // */ // @NotNull // SortedMap<K, V> take(int number); // // /** // * Returns an immutable view of this map as an instance of {@code java.util.SortedMap}. // */ // @NotNull // java.util.SortedMap<K, V> asSortedMap(); // }
import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.SortedMap; import org.jetbrains.annotations.NotNull; import java.util.Comparator; import java.util.NoSuchElementException;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.adapter; /** * */ public class SortedMapAdapter<K, V> extends MapAdapter<K, V> implements java.util.SortedMap<K, V> { private SortedMap<K, V> map; public SortedMapAdapter(SortedMap<K, V> map) { super(map); this.map = map; } @SuppressWarnings("NullableProblems") // JetBrains annotation doesn't match the spec @Override public Comparator<? super K> comparator() { return map.comparator(); } @NotNull @Override public java.util.SortedMap<K, V> subMap(@NotNull K fromKey, @NotNull K toKey) { return new SortedMapAdapter<K, V>(map.range(fromKey, true, toKey, false)); } @NotNull @Override public java.util.SortedMap<K, V> headMap(@NotNull K toKey) { return new SortedMapAdapter<K, V>(map.to(toKey, false)); } @NotNull @Override public java.util.SortedMap<K, V> tailMap(@NotNull K fromKey) { return new SortedMapAdapter<K, V>(map.from(fromKey, true)); } @Override public K firstKey() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/SortedMap.java // public interface SortedMap<K, V> extends Map<K, V> { // @NotNull // SortedMap<K, V> put(@NotNull K key, V value); // // @NotNull // SortedMap<K, V> remove(@NotNull K key); // // /** // * Returns the bottom of the map starting from the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedMap<K, V> from(@NotNull K key, boolean inclusive); // // /** // * Returns the top of the map up until the key specified. // * // * @param inclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedMap<K, V> to(@NotNull K key, boolean inclusive); // // /** // * Returns a subset of the map between the {@code from} and {@code to} keys specified. // * // * @param fromInclusive if true, the key will be included in the result, otherwise it will be excluded // * @param toInclusive if true, the key will be included in the result, otherwise it will be excluded // */ // @NotNull // SortedMap<K, V> range(@NotNull K from, boolean fromInclusive, @NotNull K to, boolean toInclusive); // // /** // * Returns the comparator associated with this map, or {@code null} if the default ordering is used. // */ // Comparator<? super K> comparator(); // // /** // * Returns the first entry in the map or {@code null} if the map is empty. // */ // @Nullable // Pair<K, V> first(); // // /** // * Returns the last entry in the map or {@code null} if the map is empty. // */ // @Nullable // Pair<K, V> last(); // // /** // * Returns a map containing all elements in this map, excluding the first {@code number} of elements. // */ // @NotNull // SortedMap<K, V> drop(int number); // // /** // * Returns a list containing the first {@code number} of elements from this list. // */ // @NotNull // SortedMap<K, V> take(int number); // // /** // * Returns an immutable view of this map as an instance of {@code java.util.SortedMap}. // */ // @NotNull // java.util.SortedMap<K, V> asSortedMap(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/SortedMapAdapter.java import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.SortedMap; import org.jetbrains.annotations.NotNull; import java.util.Comparator; import java.util.NoSuchElementException; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.adapter; /** * */ public class SortedMapAdapter<K, V> extends MapAdapter<K, V> implements java.util.SortedMap<K, V> { private SortedMap<K, V> map; public SortedMapAdapter(SortedMap<K, V> map) { super(map); this.map = map; } @SuppressWarnings("NullableProblems") // JetBrains annotation doesn't match the spec @Override public Comparator<? super K> comparator() { return map.comparator(); } @NotNull @Override public java.util.SortedMap<K, V> subMap(@NotNull K fromKey, @NotNull K toKey) { return new SortedMapAdapter<K, V>(map.range(fromKey, true, toKey, false)); } @NotNull @Override public java.util.SortedMap<K, V> headMap(@NotNull K toKey) { return new SortedMapAdapter<K, V>(map.to(toKey, false)); } @NotNull @Override public java.util.SortedMap<K, V> tailMap(@NotNull K fromKey) { return new SortedMapAdapter<K, V>(map.from(fromKey, true)); } @Override public K firstKey() {
Pair<K, V> first = map.first();
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/Tree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // }
import com.github.andrewoma.dexx.collection.KeyFunction;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; /** * */ public interface Tree<K, V> { int count(); boolean isBlack(); boolean isRed(); Tree<K, V> black(); Tree<K, V> red();
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/Tree.java import com.github.andrewoma.dexx.collection.KeyFunction; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; /** * */ public interface Tree<K, V> { int count(); boolean isBlack(); boolean isRed(); Tree<K, V> black(); Tree<K, V> red();
K getKey(KeyFunction<K, V> keyFunction);
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractIterable.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // }
import com.github.andrewoma.dexx.collection.Function; import org.jetbrains.annotations.NotNull;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.base; public abstract class AbstractIterable<E> extends AbstractTraversable<E> implements com.github.andrewoma.dexx.collection.Iterable<E> { @SuppressWarnings("NullableProblems") @Override
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractIterable.java import com.github.andrewoma.dexx.collection.Function; import org.jetbrains.annotations.NotNull; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.base; public abstract class AbstractIterable<E> extends AbstractTraversable<E> implements com.github.andrewoma.dexx.collection.Iterable<E> { @SuppressWarnings("NullableProblems") @Override
public <U> void forEach(@NotNull final Function<E, U> f) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/TreeIterator.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Iterator; import java.util.NoSuchElementException;
try { path[index] = tree; index += 1; } catch (ArrayIndexOutOfBoundsException e) { /* * Either the tree became unbalanced or we calculated the maximum height incorrectly. * To avoid crashing the iterator we expand the path array. Obviously this should never * happen... * * An exception handler is used instead of an if-condition to optimize the normal path. * This makes a large difference in iteration speed! */ e.printStackTrace(); assert (index >= path.length); Tree<K, V>[] temp = new Tree[path.length + 1]; System.arraycopy(path, 0, temp, 0, path.length); path = temp; pushPath(tree); } } private Tree<K, V> popPath() { if (index == 0) return null; index -= 1; return path[index]; } }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/TreeIterator.java import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Iterator; import java.util.NoSuchElementException; try { path[index] = tree; index += 1; } catch (ArrayIndexOutOfBoundsException e) { /* * Either the tree became unbalanced or we calculated the maximum height incorrectly. * To avoid crashing the iterator we expand the path array. Obviously this should never * happen... * * An exception handler is used instead of an if-condition to optimize the normal path. * This makes a large difference in iteration speed! */ e.printStackTrace(); assert (index >= path.length); Tree<K, V>[] temp = new Tree[path.length + 1]; System.arraycopy(path, 0, temp, 0, path.length); path = temp; pushPath(tree); } } private Tree<K, V> popPath() { if (index == 0) return null; index -= 1; return path[index]; } }
class EntriesIterator<K, V> extends TreeIterator<K, V, Pair<K, V>> {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/TreeIterator.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Iterator; import java.util.NoSuchElementException;
e.printStackTrace(); assert (index >= path.length); Tree<K, V>[] temp = new Tree[path.length + 1]; System.arraycopy(path, 0, temp, 0, path.length); path = temp; pushPath(tree); } } private Tree<K, V> popPath() { if (index == 0) return null; index -= 1; return path[index]; } } class EntriesIterator<K, V> extends TreeIterator<K, V, Pair<K, V>> { public EntriesIterator(Tree<K, V> tree) { super(tree); } @Override protected Pair<K, V> nextResult(Tree<K, V> tree) { return new Pair<K, V>(tree.getKey(null), tree.getValue()); } } class KeysIterator<K, V> extends TreeIterator<K, V, K> {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/TreeIterator.java import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Iterator; import java.util.NoSuchElementException; e.printStackTrace(); assert (index >= path.length); Tree<K, V>[] temp = new Tree[path.length + 1]; System.arraycopy(path, 0, temp, 0, path.length); path = temp; pushPath(tree); } } private Tree<K, V> popPath() { if (index == 0) return null; index -= 1; return path[index]; } } class EntriesIterator<K, V> extends TreeIterator<K, V, Pair<K, V>> { public EntriesIterator(Tree<K, V> tree) { super(tree); } @Override protected Pair<K, V> nextResult(Tree<K, V> tree) { return new Pair<K, V>(tree.getKey(null), tree.getValue()); } } class KeysIterator<K, V> extends TreeIterator<K, V, K> {
private final KeyFunction<K, V> kf;
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/MapAdapter.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Map.java // @SuppressWarnings("NullableProblems") // public interface Map<K, V> extends Iterable<Pair<K, V>> { // /** // * Returns a map with the value specified associated to the key specified. // * <p>If value already exists for the key, it will be replaced. // */ // @NotNull // Map<K, V> put(@NotNull K key, V value); // // /** // * Returns the value associated with the key or {@code null} if the no value exists with the key specified. // */ // @Nullable // V get(@NotNull K key); // // /** // * Returns a map with the value associated with the key removed if it exists. // */ // @NotNull // Map<K, V> remove(@NotNull K key); // // /** // * Returns the keys for this map. // */ // @NotNull // Iterable<K> keys(); // // /** // * Returns the values for this map. // */ // @NotNull // Iterable<V> values(); // // /** // * Returns true if this map contains the specified key. // */ // boolean containsKey(@NotNull K key); // // /** // * Returns an immutable view of this map as an instance of {@link java.util.Map}. // */ // @NotNull // java.util.Map<K, V> asMap(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java // public class MappedIterable<T, F> extends AbstractIterable<T> { // private final Function<F, T> mapFunction; // private final com.github.andrewoma.dexx.collection.Iterable<F> from; // // public MappedIterable(Iterable<F> from, Function<F, T> mapFunction) { // this.mapFunction = mapFunction; // this.from = from; // } // // @NotNull // @Override // public Iterator<T> iterator() { // final Iterator<F> iterator = from.iterator(); // return new Iterator<T>() { // @Override // public boolean hasNext() { // return iterator.hasNext(); // } // // @Override // public T next() { // return mapFunction.invoke(iterator.next()); // } // // @Override // public void remove() { // iterator.remove(); // } // }; // } // }
import java.util.Collection; import java.util.Iterator; import java.util.Set; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.internal.base.MappedIterable; import org.jetbrains.annotations.NotNull; import java.util.AbstractCollection; import java.util.AbstractSet;
public boolean retainAll(@NotNull Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } }; } @NotNull @Override public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K, V>>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { try { @SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>) o;
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Map.java // @SuppressWarnings("NullableProblems") // public interface Map<K, V> extends Iterable<Pair<K, V>> { // /** // * Returns a map with the value specified associated to the key specified. // * <p>If value already exists for the key, it will be replaced. // */ // @NotNull // Map<K, V> put(@NotNull K key, V value); // // /** // * Returns the value associated with the key or {@code null} if the no value exists with the key specified. // */ // @Nullable // V get(@NotNull K key); // // /** // * Returns a map with the value associated with the key removed if it exists. // */ // @NotNull // Map<K, V> remove(@NotNull K key); // // /** // * Returns the keys for this map. // */ // @NotNull // Iterable<K> keys(); // // /** // * Returns the values for this map. // */ // @NotNull // Iterable<V> values(); // // /** // * Returns true if this map contains the specified key. // */ // boolean containsKey(@NotNull K key); // // /** // * Returns an immutable view of this map as an instance of {@link java.util.Map}. // */ // @NotNull // java.util.Map<K, V> asMap(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java // public class MappedIterable<T, F> extends AbstractIterable<T> { // private final Function<F, T> mapFunction; // private final com.github.andrewoma.dexx.collection.Iterable<F> from; // // public MappedIterable(Iterable<F> from, Function<F, T> mapFunction) { // this.mapFunction = mapFunction; // this.from = from; // } // // @NotNull // @Override // public Iterator<T> iterator() { // final Iterator<F> iterator = from.iterator(); // return new Iterator<T>() { // @Override // public boolean hasNext() { // return iterator.hasNext(); // } // // @Override // public T next() { // return mapFunction.invoke(iterator.next()); // } // // @Override // public void remove() { // iterator.remove(); // } // }; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/MapAdapter.java import java.util.Collection; import java.util.Iterator; import java.util.Set; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.internal.base.MappedIterable; import org.jetbrains.annotations.NotNull; import java.util.AbstractCollection; import java.util.AbstractSet; public boolean retainAll(@NotNull Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } }; } @NotNull @Override public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K, V>>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { try { @SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>) o;
Pair<K, V> pair = new Pair<K, V>(entry.getKey(), entry.getValue());
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/MapAdapter.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Map.java // @SuppressWarnings("NullableProblems") // public interface Map<K, V> extends Iterable<Pair<K, V>> { // /** // * Returns a map with the value specified associated to the key specified. // * <p>If value already exists for the key, it will be replaced. // */ // @NotNull // Map<K, V> put(@NotNull K key, V value); // // /** // * Returns the value associated with the key or {@code null} if the no value exists with the key specified. // */ // @Nullable // V get(@NotNull K key); // // /** // * Returns a map with the value associated with the key removed if it exists. // */ // @NotNull // Map<K, V> remove(@NotNull K key); // // /** // * Returns the keys for this map. // */ // @NotNull // Iterable<K> keys(); // // /** // * Returns the values for this map. // */ // @NotNull // Iterable<V> values(); // // /** // * Returns true if this map contains the specified key. // */ // boolean containsKey(@NotNull K key); // // /** // * Returns an immutable view of this map as an instance of {@link java.util.Map}. // */ // @NotNull // java.util.Map<K, V> asMap(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java // public class MappedIterable<T, F> extends AbstractIterable<T> { // private final Function<F, T> mapFunction; // private final com.github.andrewoma.dexx.collection.Iterable<F> from; // // public MappedIterable(Iterable<F> from, Function<F, T> mapFunction) { // this.mapFunction = mapFunction; // this.from = from; // } // // @NotNull // @Override // public Iterator<T> iterator() { // final Iterator<F> iterator = from.iterator(); // return new Iterator<T>() { // @Override // public boolean hasNext() { // return iterator.hasNext(); // } // // @Override // public T next() { // return mapFunction.invoke(iterator.next()); // } // // @Override // public void remove() { // iterator.remove(); // } // }; // } // }
import java.util.Collection; import java.util.Iterator; import java.util.Set; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.internal.base.MappedIterable; import org.jetbrains.annotations.NotNull; import java.util.AbstractCollection; import java.util.AbstractSet;
public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K, V>>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { try { @SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>) o; Pair<K, V> pair = new Pair<K, V>(entry.getKey(), entry.getValue()); return Adapters.contains(map, pair); } catch (ClassCastException e) { return false; } } @NotNull @Override public Iterator<Entry<K, V>> iterator() { return getEntries().iterator(); }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Map.java // @SuppressWarnings("NullableProblems") // public interface Map<K, V> extends Iterable<Pair<K, V>> { // /** // * Returns a map with the value specified associated to the key specified. // * <p>If value already exists for the key, it will be replaced. // */ // @NotNull // Map<K, V> put(@NotNull K key, V value); // // /** // * Returns the value associated with the key or {@code null} if the no value exists with the key specified. // */ // @Nullable // V get(@NotNull K key); // // /** // * Returns a map with the value associated with the key removed if it exists. // */ // @NotNull // Map<K, V> remove(@NotNull K key); // // /** // * Returns the keys for this map. // */ // @NotNull // Iterable<K> keys(); // // /** // * Returns the values for this map. // */ // @NotNull // Iterable<V> values(); // // /** // * Returns true if this map contains the specified key. // */ // boolean containsKey(@NotNull K key); // // /** // * Returns an immutable view of this map as an instance of {@link java.util.Map}. // */ // @NotNull // java.util.Map<K, V> asMap(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java // public class MappedIterable<T, F> extends AbstractIterable<T> { // private final Function<F, T> mapFunction; // private final com.github.andrewoma.dexx.collection.Iterable<F> from; // // public MappedIterable(Iterable<F> from, Function<F, T> mapFunction) { // this.mapFunction = mapFunction; // this.from = from; // } // // @NotNull // @Override // public Iterator<T> iterator() { // final Iterator<F> iterator = from.iterator(); // return new Iterator<T>() { // @Override // public boolean hasNext() { // return iterator.hasNext(); // } // // @Override // public T next() { // return mapFunction.invoke(iterator.next()); // } // // @Override // public void remove() { // iterator.remove(); // } // }; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/MapAdapter.java import java.util.Collection; import java.util.Iterator; import java.util.Set; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.internal.base.MappedIterable; import org.jetbrains.annotations.NotNull; import java.util.AbstractCollection; import java.util.AbstractSet; public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K, V>>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { try { @SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>) o; Pair<K, V> pair = new Pair<K, V>(entry.getKey(), entry.getValue()); return Adapters.contains(map, pair); } catch (ClassCastException e) { return false; } } @NotNull @Override public Iterator<Entry<K, V>> iterator() { return getEntries().iterator(); }
private MappedIterable<Entry<K, V>, Pair<K, V>> getEntries() {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/MapAdapter.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Map.java // @SuppressWarnings("NullableProblems") // public interface Map<K, V> extends Iterable<Pair<K, V>> { // /** // * Returns a map with the value specified associated to the key specified. // * <p>If value already exists for the key, it will be replaced. // */ // @NotNull // Map<K, V> put(@NotNull K key, V value); // // /** // * Returns the value associated with the key or {@code null} if the no value exists with the key specified. // */ // @Nullable // V get(@NotNull K key); // // /** // * Returns a map with the value associated with the key removed if it exists. // */ // @NotNull // Map<K, V> remove(@NotNull K key); // // /** // * Returns the keys for this map. // */ // @NotNull // Iterable<K> keys(); // // /** // * Returns the values for this map. // */ // @NotNull // Iterable<V> values(); // // /** // * Returns true if this map contains the specified key. // */ // boolean containsKey(@NotNull K key); // // /** // * Returns an immutable view of this map as an instance of {@link java.util.Map}. // */ // @NotNull // java.util.Map<K, V> asMap(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java // public class MappedIterable<T, F> extends AbstractIterable<T> { // private final Function<F, T> mapFunction; // private final com.github.andrewoma.dexx.collection.Iterable<F> from; // // public MappedIterable(Iterable<F> from, Function<F, T> mapFunction) { // this.mapFunction = mapFunction; // this.from = from; // } // // @NotNull // @Override // public Iterator<T> iterator() { // final Iterator<F> iterator = from.iterator(); // return new Iterator<T>() { // @Override // public boolean hasNext() { // return iterator.hasNext(); // } // // @Override // public T next() { // return mapFunction.invoke(iterator.next()); // } // // @Override // public void remove() { // iterator.remove(); // } // }; // } // }
import java.util.Collection; import java.util.Iterator; import java.util.Set; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.internal.base.MappedIterable; import org.jetbrains.annotations.NotNull; import java.util.AbstractCollection; import java.util.AbstractSet;
return new AbstractSet<Entry<K, V>>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { try { @SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>) o; Pair<K, V> pair = new Pair<K, V>(entry.getKey(), entry.getValue()); return Adapters.contains(map, pair); } catch (ClassCastException e) { return false; } } @NotNull @Override public Iterator<Entry<K, V>> iterator() { return getEntries().iterator(); } private MappedIterable<Entry<K, V>, Pair<K, V>> getEntries() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Map.java // @SuppressWarnings("NullableProblems") // public interface Map<K, V> extends Iterable<Pair<K, V>> { // /** // * Returns a map with the value specified associated to the key specified. // * <p>If value already exists for the key, it will be replaced. // */ // @NotNull // Map<K, V> put(@NotNull K key, V value); // // /** // * Returns the value associated with the key or {@code null} if the no value exists with the key specified. // */ // @Nullable // V get(@NotNull K key); // // /** // * Returns a map with the value associated with the key removed if it exists. // */ // @NotNull // Map<K, V> remove(@NotNull K key); // // /** // * Returns the keys for this map. // */ // @NotNull // Iterable<K> keys(); // // /** // * Returns the values for this map. // */ // @NotNull // Iterable<V> values(); // // /** // * Returns true if this map contains the specified key. // */ // boolean containsKey(@NotNull K key); // // /** // * Returns an immutable view of this map as an instance of {@link java.util.Map}. // */ // @NotNull // java.util.Map<K, V> asMap(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/MappedIterable.java // public class MappedIterable<T, F> extends AbstractIterable<T> { // private final Function<F, T> mapFunction; // private final com.github.andrewoma.dexx.collection.Iterable<F> from; // // public MappedIterable(Iterable<F> from, Function<F, T> mapFunction) { // this.mapFunction = mapFunction; // this.from = from; // } // // @NotNull // @Override // public Iterator<T> iterator() { // final Iterator<F> iterator = from.iterator(); // return new Iterator<T>() { // @Override // public boolean hasNext() { // return iterator.hasNext(); // } // // @Override // public T next() { // return mapFunction.invoke(iterator.next()); // } // // @Override // public void remove() { // iterator.remove(); // } // }; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/MapAdapter.java import java.util.Collection; import java.util.Iterator; import java.util.Set; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Map; import com.github.andrewoma.dexx.collection.Pair; import com.github.andrewoma.dexx.collection.internal.base.MappedIterable; import org.jetbrains.annotations.NotNull; import java.util.AbstractCollection; import java.util.AbstractSet; return new AbstractSet<Entry<K, V>>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean contains(Object o) { try { @SuppressWarnings("unchecked") Entry<K, V> entry = (Entry<K, V>) o; Pair<K, V> pair = new Pair<K, V>(entry.getKey(), entry.getValue()); return Adapters.contains(map, pair); } catch (ClassCastException e) { return false; } } @NotNull @Override public Iterator<Entry<K, V>> iterator() { return getEntries().iterator(); } private MappedIterable<Entry<K, V>, Pair<K, V>> getEntries() {
return new MappedIterable<Entry<K, V>, Pair<K, V>>(map, new Function<Pair<K, V>, Entry<K, V>>() {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/Vector.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractIndexedList.java // public abstract class AbstractIndexedList<E> extends AbstractList<E> implements IndexedList<E> { // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // }
import com.github.andrewoma.dexx.collection.internal.base.AbstractIndexedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Iterator; import java.util.NoSuchElementException;
display5 = new Object[32]; display5[(oldIndex >> 25) & 31] = display4; display4 = new Object[32]; display3 = new Object[32]; display2 = new Object[32]; display1 = new Object[32]; depth += 1; } display4 = (Object[]) display5[(newIndex >> 25) & 31]; if (display4 == null) display4 = new Object[32]; display3 = (Object[]) display4[(newIndex >> 20) & 31]; if (display3 == null) display3 = new Object[32]; display2 = (Object[]) display3[(newIndex >> 15) & 31]; if (display2 == null) display2 = new Object[32]; display1 = (Object[]) display2[(newIndex >> 10) & 31]; if (display1 == null) display1 = new Object[32]; display0 = new Object[32]; } else { // level = 6 throw new IllegalArgumentException(); } } // requires structure is dirty and at pos oldIndex, // ensures structure is dirty and at pos newIndex and writable at level 0 public void gotoFreshPosWritable1(int oldIndex, int newIndex, int xor) { stabilize(oldIndex); gotoFreshPosWritable0(oldIndex, newIndex, xor); } }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractIndexedList.java // public abstract class AbstractIndexedList<E> extends AbstractList<E> implements IndexedList<E> { // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Vector.java import com.github.andrewoma.dexx.collection.internal.base.AbstractIndexedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Iterator; import java.util.NoSuchElementException; display5 = new Object[32]; display5[(oldIndex >> 25) & 31] = display4; display4 = new Object[32]; display3 = new Object[32]; display2 = new Object[32]; display1 = new Object[32]; depth += 1; } display4 = (Object[]) display5[(newIndex >> 25) & 31]; if (display4 == null) display4 = new Object[32]; display3 = (Object[]) display4[(newIndex >> 20) & 31]; if (display3 == null) display3 = new Object[32]; display2 = (Object[]) display3[(newIndex >> 15) & 31]; if (display2 == null) display2 = new Object[32]; display1 = (Object[]) display2[(newIndex >> 10) & 31]; if (display1 == null) display1 = new Object[32]; display0 = new Object[32]; } else { // level = 6 throw new IllegalArgumentException(); } } // requires structure is dirty and at pos oldIndex, // ensures structure is dirty and at pos newIndex and writable at level 0 public void gotoFreshPosWritable1(int oldIndex, int newIndex, int xor) { stabilize(oldIndex); gotoFreshPosWritable0(oldIndex, newIndex, xor); } }
class VectorBuilder<E> extends AbstractBuilder<E, Vector<E>> {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/AbstractDefaultTree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // }
import com.github.andrewoma.dexx.collection.KeyFunction;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; abstract class AbstractDefaultTree<K, V> extends AbstractTree<K, V> { private final K key; protected AbstractDefaultTree(K key, V value, Tree<K, V> left, Tree<K, V> right) { super(left, right, value); this.key = key; } @Override
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/AbstractDefaultTree.java import com.github.andrewoma.dexx.collection.KeyFunction; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.redblack; abstract class AbstractDefaultTree<K, V> extends AbstractTree<K, V> { private final K key; protected AbstractDefaultTree(K key, V value, Tree<K, V> left, Tree<K, V> right) { super(left, right, value); this.key = key; } @Override
public K getKey(KeyFunction<K, V> keyFunction) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractList.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/List.java // public interface List<E> extends Iterable<E> { // /** // * Returns the element at the specified index in this list (zero-based). // * // * @throws IndexOutOfBoundsException if the index is out of range // */ // E get(int i); // // /** // * Returns a list with the element set to the value specified at the index (zero-based). // * // * @throws IndexOutOfBoundsException if the index is out of range // */ // @NotNull // List<E> set(int i, E elem); // // /** // * Returns a list with the specified element appended to the bottom of the list. // */ // @NotNull // List<E> append(E elem); // // /** // * Returns a list with the specified element prepended to the top of the list. // */ // @NotNull // List<E> prepend(E elem); // // /** // * Returns the index of the first occurrence of the specified element in the list or -1 if there are no occurrences. // */ // int indexOf(E elem); // // /** // * Returns the index of the last occurrence of the specified element in the list or -1 if there are no occurrences. // */ // int lastIndexOf(E elem); // // /** // * Returns first element in the list or {@code null} if the list is empty. // */ // @Nullable // E first(); // // /** // * Returns last element in the list or {@code null} if the list is empty. // */ // @Nullable // E last(); // // /** // * Returns a list containing all elements in the list, excluding the first element. An empty list is // * returned if the list is empty. // */ // @NotNull // List<E> tail(); // // /** // * Returns a list containing all elements in this list, excluding the first {@code number} of elements. // */ // @NotNull // List<E> drop(int number); // // /** // * Returns a list containing the first {@code number} of elements from this list. // */ // @NotNull // List<E> take(int number); // // /** // * Returns a list containing a contiguous range of elements from this list. // * // * @param from starting index for the range (zero-based) // * @param fromInclusive if true, the element at the {@code from} index will be included // * @param to end index for the range (zero-based) // * @param toInclusive if true, the element at the {@code to} index will be included // */ // @NotNull // List<E> range(int from, boolean fromInclusive, int to, boolean toInclusive); // // /** // * Returns an immutable view of this list as an instance of {@code java.util.List}. // */ // @NotNull // java.util.List<E> asList(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/ListAdapater.java // public class ListAdapater<E> extends AbstractList<E> { // private List<E> list; // // public ListAdapater(List<E> list) { // this.list = list; // } // // @Override // public int size() { // return list.size(); // } // // @Override // public boolean isEmpty() { // return list.isEmpty(); // } // // @Override // public boolean contains(Object o) { // return Adapters.contains(list, o); // } // // @NotNull // @Override // public Iterator<E> iterator() { // return list.iterator(); // } // // @NotNull // @Override // public Object[] toArray() { // return list.toArray(); // } // // @NotNull // @Override // public <T> T[] toArray(@NotNull T[] a) { // return Adapters.toArray(list, a); // } // // @Override // public boolean add(E e) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean remove(Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean containsAll(@NotNull Collection<?> c) { // return Adapters.containsAll(list, c); // } // // @Override // public boolean addAll(@NotNull Collection<? extends E> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean retainAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean removeAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public void clear() { // throw new UnsupportedOperationException(); // } // // @NotNull // @Override // public E get(int index) { // return list.get(index); // } // }
import com.github.andrewoma.dexx.collection.List; import com.github.andrewoma.dexx.collection.internal.adapter.ListAdapater; import org.jetbrains.annotations.NotNull; import java.util.Iterator;
if (!(other instanceof List)) return false; Iterator<E> iterator = iterator(); Iterator otherIterator = ((List) other).iterator(); while (iterator.hasNext() && otherIterator.hasNext()) { E elem = iterator.next(); Object otherElem = otherIterator.next(); if (!(elem == null ? otherElem == null : elem.equals(otherElem))) return false; } return !(iterator.hasNext() || otherIterator.hasNext()); } @Override public int hashCode() { int hashCode = 1; for (E elem : this) { hashCode = 31 * hashCode + (elem == null ? 0 : elem.hashCode()); } return hashCode; } @NotNull @Override public java.util.List<E> asList() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/List.java // public interface List<E> extends Iterable<E> { // /** // * Returns the element at the specified index in this list (zero-based). // * // * @throws IndexOutOfBoundsException if the index is out of range // */ // E get(int i); // // /** // * Returns a list with the element set to the value specified at the index (zero-based). // * // * @throws IndexOutOfBoundsException if the index is out of range // */ // @NotNull // List<E> set(int i, E elem); // // /** // * Returns a list with the specified element appended to the bottom of the list. // */ // @NotNull // List<E> append(E elem); // // /** // * Returns a list with the specified element prepended to the top of the list. // */ // @NotNull // List<E> prepend(E elem); // // /** // * Returns the index of the first occurrence of the specified element in the list or -1 if there are no occurrences. // */ // int indexOf(E elem); // // /** // * Returns the index of the last occurrence of the specified element in the list or -1 if there are no occurrences. // */ // int lastIndexOf(E elem); // // /** // * Returns first element in the list or {@code null} if the list is empty. // */ // @Nullable // E first(); // // /** // * Returns last element in the list or {@code null} if the list is empty. // */ // @Nullable // E last(); // // /** // * Returns a list containing all elements in the list, excluding the first element. An empty list is // * returned if the list is empty. // */ // @NotNull // List<E> tail(); // // /** // * Returns a list containing all elements in this list, excluding the first {@code number} of elements. // */ // @NotNull // List<E> drop(int number); // // /** // * Returns a list containing the first {@code number} of elements from this list. // */ // @NotNull // List<E> take(int number); // // /** // * Returns a list containing a contiguous range of elements from this list. // * // * @param from starting index for the range (zero-based) // * @param fromInclusive if true, the element at the {@code from} index will be included // * @param to end index for the range (zero-based) // * @param toInclusive if true, the element at the {@code to} index will be included // */ // @NotNull // List<E> range(int from, boolean fromInclusive, int to, boolean toInclusive); // // /** // * Returns an immutable view of this list as an instance of {@code java.util.List}. // */ // @NotNull // java.util.List<E> asList(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/adapter/ListAdapater.java // public class ListAdapater<E> extends AbstractList<E> { // private List<E> list; // // public ListAdapater(List<E> list) { // this.list = list; // } // // @Override // public int size() { // return list.size(); // } // // @Override // public boolean isEmpty() { // return list.isEmpty(); // } // // @Override // public boolean contains(Object o) { // return Adapters.contains(list, o); // } // // @NotNull // @Override // public Iterator<E> iterator() { // return list.iterator(); // } // // @NotNull // @Override // public Object[] toArray() { // return list.toArray(); // } // // @NotNull // @Override // public <T> T[] toArray(@NotNull T[] a) { // return Adapters.toArray(list, a); // } // // @Override // public boolean add(E e) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean remove(Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean containsAll(@NotNull Collection<?> c) { // return Adapters.containsAll(list, c); // } // // @Override // public boolean addAll(@NotNull Collection<? extends E> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean retainAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean removeAll(@NotNull Collection<?> c) { // throw new UnsupportedOperationException(); // } // // @Override // public void clear() { // throw new UnsupportedOperationException(); // } // // @NotNull // @Override // public E get(int index) { // return list.get(index); // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractList.java import com.github.andrewoma.dexx.collection.List; import com.github.andrewoma.dexx.collection.internal.adapter.ListAdapater; import org.jetbrains.annotations.NotNull; import java.util.Iterator; if (!(other instanceof List)) return false; Iterator<E> iterator = iterator(); Iterator otherIterator = ((List) other).iterator(); while (iterator.hasNext() && otherIterator.hasNext()) { E elem = iterator.next(); Object otherElem = otherIterator.next(); if (!(elem == null ? otherElem == null : elem.equals(otherElem))) return false; } return !(iterator.hasNext() || otherIterator.hasNext()); } @Override public int hashCode() { int hashCode = 1; for (E elem : this) { hashCode = 31 * hashCode + (elem == null ? 0 : elem.hashCode()); } return hashCode; } @NotNull @Override public java.util.List<E> asList() {
return new ListAdapater<E>(this);
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/RedBlackTree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException;
/* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2005-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.redblack; public class RedBlackTree<K, V> { private final TreeFactory factory; private final Comparator<? super K> ordering;
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/RedBlackTree.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2005-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.redblack; public class RedBlackTree<K, V> { private final TreeFactory factory; private final Comparator<? super K> ordering;
private final KeyFunction<K, V> kf;
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/RedBlackTree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException;
public Tree<K, V> until(Tree<K, V> tree, K key, boolean inclusive) { return blacken(doUntil(tree, key, inclusive)); } public Tree<K, V> drop(Tree<K, V> tree, int n) { return blacken(doDrop(tree, n)); } public Tree<K, V> take(Tree<K, V> tree, int n) { return blacken(doTake(tree, n)); } public Tree<K, V> slice(Tree<K, V> tree, int from, int until) { return blacken(doSlice(tree, from, until)); } public Tree<K, V> smallest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getLeft() != null) result = result.getLeft(); return result; } public Tree<K, V> greatest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getRight() != null) result = result.getRight(); return result; }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/RedBlackTree.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; public Tree<K, V> until(Tree<K, V> tree, K key, boolean inclusive) { return blacken(doUntil(tree, key, inclusive)); } public Tree<K, V> drop(Tree<K, V> tree, int n) { return blacken(doDrop(tree, n)); } public Tree<K, V> take(Tree<K, V> tree, int n) { return blacken(doTake(tree, n)); } public Tree<K, V> slice(Tree<K, V> tree, int from, int until) { return blacken(doSlice(tree, from, until)); } public Tree<K, V> smallest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getLeft() != null) result = result.getLeft(); return result; } public Tree<K, V> greatest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getRight() != null) result = result.getRight(); return result; }
public <U> void forEach(Tree<K, V> tree, Function<Pair<K, V>, U> f) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/RedBlackTree.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException;
public Tree<K, V> until(Tree<K, V> tree, K key, boolean inclusive) { return blacken(doUntil(tree, key, inclusive)); } public Tree<K, V> drop(Tree<K, V> tree, int n) { return blacken(doDrop(tree, n)); } public Tree<K, V> take(Tree<K, V> tree, int n) { return blacken(doTake(tree, n)); } public Tree<K, V> slice(Tree<K, V> tree, int from, int until) { return blacken(doSlice(tree, from, until)); } public Tree<K, V> smallest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getLeft() != null) result = result.getLeft(); return result; } public Tree<K, V> greatest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getRight() != null) result = result.getRight(); return result; }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/redblack/RedBlackTree.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; public Tree<K, V> until(Tree<K, V> tree, K key, boolean inclusive) { return blacken(doUntil(tree, key, inclusive)); } public Tree<K, V> drop(Tree<K, V> tree, int n) { return blacken(doDrop(tree, n)); } public Tree<K, V> take(Tree<K, V> tree, int n) { return blacken(doTake(tree, n)); } public Tree<K, V> slice(Tree<K, V> tree, int from, int until) { return blacken(doSlice(tree, from, until)); } public Tree<K, V> smallest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getLeft() != null) result = result.getLeft(); return result; } public Tree<K, V> greatest(Tree<K, V> tree) { if (tree == null) throw new NoSuchElementException("empty map"); Tree<K, V> result = tree; while (result.getRight() != null) result = result.getRight(); return result; }
public <U> void forEach(Tree<K, V> tree, Function<Pair<K, V>, U> f) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/ArrayList.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractIndexedList.java // public abstract class AbstractIndexedList<E> extends AbstractList<E> implements IndexedList<E> { // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // }
import com.github.andrewoma.dexx.collection.internal.base.AbstractIndexedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection; /** * {@code ArrayList} is an {@code IndexedList} implementation backed by an array. * <p/> * <p><b>WARNING:</b> All modifications copy the entire backing array. {@code ArrayLists} should only be * used where modifications are infrequent and access times are critical. ArrayList is also compact * in memory usage, so may be appropriate for small lists. If there is any doubt regarding access patterns * for a {@code List} then use a {@link com.github.andrewoma.dexx.collection.Vector} instead. */ public class ArrayList<E> extends AbstractIndexedList<E> { private static final ArrayList<Object> EMPTY = new ArrayList<Object>(); private final Object[] elements; @SuppressWarnings("unchecked") public static <E> ArrayList<E> empty() { return (ArrayList<E>) EMPTY; } @NotNull public static <E> BuilderFactory<E, ArrayList<E>> factory() { return new BuilderFactory<E, ArrayList<E>>() { @NotNull @Override public Builder<E, ArrayList<E>> newBuilder() {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/base/AbstractIndexedList.java // public abstract class AbstractIndexedList<E> extends AbstractList<E> implements IndexedList<E> { // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java // public abstract class AbstractBuilder<E, R> implements Builder<E, R> { // private boolean built = false; // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Traversable<E> elements) { // elements.forEach(new Function<E, Object>() { // @Override // public Object invoke(E element) { // add(element); // return null; // } // }); // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterable<E> elements) { // for (E element : elements) { // add(element); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(@NotNull Iterator<E> iterator) { // while (iterator.hasNext()) { // add(iterator.next()); // } // return this; // } // // @NotNull // @Override // public Builder<E, R> addAll(E e1, E e2, E... es) { // add(e1); // add(e2); // for (E e : es) { // add(e); // } // return this; // } // // @NotNull // @Override // final public R build() { // if (built) throw new IllegalStateException("Builders do not support multiple calls to build()"); // built = true; // return doBuild(); // } // // @NotNull // public abstract R doBuild(); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/ArrayList.java import com.github.andrewoma.dexx.collection.internal.base.AbstractIndexedList; import com.github.andrewoma.dexx.collection.internal.builder.AbstractBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection; /** * {@code ArrayList} is an {@code IndexedList} implementation backed by an array. * <p/> * <p><b>WARNING:</b> All modifications copy the entire backing array. {@code ArrayLists} should only be * used where modifications are infrequent and access times are critical. ArrayList is also compact * in memory usage, so may be appropriate for small lists. If there is any doubt regarding access patterns * for a {@code List} then use a {@link com.github.andrewoma.dexx.collection.Vector} instead. */ public class ArrayList<E> extends AbstractIndexedList<E> { private static final ArrayList<Object> EMPTY = new ArrayList<Object>(); private final Object[] elements; @SuppressWarnings("unchecked") public static <E> ArrayList<E> empty() { return (ArrayList<E>) EMPTY; } @NotNull public static <E> BuilderFactory<E, ArrayList<E>> factory() { return new BuilderFactory<E, ArrayList<E>>() { @NotNull @Override public Builder<E, ArrayList<E>> newBuilder() {
return new AbstractBuilder<E, ArrayList<E>>() {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // }
import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import org.jetbrains.annotations.NotNull; import java.util.Iterator;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.builder; /** * */ public abstract class AbstractBuilder<E, R> implements Builder<E, R> { private boolean built = false; @NotNull @Override
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import org.jetbrains.annotations.NotNull; import java.util.Iterator; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.builder; /** * */ public abstract class AbstractBuilder<E, R> implements Builder<E, R> { private boolean built = false; @NotNull @Override
public Builder<E, R> addAll(@NotNull Traversable<E> elements) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // }
import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import org.jetbrains.annotations.NotNull; import java.util.Iterator;
/* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.builder; /** * */ public abstract class AbstractBuilder<E, R> implements Builder<E, R> { private boolean built = false; @NotNull @Override public Builder<E, R> addAll(@NotNull Traversable<E> elements) {
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Builder.java // public interface Builder<E, R> { // @NotNull // Builder<E, R> add(E element); // // @NotNull // Builder<E, R> addAll(@NotNull Traversable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull java.lang.Iterable<E> elements); // // @NotNull // Builder<E, R> addAll(@NotNull Iterator<E> iterator); // // @NotNull // Builder<E, R> addAll(E e1, E e2, E... es); // // @NotNull // R build(); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Traversable.java // public interface Traversable<E> { // /** // * All collection methods can be built upon this {@code forEach} definition. // */ // @SuppressWarnings("NullableProblems") // <U> void forEach(@NotNull Function<E, U> f); // // /** // * Returns the size of the collection. // * <p/> // * <p>Warning: infinite collections are possible, as are collections that require traversal to calculate the // * size. // */ // int size(); // // /** // * Returns true if this collection is empty. // */ // boolean isEmpty(); // // /** // * Returns this collection converted to a string by joining elements together with the specified {@code separator}. // */ // @NotNull // String makeString(@NotNull String separator); // // /** // * Returns this collection converted to a string. // * // * @param separator Specifies the joining character // * @param prefix Specifies a prefix to the string // * @param postfix Species a postfix to the string // * @param limit Specifies the maximum number of elements to join. If the limit is exceeded, additional elements are ignored. // * @param truncated If the limit is reached, the {@code truncated} value will be appended to indicate the limit was reached. // */ // @NotNull // String makeString(@NotNull String separator, @NotNull String prefix, @NotNull String postfix, int limit, @NotNull String truncated); // // /** // * Converts this collection to another collection using a builder. // */ // @NotNull // <R extends Traversable<E>> R to(@NotNull Builder<E, R> builder); // // /** // * Converts this collection to a set. // */ // @NotNull // Set<E> toSet(); // // /** // * Converts this collection to a sorted set. // */ // @NotNull // SortedSet<E> toSortedSet(Comparator<? super E> comparator); // // /** // * Converts this collection to an indexed list. // */ // @NotNull // IndexedList<E> toIndexedList(); // // /** // * Converts this collection to an array of objects. // */ // @NotNull // Object[] toArray(); // // /** // * Converts this collection to an array of objects of the correct type. // */ // @NotNull // E[] toArray(E[] array); // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/builder/AbstractBuilder.java import com.github.andrewoma.dexx.collection.Builder; import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.Traversable; import org.jetbrains.annotations.NotNull; import java.util.Iterator; /* * Copyright (c) 2014 Andrew O'Malley * * 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.github.andrewoma.dexx.collection.internal.builder; /** * */ public abstract class AbstractBuilder<E, R> implements Builder<E, R> { private boolean built = false; @NotNull @Override public Builder<E, R> addAll(@NotNull Traversable<E> elements) {
elements.forEach(new Function<E, Object>() {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/hashmap/CompactHashMap.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack;
/* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.hashmap; /** * */ public class CompactHashMap<K, V> { protected static final CompactHashMap EMPTY = new CompactHashMap();
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/hashmap/CompactHashMap.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack; /* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.hashmap; /** * */ public class CompactHashMap<K, V> { protected static final CompactHashMap EMPTY = new CompactHashMap();
public Iterator<Pair<K, V>> iterator(KeyFunction<K, V> kf) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/hashmap/CompactHashMap.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack;
/* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.hashmap; /** * */ public class CompactHashMap<K, V> { protected static final CompactHashMap EMPTY = new CompactHashMap();
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/hashmap/CompactHashMap.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack; /* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.hashmap; /** * */ public class CompactHashMap<K, V> { protected static final CompactHashMap EMPTY = new CompactHashMap();
public Iterator<Pair<K, V>> iterator(KeyFunction<K, V> kf) {
andrewoma/dexx
collection/src/main/java/com/github/andrewoma/dexx/collection/internal/hashmap/CompactHashMap.java
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // }
import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack;
/* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.hashmap; /** * */ public class CompactHashMap<K, V> { protected static final CompactHashMap EMPTY = new CompactHashMap(); public Iterator<Pair<K, V>> iterator(KeyFunction<K, V> kf) { return Collections.<Pair<K, V>>emptyList().iterator(); } public int size() { return 0; } @SuppressWarnings("unchecked") public static <K, V> CompactHashMap<K, V> empty() { return EMPTY; }
// Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Function.java // public interface Function<P, R> { // R invoke(P parameter); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/KeyFunction.java // public interface KeyFunction<K, V> { // @NotNull // K key(@NotNull V value); // } // // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/Pair.java // public class Pair<C1, C2> { // private final C1 component1; // private final C2 component2; // // public Pair(C1 component1, C2 component2) { // this.component1 = component1; // this.component2 = component2; // } // // public C1 component1() { // return component1; // } // // public C2 component2() { // return component2; // } // // @Override // public String toString() { // return "(" + component1 + ", " + component2 + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Pair pair = (Pair) o; // return !(component1 != null ? !component1.equals(pair.component1) : pair.component1 != null) // && !(component2 != null ? !component2.equals(pair.component2) : pair.component2 != null); // } // // @Override // public int hashCode() { // int result = component1 != null ? component1.hashCode() : 0; // result = 31 * result + (component2 != null ? component2.hashCode() : 0); // return result; // } // } // Path: collection/src/main/java/com/github/andrewoma/dexx/collection/internal/hashmap/CompactHashMap.java import com.github.andrewoma.dexx.collection.Function; import com.github.andrewoma.dexx.collection.KeyFunction; import com.github.andrewoma.dexx.collection.Pair; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack; /* * Copyright (c) 2014 Andrew O'Malley * * 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. */ /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package com.github.andrewoma.dexx.collection.internal.hashmap; /** * */ public class CompactHashMap<K, V> { protected static final CompactHashMap EMPTY = new CompactHashMap(); public Iterator<Pair<K, V>> iterator(KeyFunction<K, V> kf) { return Collections.<Pair<K, V>>emptyList().iterator(); } public int size() { return 0; } @SuppressWarnings("unchecked") public static <K, V> CompactHashMap<K, V> empty() { return EMPTY; }
public <U> void forEach(Function<Pair<K, V>, U> f, KeyFunction<K, V> keyFunction) {
Beloumi/PeaFactory
src/peafactory/crypto/HashStuff.java
// Path: src/peafactory/tools/Zeroizer.java // public class Zeroizer { // // private static byte zero8bit = 0; // private static char zeroChar = '\0'; // private static int zero32bit = 0; // private static long zero64bit = 0L; // // public final static void zero(byte[] input) { // if (input != null && input.length > 0) { // Arrays.fill(input, (byte) 0); // /*for (int i = 0; i < input.length; i++) { // zero8bit |= input[i]; // } */ // zero8bit |= input[input.length - 1]; // } // } // public final static void zero(int[] input) { // if (input != null && input.length > 0) { // Arrays.fill(input, 0); // /*for (int i = 0; i < input.length; i++) { // zero32bit |= input[i]; // }*/ // zero32bit |= input[input.length - 1]; // } // } // public final static void zero(long[] input) { // if (input != null && input.length > 0) { // Arrays.fill(input, 0); // /*for (int i = 0; i < input.length; i++) { // zero64bit |= input[i]; // }*/ // zero64bit |= input[input.length - 1]; // } // } // public final static void zero(char[] input) { // /*for (int i = 0; i < input.length; i++) { // zeroChar |= input[i]; // }*/ // if (input != null && input.length > 0) { // Arrays.fill(input, '\0'); // zeroChar |= input[input.length - 1]; // } // } // // public final static void zero(byte zero) { // zero = (byte) 0; // zero8bit |= zero; // } // public final static void zero(int zero) { // zero = 0; // zero32bit |= zero; // } // public final static void zero(long zero) { // zero = (byte) 0; // zero64bit |= zero; // } // public final static void zero(char zero) { // zero = '\0'; // zeroChar |= zero; // } // public final static void zeroFile(String fileName) { // RandomAccessFile raf = null; // try { // raf = new RandomAccessFile(fileName, "rw"); // byte[] zeroBytes = new byte[(int)raf.length()]; // raf.seek(0); // raf.write(zeroBytes); // raf.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // // /** // * To check the execution, this function should be // * called as last step before the application exits // */ // public final static void getZeroizationResult() { // // if (zeroChar != '\0') { // System.err.println("Zeroization failed - char: " + zeroChar); // } // // if ( (zero8bit != 0) || (zero32bit != 0) || (zero64bit != 0)) { // System.err.println("Zeroization failed - \nbyte: " + zero8bit // + "\nint: " + zero32bit // + "\nlong: " + zero64bit); // } else { // System.out.println("Zeroization: success"); // } // } // // // Test: // /* public static void main(String[] args) { // // char[] testChars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); // byte[] testBytes = new byte[128]; // Arrays.fill(testBytes, (byte) 5); // int[] testInts = new int[55]; // Arrays.fill(testInts, 55); // long[] testLongs = new long[33]; // Arrays.fill(testLongs, 33L); // byte b = (byte) 0xFF; // int i = 0xFFFFFFFF; // long l = 0xFFFFFFFFFFFFFFFFL; // char c = 'X'; // // zero(testChars); // zero(testBytes); // zero(testInts); // zero(testLongs); // // zero(b); // zero(i); // zero(l); // zero(c); // // getZeroizationResult(); // } */ // }
import cologne.eck.peafactory.tools.Zeroizer; import org.bouncycastle.crypto.Digest;
package cologne.eck.peafactory.crypto; /* * Peafactory - Production of Password Encryption Archives * Copyright (C) 2015 Axel von dem Bruch * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See: http://www.gnu.org/licenses/gpl-2.0.html * You should have received a copy of the GNU General Public License * along with this library. */ /** * Handles hash functions. */ public class HashStuff { private static Digest hashAlgo; /** * Perform a hash function and clear the input immediately * * @param input the input to hash * @return the output of the hash function */ public static final byte[] hashAndOverwrite(byte[] input) { hashAlgo.update(input, 0, input.length); byte[] digest = new byte[hashAlgo.getDigestSize()]; hashAlgo.doFinal(digest, 0);
// Path: src/peafactory/tools/Zeroizer.java // public class Zeroizer { // // private static byte zero8bit = 0; // private static char zeroChar = '\0'; // private static int zero32bit = 0; // private static long zero64bit = 0L; // // public final static void zero(byte[] input) { // if (input != null && input.length > 0) { // Arrays.fill(input, (byte) 0); // /*for (int i = 0; i < input.length; i++) { // zero8bit |= input[i]; // } */ // zero8bit |= input[input.length - 1]; // } // } // public final static void zero(int[] input) { // if (input != null && input.length > 0) { // Arrays.fill(input, 0); // /*for (int i = 0; i < input.length; i++) { // zero32bit |= input[i]; // }*/ // zero32bit |= input[input.length - 1]; // } // } // public final static void zero(long[] input) { // if (input != null && input.length > 0) { // Arrays.fill(input, 0); // /*for (int i = 0; i < input.length; i++) { // zero64bit |= input[i]; // }*/ // zero64bit |= input[input.length - 1]; // } // } // public final static void zero(char[] input) { // /*for (int i = 0; i < input.length; i++) { // zeroChar |= input[i]; // }*/ // if (input != null && input.length > 0) { // Arrays.fill(input, '\0'); // zeroChar |= input[input.length - 1]; // } // } // // public final static void zero(byte zero) { // zero = (byte) 0; // zero8bit |= zero; // } // public final static void zero(int zero) { // zero = 0; // zero32bit |= zero; // } // public final static void zero(long zero) { // zero = (byte) 0; // zero64bit |= zero; // } // public final static void zero(char zero) { // zero = '\0'; // zeroChar |= zero; // } // public final static void zeroFile(String fileName) { // RandomAccessFile raf = null; // try { // raf = new RandomAccessFile(fileName, "rw"); // byte[] zeroBytes = new byte[(int)raf.length()]; // raf.seek(0); // raf.write(zeroBytes); // raf.close(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // // /** // * To check the execution, this function should be // * called as last step before the application exits // */ // public final static void getZeroizationResult() { // // if (zeroChar != '\0') { // System.err.println("Zeroization failed - char: " + zeroChar); // } // // if ( (zero8bit != 0) || (zero32bit != 0) || (zero64bit != 0)) { // System.err.println("Zeroization failed - \nbyte: " + zero8bit // + "\nint: " + zero32bit // + "\nlong: " + zero64bit); // } else { // System.out.println("Zeroization: success"); // } // } // // // Test: // /* public static void main(String[] args) { // // char[] testChars = "abcdefghijklmnopqrstuvwxyz".toCharArray(); // byte[] testBytes = new byte[128]; // Arrays.fill(testBytes, (byte) 5); // int[] testInts = new int[55]; // Arrays.fill(testInts, 55); // long[] testLongs = new long[33]; // Arrays.fill(testLongs, 33L); // byte b = (byte) 0xFF; // int i = 0xFFFFFFFF; // long l = 0xFFFFFFFFFFFFFFFFL; // char c = 'X'; // // zero(testChars); // zero(testBytes); // zero(testInts); // zero(testLongs); // // zero(b); // zero(i); // zero(l); // zero(c); // // getZeroizationResult(); // } */ // } // Path: src/peafactory/crypto/HashStuff.java import cologne.eck.peafactory.tools.Zeroizer; import org.bouncycastle.crypto.Digest; package cologne.eck.peafactory.crypto; /* * Peafactory - Production of Password Encryption Archives * Copyright (C) 2015 Axel von dem Bruch * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * See: http://www.gnu.org/licenses/gpl-2.0.html * You should have received a copy of the GNU General Public License * along with this library. */ /** * Handles hash functions. */ public class HashStuff { private static Digest hashAlgo; /** * Perform a hash function and clear the input immediately * * @param input the input to hash * @return the output of the hash function */ public static final byte[] hashAndOverwrite(byte[] input) { hashAlgo.update(input, 0, input.length); byte[] digest = new byte[hashAlgo.getDigestSize()]; hashAlgo.doFinal(digest, 0);
Zeroizer.zero(input);
aeshell/aesh-extensions
readline/src/test/java/org.aesh.extensions/man/ManParameterTester.java
// Path: readline/src/main/java/org/aesh/extensions/manual/parser/ManParameter.java // public class ManParameter { // // List<String> out = new ArrayList<String>(); // private static String argPad = " "; // private static String textPad = " "; // // /** // * First line is the param/option name // * following lines are the description // */ // public ManParameter parseParams(List<String> input, int columns) { // out.add(argPad+ManParserUtil.convertStringToAnsi(input.get(0))); // input.remove(0); // if(!input.isEmpty()) { // StringBuilder builder = new StringBuilder(); // for(String in : input) { // if(in.trim().length() > 0) // builder.append(in.trim()).append(' '); // } // // if(builder.length() > 0) { // for(String s : Parser.splitBySizeKeepWords(builder.toString(), columns-textPad.length())) { // out.add(textPad+ManParserUtil.convertStringToAnsi(s)); // } // } // //add an empty line at the bottom to create a line separator between params // if(out.size() > 0) // out.add(" "); // } // return this; // } // // public List<String> getAsList() { // return out; // } // // public String printToTerminal() { // StringBuilder builder = new StringBuilder(); // for(String s : out) // builder.append(s).append(Config.getLineSeparator()); // // return builder.toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof ManParameter)) return false; // // ManParameter that = (ManParameter) o; // // if (out != null ? !out.equals(that.out) : that.out != null) return false; // // return true; // } // // @Override // public int hashCode() { // return out != null ? out.hashCode() : 0; // } // }
import org.aesh.extensions.manual.parser.ManParameter; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.man; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ManParameterTester { @Test public void testParameter() { List<String> input = new ArrayList<String>(); input.add("*-a, --attribute*='ATTRIBUTE'::"); assertEquals(" "+ ANSI.BOLD+ "-a, --attribute"+ ANSI.DEFAULT_TEXT+ "="+ANSI.UNDERLINE+ "ATTRIBUTE"+ ANSI.DEFAULT_TEXT+ Config.getLineSeparator(),
// Path: readline/src/main/java/org/aesh/extensions/manual/parser/ManParameter.java // public class ManParameter { // // List<String> out = new ArrayList<String>(); // private static String argPad = " "; // private static String textPad = " "; // // /** // * First line is the param/option name // * following lines are the description // */ // public ManParameter parseParams(List<String> input, int columns) { // out.add(argPad+ManParserUtil.convertStringToAnsi(input.get(0))); // input.remove(0); // if(!input.isEmpty()) { // StringBuilder builder = new StringBuilder(); // for(String in : input) { // if(in.trim().length() > 0) // builder.append(in.trim()).append(' '); // } // // if(builder.length() > 0) { // for(String s : Parser.splitBySizeKeepWords(builder.toString(), columns-textPad.length())) { // out.add(textPad+ManParserUtil.convertStringToAnsi(s)); // } // } // //add an empty line at the bottom to create a line separator between params // if(out.size() > 0) // out.add(" "); // } // return this; // } // // public List<String> getAsList() { // return out; // } // // public String printToTerminal() { // StringBuilder builder = new StringBuilder(); // for(String s : out) // builder.append(s).append(Config.getLineSeparator()); // // return builder.toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof ManParameter)) return false; // // ManParameter that = (ManParameter) o; // // if (out != null ? !out.equals(that.out) : that.out != null) return false; // // return true; // } // // @Override // public int hashCode() { // return out != null ? out.hashCode() : 0; // } // } // Path: readline/src/test/java/org.aesh.extensions/man/ManParameterTester.java import org.aesh.extensions.manual.parser.ManParameter; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.man; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ManParameterTester { @Test public void testParameter() { List<String> input = new ArrayList<String>(); input.add("*-a, --attribute*='ATTRIBUTE'::"); assertEquals(" "+ ANSI.BOLD+ "-a, --attribute"+ ANSI.DEFAULT_TEXT+ "="+ANSI.UNDERLINE+ "ATTRIBUTE"+ ANSI.DEFAULT_TEXT+ Config.getLineSeparator(),
new ManParameter().parseParams(input, 80).printToTerminal());
aeshell/aesh-extensions
aesh/src/main/java/org/aesh/extensions/more/More.java
// Path: aesh/src/main/java/org/aesh/extensions/less/SimpleFileParser.java // public class SimpleFileParser implements FileParser { // // private String pageAsString; // private String fileName; // private InputStreamReader reader; // // public SimpleFileParser() { // } // // /** // * Read from a specified filename. Also supports gzipped files. // * // * @param filename File // * @throws IOException // */ // public void setFile(String filename) throws IOException { // setFile(new File(filename)); // } // // /** // * Read from a specified file. Also supports gzipped files. // * // * @param file File // * @throws IOException // */ // public void setFile(File file) throws IOException { // if(!file.isFile()) // throw new IllegalArgumentException(file+" must be a file."); // else { // if(file.getName().endsWith("gz")) // initGzReader(file); // else // initReader(file); // } // } // // public void setFile(InputStream inputStream) { // reader = new InputStreamReader(inputStream); // } // // public void setFile(InputStream inputStream, String fileName) { // reader = new InputStreamReader(inputStream); // this.fileName = fileName; // } // // // /** // * Read a file resouce located in a jar // * // * @param fileName name // */ // public void setFileFromAJar(String fileName) { // InputStream is = this.getClass().getResourceAsStream(fileName); // if(is != null) { // this.fileName = fileName; // reader = new InputStreamReader(is); // } // } // // private void initReader(File file) throws FileNotFoundException { // fileName = file.getAbsolutePath(); // reader = new FileReader(file); // } // // public void readPageAsString(String pageAsString) { // this.pageAsString = pageAsString; // } // // @Override // public String getName() { // if(fileName != null) // return fileName; // else // return "STREAM"; // } // // private void initGzReader(File file) throws IOException { // fileName = file.getAbsolutePath(); // GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file)); // reader = new InputStreamReader(gzip); // } // // @Override // public List<String> loadPage(int columns) throws IOException { // List<String> lines = new ArrayList<String>(); // //read file and save each line in a list // if(reader != null) { // BufferedReader br = new BufferedReader(reader); // try { // String line = br.readLine(); // // while (line != null) { // if(line.length() > columns) { // //split the line in the size of column // for(String s : line.split("(?<=\\G.{"+columns+"})")) // lines.add(s); // } // else // lines.add(line); // line = br.readLine(); // } // } // finally { // br.close(); // } // } // else if(pageAsString != null) { // for(String s : pageAsString.split("\n")) { // for(String s2 : s.split("(?<=\\G.{" + columns + "})")) // lines.add(s2); // } // } // // return lines; // } // // }
import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.option.Arguments; import org.aesh.command.man.FileParser; import org.aesh.command.man.TerminalPage; import org.aesh.extensions.less.SimpleFileParser; import org.aesh.io.Resource; import org.aesh.readline.action.KeyAction; import org.aesh.readline.terminal.Key; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.aesh.command.CommandException;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.more; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ @CommandDefinition(name="more", description = "is more less?") public class More implements Command<CommandInvocation> { private int rows; private int topVisibleRow; private int prevTopVisibleRow; private StringBuilder number; private MorePage page;
// Path: aesh/src/main/java/org/aesh/extensions/less/SimpleFileParser.java // public class SimpleFileParser implements FileParser { // // private String pageAsString; // private String fileName; // private InputStreamReader reader; // // public SimpleFileParser() { // } // // /** // * Read from a specified filename. Also supports gzipped files. // * // * @param filename File // * @throws IOException // */ // public void setFile(String filename) throws IOException { // setFile(new File(filename)); // } // // /** // * Read from a specified file. Also supports gzipped files. // * // * @param file File // * @throws IOException // */ // public void setFile(File file) throws IOException { // if(!file.isFile()) // throw new IllegalArgumentException(file+" must be a file."); // else { // if(file.getName().endsWith("gz")) // initGzReader(file); // else // initReader(file); // } // } // // public void setFile(InputStream inputStream) { // reader = new InputStreamReader(inputStream); // } // // public void setFile(InputStream inputStream, String fileName) { // reader = new InputStreamReader(inputStream); // this.fileName = fileName; // } // // // /** // * Read a file resouce located in a jar // * // * @param fileName name // */ // public void setFileFromAJar(String fileName) { // InputStream is = this.getClass().getResourceAsStream(fileName); // if(is != null) { // this.fileName = fileName; // reader = new InputStreamReader(is); // } // } // // private void initReader(File file) throws FileNotFoundException { // fileName = file.getAbsolutePath(); // reader = new FileReader(file); // } // // public void readPageAsString(String pageAsString) { // this.pageAsString = pageAsString; // } // // @Override // public String getName() { // if(fileName != null) // return fileName; // else // return "STREAM"; // } // // private void initGzReader(File file) throws IOException { // fileName = file.getAbsolutePath(); // GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file)); // reader = new InputStreamReader(gzip); // } // // @Override // public List<String> loadPage(int columns) throws IOException { // List<String> lines = new ArrayList<String>(); // //read file and save each line in a list // if(reader != null) { // BufferedReader br = new BufferedReader(reader); // try { // String line = br.readLine(); // // while (line != null) { // if(line.length() > columns) { // //split the line in the size of column // for(String s : line.split("(?<=\\G.{"+columns+"})")) // lines.add(s); // } // else // lines.add(line); // line = br.readLine(); // } // } // finally { // br.close(); // } // } // else if(pageAsString != null) { // for(String s : pageAsString.split("\n")) { // for(String s2 : s.split("(?<=\\G.{" + columns + "})")) // lines.add(s2); // } // } // // return lines; // } // // } // Path: aesh/src/main/java/org/aesh/extensions/more/More.java import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.option.Arguments; import org.aesh.command.man.FileParser; import org.aesh.command.man.TerminalPage; import org.aesh.extensions.less.SimpleFileParser; import org.aesh.io.Resource; import org.aesh.readline.action.KeyAction; import org.aesh.readline.terminal.Key; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.aesh.command.CommandException; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.more; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ @CommandDefinition(name="more", description = "is more less?") public class More implements Command<CommandInvocation> { private int rows; private int topVisibleRow; private int prevTopVisibleRow; private StringBuilder number; private MorePage page;
private SimpleFileParser loader;
aeshell/aesh-extensions
readline/src/test/java/org.aesh.extensions/man/ManParserUtilTester.java
// Path: readline/src/main/java/org/aesh/extensions/manual/parser/ManParserUtil.java // public class ManParserUtil { // // private static Pattern boldRegex = Pattern.compile("(\\*[^']+\\*)|(\'\\S+\')|(::$)"); // // public static String convertStringToAnsi(String line) { // StringBuilder builder = new StringBuilder(); // Matcher matcher = boldRegex.matcher(line); // while(matcher.find()) { // if(matcher.group(1) != null) { // builder.append(line.substring(0,matcher.start(1))) // .append(ANSI.BOLD) // .append(line.substring(matcher.start(1)+1,matcher.end(1)-1)) // .append(ANSI.DEFAULT_TEXT); // //.append(line.substring(matcher.end(1))); // line = line.substring(matcher.end(1)); // matcher = boldRegex.matcher(line); // } // else if(matcher.group(2) != null) { // builder.append(line.substring(0,matcher.start(2))) // .append(ANSI.UNDERLINE) // .append(line.substring(matcher.start(2)+1,matcher.end(2)-1)) // .append(ANSI.DEFAULT_TEXT); // //.append(line.substring(matcher.end(2))); // line = line.substring(matcher.end(2)); // matcher = boldRegex.matcher(line); // } // else if(matcher.group(3) != null) { // builder.append(line.substring(0,matcher.start(3))); // line = line.substring(matcher.end(3)); // matcher = boldRegex.matcher(line); // } // } // if(line.length() > 0) // builder.append(line); // // if(builder.length() < 1) // return line; // else // return builder.toString(); // } // }
import org.aesh.extensions.manual.parser.ManParserUtil; import org.aesh.terminal.utils.ANSI; import org.junit.Test; import static org.junit.Assert.*;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.man; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ManParserUtilTester { @Test public void testBoldParser() { assertEquals(ANSI.BOLD+"foo"+ANSI.DEFAULT_TEXT,
// Path: readline/src/main/java/org/aesh/extensions/manual/parser/ManParserUtil.java // public class ManParserUtil { // // private static Pattern boldRegex = Pattern.compile("(\\*[^']+\\*)|(\'\\S+\')|(::$)"); // // public static String convertStringToAnsi(String line) { // StringBuilder builder = new StringBuilder(); // Matcher matcher = boldRegex.matcher(line); // while(matcher.find()) { // if(matcher.group(1) != null) { // builder.append(line.substring(0,matcher.start(1))) // .append(ANSI.BOLD) // .append(line.substring(matcher.start(1)+1,matcher.end(1)-1)) // .append(ANSI.DEFAULT_TEXT); // //.append(line.substring(matcher.end(1))); // line = line.substring(matcher.end(1)); // matcher = boldRegex.matcher(line); // } // else if(matcher.group(2) != null) { // builder.append(line.substring(0,matcher.start(2))) // .append(ANSI.UNDERLINE) // .append(line.substring(matcher.start(2)+1,matcher.end(2)-1)) // .append(ANSI.DEFAULT_TEXT); // //.append(line.substring(matcher.end(2))); // line = line.substring(matcher.end(2)); // matcher = boldRegex.matcher(line); // } // else if(matcher.group(3) != null) { // builder.append(line.substring(0,matcher.start(3))); // line = line.substring(matcher.end(3)); // matcher = boldRegex.matcher(line); // } // } // if(line.length() > 0) // builder.append(line); // // if(builder.length() < 1) // return line; // else // return builder.toString(); // } // } // Path: readline/src/test/java/org.aesh.extensions/man/ManParserUtilTester.java import org.aesh.extensions.manual.parser.ManParserUtil; import org.aesh.terminal.utils.ANSI; import org.junit.Test; import static org.junit.Assert.*; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.man; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ManParserUtilTester { @Test public void testBoldParser() { assertEquals(ANSI.BOLD+"foo"+ANSI.DEFAULT_TEXT,
ManParserUtil.convertStringToAnsi("*foo*"));
aeshell/aesh-extensions
readline/src/main/java/org/aesh/extensions/manual/TerminalPage.java
// Path: readline/src/main/java/org/aesh/extensions/util/FileParser.java // public interface FileParser { // // List<String> loadPage(int columns) throws IOException; // // String getName(); // }
import org.aesh.extensions.util.FileParser; import java.io.IOException; import java.util.ArrayList; import java.util.List;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.manual; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class TerminalPage { private List<String> lines;
// Path: readline/src/main/java/org/aesh/extensions/util/FileParser.java // public interface FileParser { // // List<String> loadPage(int columns) throws IOException; // // String getName(); // } // Path: readline/src/main/java/org/aesh/extensions/manual/TerminalPage.java import org.aesh.extensions.util.FileParser; import java.io.IOException; import java.util.ArrayList; import java.util.List; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.manual; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class TerminalPage { private List<String> lines;
private FileParser fileParser;
aeshell/aesh-extensions
readline/src/main/java/org/aesh/extensions/manual/page/FileDisplayer.java
// Path: readline/src/main/java/org/aesh/extensions/util/FileParser.java // public interface FileParser { // // List<String> loadPage(int columns) throws IOException; // // String getName(); // } // // Path: readline/src/main/java/org/aesh/extensions/manual/TerminalPage.java // public class TerminalPage { // private List<String> lines; // private FileParser fileParser; // // public TerminalPage(FileParser fileParser, int columns) throws IOException { // this.fileParser = fileParser; // lines = fileParser.loadPage(columns); // } // // public String getLine(int num) { // if(num < lines.size()) // return lines.get(num); // else // return ""; // } // // public List<Integer> findWord(String word) { // List<Integer> wordLines = new ArrayList<Integer>(); // for(int i=0; i < lines.size();i++) { // if(lines.get(i).contains(word)) // wordLines.add(i); // } // return wordLines; // } // // public int size() { // return lines.size(); // } // // public String getFileName() { // return fileParser.getName(); // } // // public List<String> getLines() { // return lines; // } // // public boolean hasData() { // return !lines.isEmpty(); // } // // public void clear() { // lines.clear(); // } // // public static enum Search { // SEARCHING, // RESULT, // NOT_FOUND, // NO_SEARCH // } // // }
import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import org.aesh.extensions.util.FileParser; import org.aesh.extensions.manual.TerminalPage; import org.aesh.readline.action.KeyAction; import org.aesh.readline.completion.Completion; import org.aesh.readline.terminal.Key; import org.aesh.terminal.Attributes; import org.aesh.terminal.Connection; import org.aesh.readline.util.LoggerUtil; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import java.io.IOException; import java.util.List;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.manual.page; /** * An abstract command used to display files * Implemented similar to less * * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public abstract class FileDisplayer implements Completion { private int rows; private int columns; private int topVisibleRow; private int topVisibleRowCache; //only rewrite page if rowCache != row
// Path: readline/src/main/java/org/aesh/extensions/util/FileParser.java // public interface FileParser { // // List<String> loadPage(int columns) throws IOException; // // String getName(); // } // // Path: readline/src/main/java/org/aesh/extensions/manual/TerminalPage.java // public class TerminalPage { // private List<String> lines; // private FileParser fileParser; // // public TerminalPage(FileParser fileParser, int columns) throws IOException { // this.fileParser = fileParser; // lines = fileParser.loadPage(columns); // } // // public String getLine(int num) { // if(num < lines.size()) // return lines.get(num); // else // return ""; // } // // public List<Integer> findWord(String word) { // List<Integer> wordLines = new ArrayList<Integer>(); // for(int i=0; i < lines.size();i++) { // if(lines.get(i).contains(word)) // wordLines.add(i); // } // return wordLines; // } // // public int size() { // return lines.size(); // } // // public String getFileName() { // return fileParser.getName(); // } // // public List<String> getLines() { // return lines; // } // // public boolean hasData() { // return !lines.isEmpty(); // } // // public void clear() { // lines.clear(); // } // // public static enum Search { // SEARCHING, // RESULT, // NOT_FOUND, // NO_SEARCH // } // // } // Path: readline/src/main/java/org/aesh/extensions/manual/page/FileDisplayer.java import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import org.aesh.extensions.util.FileParser; import org.aesh.extensions.manual.TerminalPage; import org.aesh.readline.action.KeyAction; import org.aesh.readline.completion.Completion; import org.aesh.readline.terminal.Key; import org.aesh.terminal.Attributes; import org.aesh.terminal.Connection; import org.aesh.readline.util.LoggerUtil; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import java.io.IOException; import java.util.List; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.manual.page; /** * An abstract command used to display files * Implemented similar to less * * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public abstract class FileDisplayer implements Completion { private int rows; private int columns; private int topVisibleRow; private int topVisibleRowCache; //only rewrite page if rowCache != row
private TerminalPage page;
aeshell/aesh-extensions
readline/src/main/java/org/aesh/extensions/manual/page/FileDisplayer.java
// Path: readline/src/main/java/org/aesh/extensions/util/FileParser.java // public interface FileParser { // // List<String> loadPage(int columns) throws IOException; // // String getName(); // } // // Path: readline/src/main/java/org/aesh/extensions/manual/TerminalPage.java // public class TerminalPage { // private List<String> lines; // private FileParser fileParser; // // public TerminalPage(FileParser fileParser, int columns) throws IOException { // this.fileParser = fileParser; // lines = fileParser.loadPage(columns); // } // // public String getLine(int num) { // if(num < lines.size()) // return lines.get(num); // else // return ""; // } // // public List<Integer> findWord(String word) { // List<Integer> wordLines = new ArrayList<Integer>(); // for(int i=0; i < lines.size();i++) { // if(lines.get(i).contains(word)) // wordLines.add(i); // } // return wordLines; // } // // public int size() { // return lines.size(); // } // // public String getFileName() { // return fileParser.getName(); // } // // public List<String> getLines() { // return lines; // } // // public boolean hasData() { // return !lines.isEmpty(); // } // // public void clear() { // lines.clear(); // } // // public static enum Search { // SEARCHING, // RESULT, // NOT_FOUND, // NO_SEARCH // } // // }
import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import org.aesh.extensions.util.FileParser; import org.aesh.extensions.manual.TerminalPage; import org.aesh.readline.action.KeyAction; import org.aesh.readline.completion.Completion; import org.aesh.readline.terminal.Key; import org.aesh.terminal.Attributes; import org.aesh.terminal.Connection; import org.aesh.readline.util.LoggerUtil; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import java.io.IOException; import java.util.List;
connection.write(line); connection.write(Config.getLineSeparator()); } } topVisibleRowCache = topVisibleRow; } else { for(int i=topVisibleRow; i < (topVisibleRow+rows-1); i++) { if(i < page.size()) { connection.write(page.getLine(i)+Config.getLineSeparator()); } } topVisibleRowCache = topVisibleRow; } displayBottom(); } } /** * highlight the specific word thats found in the search */ private void displaySearchLine(String line, String searchWord) throws IOException { int start = line.indexOf(searchWord); connection.write(line.substring(0,start)); connection.write(ANSI.INVERT_BACKGROUND); connection.write(searchWord); connection.write(ANSI.RESET); connection.write(line.substring(start + searchWord.length(), line.length())); }
// Path: readline/src/main/java/org/aesh/extensions/util/FileParser.java // public interface FileParser { // // List<String> loadPage(int columns) throws IOException; // // String getName(); // } // // Path: readline/src/main/java/org/aesh/extensions/manual/TerminalPage.java // public class TerminalPage { // private List<String> lines; // private FileParser fileParser; // // public TerminalPage(FileParser fileParser, int columns) throws IOException { // this.fileParser = fileParser; // lines = fileParser.loadPage(columns); // } // // public String getLine(int num) { // if(num < lines.size()) // return lines.get(num); // else // return ""; // } // // public List<Integer> findWord(String word) { // List<Integer> wordLines = new ArrayList<Integer>(); // for(int i=0; i < lines.size();i++) { // if(lines.get(i).contains(word)) // wordLines.add(i); // } // return wordLines; // } // // public int size() { // return lines.size(); // } // // public String getFileName() { // return fileParser.getName(); // } // // public List<String> getLines() { // return lines; // } // // public boolean hasData() { // return !lines.isEmpty(); // } // // public void clear() { // lines.clear(); // } // // public static enum Search { // SEARCHING, // RESULT, // NOT_FOUND, // NO_SEARCH // } // // } // Path: readline/src/main/java/org/aesh/extensions/manual/page/FileDisplayer.java import java.util.concurrent.CountDownLatch; import java.util.logging.Logger; import org.aesh.extensions.util.FileParser; import org.aesh.extensions.manual.TerminalPage; import org.aesh.readline.action.KeyAction; import org.aesh.readline.completion.Completion; import org.aesh.readline.terminal.Key; import org.aesh.terminal.Attributes; import org.aesh.terminal.Connection; import org.aesh.readline.util.LoggerUtil; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import java.io.IOException; import java.util.List; connection.write(line); connection.write(Config.getLineSeparator()); } } topVisibleRowCache = topVisibleRow; } else { for(int i=topVisibleRow; i < (topVisibleRow+rows-1); i++) { if(i < page.size()) { connection.write(page.getLine(i)+Config.getLineSeparator()); } } topVisibleRowCache = topVisibleRow; } displayBottom(); } } /** * highlight the specific word thats found in the search */ private void displaySearchLine(String line, String searchWord) throws IOException { int start = line.indexOf(searchWord); connection.write(line.substring(0,start)); connection.write(ANSI.INVERT_BACKGROUND); connection.write(searchWord); connection.write(ANSI.RESET); connection.write(line.substring(start + searchWord.length(), line.length())); }
public abstract FileParser getFileParser();
aeshell/aesh-extensions
readline/src/test/java/org.aesh.extensions/man/ManSectionTester.java
// Path: readline/src/main/java/org/aesh/extensions/manual/parser/ManSection.java // public class ManSection { // // private String name; // private List<ManParameter> parameters; // // public ManSection() { // parameters = new ArrayList<ManParameter>(); // } // // public ManSection parseSection(List<String> input, int columns) { // //we ignore the links atm // if(input.get(0).startsWith("[[")) // input.remove(0); // //first line should be the name // name = input.get(0); // input.remove(0); // //the first section, ignoring it for now // //starting a new section // if(input.get(0).startsWith("-") && // input.get(0).trim().length() == name.length()) { // input.remove(0); // //a new param // List<String> newOption = new ArrayList<String>(); // boolean startingNewOption = false; // boolean paramName = false; // for(String in : input) { // if(in.trim().length() > 0) // newOption.add(in); // else { // if(newOption.size() > 0) { // parameters.add(new ManParameter().parseParams(newOption, columns)); // newOption.clear(); // } // } // } // if(!newOption.isEmpty()) // parameters.add(new ManParameter().parseParams(newOption, columns)); // } // // return this; // } // // public String getName() { // return name; // } // // public List<ManParameter> getParameters() { // return parameters; // } // // public List<String> getAsList() { // List<String> out = new ArrayList<String>(); // out.add(ANSI.BOLD+name+ANSI.DEFAULT_TEXT); // for(ManParameter param : parameters) // out.addAll(param.getAsList()); // // // add an empty line as line separator between sections // out.add(" "); // return out; // } // // public String printToTerminal() { // StringBuilder builder = new StringBuilder(); // builder.append(ANSI.BOLD).append(name).append(ANSI.DEFAULT_TEXT); // builder.append(Config.getLineSeparator()); // for(ManParameter param : parameters) // builder.append(param.printToTerminal()); // // return builder.toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof ManSection)) return false; // // ManSection that = (ManSection) o; // // if (!name.equals(that.name)) return false; // if (!parameters.equals(that.parameters)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + parameters.hashCode(); // return result; // } // }
import org.aesh.extensions.manual.parser.ManSection; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.man; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ManSectionTester { @Test public void testManSection() { List<String> input = new ArrayList<String>(); input.add("OPTIONS"); input.add("-------"); input.add("*-a, --attribute*='ATTRIBUTE'::"); input.add(" Define or delete document attribute. "); input.add("\n"); input.add("*-b, --backend*='BACKEND'::"); input.add(" Define or delete document attribute.");
// Path: readline/src/main/java/org/aesh/extensions/manual/parser/ManSection.java // public class ManSection { // // private String name; // private List<ManParameter> parameters; // // public ManSection() { // parameters = new ArrayList<ManParameter>(); // } // // public ManSection parseSection(List<String> input, int columns) { // //we ignore the links atm // if(input.get(0).startsWith("[[")) // input.remove(0); // //first line should be the name // name = input.get(0); // input.remove(0); // //the first section, ignoring it for now // //starting a new section // if(input.get(0).startsWith("-") && // input.get(0).trim().length() == name.length()) { // input.remove(0); // //a new param // List<String> newOption = new ArrayList<String>(); // boolean startingNewOption = false; // boolean paramName = false; // for(String in : input) { // if(in.trim().length() > 0) // newOption.add(in); // else { // if(newOption.size() > 0) { // parameters.add(new ManParameter().parseParams(newOption, columns)); // newOption.clear(); // } // } // } // if(!newOption.isEmpty()) // parameters.add(new ManParameter().parseParams(newOption, columns)); // } // // return this; // } // // public String getName() { // return name; // } // // public List<ManParameter> getParameters() { // return parameters; // } // // public List<String> getAsList() { // List<String> out = new ArrayList<String>(); // out.add(ANSI.BOLD+name+ANSI.DEFAULT_TEXT); // for(ManParameter param : parameters) // out.addAll(param.getAsList()); // // // add an empty line as line separator between sections // out.add(" "); // return out; // } // // public String printToTerminal() { // StringBuilder builder = new StringBuilder(); // builder.append(ANSI.BOLD).append(name).append(ANSI.DEFAULT_TEXT); // builder.append(Config.getLineSeparator()); // for(ManParameter param : parameters) // builder.append(param.printToTerminal()); // // return builder.toString(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof ManSection)) return false; // // ManSection that = (ManSection) o; // // if (!name.equals(that.name)) return false; // if (!parameters.equals(that.parameters)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = name.hashCode(); // result = 31 * result + parameters.hashCode(); // return result; // } // } // Path: readline/src/test/java/org.aesh.extensions/man/ManSectionTester.java import org.aesh.extensions.manual.parser.ManSection; import org.aesh.terminal.utils.ANSI; import org.aesh.terminal.utils.Config; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.man; /** * @author <a href="mailto:stale.pedersen@jboss.org">Ståle W. Pedersen</a> */ public class ManSectionTester { @Test public void testManSection() { List<String> input = new ArrayList<String>(); input.add("OPTIONS"); input.add("-------"); input.add("*-a, --attribute*='ATTRIBUTE'::"); input.add(" Define or delete document attribute. "); input.add("\n"); input.add("*-b, --backend*='BACKEND'::"); input.add(" Define or delete document attribute.");
ManSection section = new ManSection().parseSection(input, 80);
aeshell/aesh-extensions
aesh/src/test/java/org/aesh/extensions/text/highlight/encoder/NullEncoder.java
// Path: aesh/src/main/java/org/aesh/extensions/highlight/Encoder.java // public interface Encoder { // // void textToken(String text, TokenType type); // // void beginGroup(TokenType type); // // void endGroup(TokenType type); // // void beginLine(TokenType type); // // void endLine(TokenType type); // // public enum Type { // TERMINAL, DEBUG // } // // public abstract static class AbstractEncoder implements Encoder { // public static final String NEW_LINE = System.getProperty("line.separator"); // // protected OutputStream out; // protected Theme theme; // protected Map<String, Object> options; // // public AbstractEncoder(OutputStream out, Theme theme, Map<String, Object> options) { // this.out = out; // this.theme = theme; // this.options = options; // } // // protected Color color(TokenType type) { // return this.theme.lookup(type); // } // // protected void write(String str) { // try { // out.write(str.getBytes()); // } // catch (IOException e) { // throw new RuntimeException("Could not write to output", e); // } // } // // protected void write(byte[] bytes) { // try { // out.write(bytes); // } // catch (IOException e) { // throw new RuntimeException("Could not write to output", e); // } // } // } // // public static class Factory { // private static Factory factory; // // private Map<String, Class<? extends Encoder>> registry; // // private Factory() { // this.registry = new HashMap<>(); // } // // private static Factory instance() { // if (factory == null) { // factory = new Factory(); // } // return factory; // } // // public static void registrer(String type, Class<? extends Encoder> encoder) { // instance().registry.put(type, encoder); // } // // public static Encoder create(String type, OutputStream out, Theme theme, Map<String, Object> options) { // Class<? extends Encoder> encoder = instance().registry.get(type); // if (encoder != null) { // try { // Constructor<? extends Encoder> constructor = encoder.getConstructor(OutputStream.class, Theme.class, // Map.class); // return constructor.newInstance(out, theme, options); // } // catch (Exception e) { // throw new RuntimeException("Could not create new instance of " + encoder); // } // } // throw new RuntimeException("No encoder found for type " + type); // } // } // } // // Path: aesh/src/main/java/org/aesh/extensions/highlight/TokenType.java // public enum TokenType { // debug, // highlight for debugging (white on blue background) // // annotation, // Groovy, Java // attribute_name, // HTML, CSS // attribute_value, // HTML // binary, // Python, Ruby // char_, // most scanners, also inside of strings // class_, // lots of scanners, for different purposes also in CSS // class_variable, // Ruby, YAML // color, // CSS // comment, // most scanners // constant, // PHP, Ruby // content, // inside of strings, most scanners // decorator, // Python // definition, // CSS // delimiter, // inside strings, comments and other types // directive, // lots of scanners // doctype, // Goorvy, HTML, Ruby, YAML // docstring, // Python // done, // Taskpaper // entity, // HTML // error, // invalid token, most scanners // escape, // Ruby (string inline variables like //$foo, //@bar) // exception, // Java, PHP, Python // filename, // Diff // float_, // most scanners // function, // CSS, JavaScript, PHP // method, // groovy // global_variable, // Ruby, YAML // hex, // hexadecimal number; lots of scanners // id, // CSS // imaginary, // Python // important, // CSS, Taskpaper // include, // C, Groovy, Java, Python, Sass // inline, // nested code, eg. inline string evaluation; lots of scanners // inline_delimiter, // used instead of :inline > :delimiter FIXME: Why use inline_delimiter? // instance_variable, // Ruby // integer, // most scanners // key, // lots of scanners, used together with :value // keyword, // reserved word that's actually implemented; most scanners // label, // C, PHP // local_variable, // local and magic variables; some scanners // map, // Lua tables // modifier, // used inside on strings; lots of scanners // namespace, // Clojure, Java, Taskpaper // octal, // lots of scanners // predefined, // predefined function: lots of scanners // predefined_constant, // lots of scanners // predefined_type, // C, Java, PHP // preprocessor, // C, Delphi, HTML // pseudo_class, // CSS // regexp, // Groovy, JavaScript, Ruby // reserved, // most scanners // shell, // Ruby // string, // most scanners // symbol, // Clojure, Ruby, YAML // tag, // CSS, HTML // type, // CSS, Java, SQL, YAML // value, // used together with :key; CSS, JSON, YAML // variable, // Sass, SQL, YAML // // change, // Diff // delete, // Diff // head, // Diff, YAML // insert, // Diff // eyecatcher, // Diff // // ident, // almost all scanners // operator, // almost all scanners // // space, // almost all scanners // plain, // almost all scanners // unknown // }
import org.aesh.extensions.highlight.Encoder; import org.aesh.extensions.highlight.TokenType;
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.text.highlight.encoder; public class NullEncoder implements Encoder { @Override
// Path: aesh/src/main/java/org/aesh/extensions/highlight/Encoder.java // public interface Encoder { // // void textToken(String text, TokenType type); // // void beginGroup(TokenType type); // // void endGroup(TokenType type); // // void beginLine(TokenType type); // // void endLine(TokenType type); // // public enum Type { // TERMINAL, DEBUG // } // // public abstract static class AbstractEncoder implements Encoder { // public static final String NEW_LINE = System.getProperty("line.separator"); // // protected OutputStream out; // protected Theme theme; // protected Map<String, Object> options; // // public AbstractEncoder(OutputStream out, Theme theme, Map<String, Object> options) { // this.out = out; // this.theme = theme; // this.options = options; // } // // protected Color color(TokenType type) { // return this.theme.lookup(type); // } // // protected void write(String str) { // try { // out.write(str.getBytes()); // } // catch (IOException e) { // throw new RuntimeException("Could not write to output", e); // } // } // // protected void write(byte[] bytes) { // try { // out.write(bytes); // } // catch (IOException e) { // throw new RuntimeException("Could not write to output", e); // } // } // } // // public static class Factory { // private static Factory factory; // // private Map<String, Class<? extends Encoder>> registry; // // private Factory() { // this.registry = new HashMap<>(); // } // // private static Factory instance() { // if (factory == null) { // factory = new Factory(); // } // return factory; // } // // public static void registrer(String type, Class<? extends Encoder> encoder) { // instance().registry.put(type, encoder); // } // // public static Encoder create(String type, OutputStream out, Theme theme, Map<String, Object> options) { // Class<? extends Encoder> encoder = instance().registry.get(type); // if (encoder != null) { // try { // Constructor<? extends Encoder> constructor = encoder.getConstructor(OutputStream.class, Theme.class, // Map.class); // return constructor.newInstance(out, theme, options); // } // catch (Exception e) { // throw new RuntimeException("Could not create new instance of " + encoder); // } // } // throw new RuntimeException("No encoder found for type " + type); // } // } // } // // Path: aesh/src/main/java/org/aesh/extensions/highlight/TokenType.java // public enum TokenType { // debug, // highlight for debugging (white on blue background) // // annotation, // Groovy, Java // attribute_name, // HTML, CSS // attribute_value, // HTML // binary, // Python, Ruby // char_, // most scanners, also inside of strings // class_, // lots of scanners, for different purposes also in CSS // class_variable, // Ruby, YAML // color, // CSS // comment, // most scanners // constant, // PHP, Ruby // content, // inside of strings, most scanners // decorator, // Python // definition, // CSS // delimiter, // inside strings, comments and other types // directive, // lots of scanners // doctype, // Goorvy, HTML, Ruby, YAML // docstring, // Python // done, // Taskpaper // entity, // HTML // error, // invalid token, most scanners // escape, // Ruby (string inline variables like //$foo, //@bar) // exception, // Java, PHP, Python // filename, // Diff // float_, // most scanners // function, // CSS, JavaScript, PHP // method, // groovy // global_variable, // Ruby, YAML // hex, // hexadecimal number; lots of scanners // id, // CSS // imaginary, // Python // important, // CSS, Taskpaper // include, // C, Groovy, Java, Python, Sass // inline, // nested code, eg. inline string evaluation; lots of scanners // inline_delimiter, // used instead of :inline > :delimiter FIXME: Why use inline_delimiter? // instance_variable, // Ruby // integer, // most scanners // key, // lots of scanners, used together with :value // keyword, // reserved word that's actually implemented; most scanners // label, // C, PHP // local_variable, // local and magic variables; some scanners // map, // Lua tables // modifier, // used inside on strings; lots of scanners // namespace, // Clojure, Java, Taskpaper // octal, // lots of scanners // predefined, // predefined function: lots of scanners // predefined_constant, // lots of scanners // predefined_type, // C, Java, PHP // preprocessor, // C, Delphi, HTML // pseudo_class, // CSS // regexp, // Groovy, JavaScript, Ruby // reserved, // most scanners // shell, // Ruby // string, // most scanners // symbol, // Clojure, Ruby, YAML // tag, // CSS, HTML // type, // CSS, Java, SQL, YAML // value, // used together with :key; CSS, JSON, YAML // variable, // Sass, SQL, YAML // // change, // Diff // delete, // Diff // head, // Diff, YAML // insert, // Diff // eyecatcher, // Diff // // ident, // almost all scanners // operator, // almost all scanners // // space, // almost all scanners // plain, // almost all scanners // unknown // } // Path: aesh/src/test/java/org/aesh/extensions/text/highlight/encoder/NullEncoder.java import org.aesh.extensions.highlight.Encoder; import org.aesh.extensions.highlight.TokenType; /* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.aesh.extensions.text.highlight.encoder; public class NullEncoder implements Encoder { @Override
public void textToken(String text, TokenType type) {
aeshell/aesh-extensions
aesh/src/main/java/org/aesh/extensions/ls/Ls.java
// Path: aesh/src/main/java/org/aesh/extensions/tty/AeshPosixFilePermissions.java // public class AeshPosixFilePermissions { // private AeshPosixFilePermissions() { } // // // Write string representation of permission bits to {@code sb}. // private static void writeBits(StringBuilder sb, boolean r, boolean w, boolean x) { // if (r) { // sb.append('r'); // } else { // sb.append('-'); // } // if (w) { // sb.append('w'); // } else { // sb.append('-'); // } // if (x) { // sb.append('x'); // } else { // sb.append('-'); // } // } // // /** // * @return the string representation of the file // */ // public static String toString(PosixFileAttributes attr) { // Set<PosixFilePermission> perms = attr.permissions(); // StringBuilder sb = new StringBuilder(10); // if(attr.isDirectory()) // sb.append('d'); // else if(attr.isSymbolicLink()) // sb.append('l'); // else // sb.append('-'); // // writeBits(sb, perms.contains(OWNER_READ), perms.contains(OWNER_WRITE), // perms.contains(OWNER_EXECUTE)); // writeBits(sb, perms.contains(GROUP_READ), perms.contains(GROUP_WRITE), // perms.contains(GROUP_EXECUTE)); // writeBits(sb, perms.contains(OTHERS_READ), perms.contains(OTHERS_WRITE), // perms.contains(OTHERS_EXECUTE)); // return sb.toString(); // } // }
import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.command.shell.Shell; import org.aesh.comparators.PosixFileNameComparator; import org.aesh.extensions.tty.AeshPosixFilePermissions; import org.aesh.io.Resource; import org.aesh.io.filter.NoDotNamesFilter; import org.aesh.readline.terminal.formatting.Color; import org.aesh.readline.terminal.formatting.TerminalColor; import org.aesh.readline.terminal.formatting.TerminalString; import org.aesh.readline.util.Parser; import org.aesh.terminal.utils.Config; import java.io.IOException; import java.math.RoundingMode; import java.nio.file.LinkOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.DosFileAttributes; import java.nio.file.attribute.PosixFileAttributes; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List;
} private void displayFile(Resource input, Shell shell) { if(longListing) { List<Resource> resourceList = new ArrayList<>(1); resourceList.add(input); shell.write(displayLongListing(resourceList)); } else { List<Resource> resourceList = new ArrayList<>(1); resourceList.add(input); shell.write(Parser.formatDisplayListTerminalString( formatFileList(resourceList), shell.size().getHeight(), shell.size().getWidth())); } } private String displayLongListing(List<Resource> files) { StringGroup access = new StringGroup(files.size()); StringGroup size = new StringGroup(files.size()); StringGroup owner = new StringGroup(files.size()); StringGroup group = new StringGroup(files.size()); StringGroup modified = new StringGroup(files.size()); try { int counter = 0; for(Resource file : files) { BasicFileAttributes attr = file.readAttributes(fileAttributes, LinkOption.NOFOLLOW_LINKS); if (Config.isOSPOSIXCompatible()) {
// Path: aesh/src/main/java/org/aesh/extensions/tty/AeshPosixFilePermissions.java // public class AeshPosixFilePermissions { // private AeshPosixFilePermissions() { } // // // Write string representation of permission bits to {@code sb}. // private static void writeBits(StringBuilder sb, boolean r, boolean w, boolean x) { // if (r) { // sb.append('r'); // } else { // sb.append('-'); // } // if (w) { // sb.append('w'); // } else { // sb.append('-'); // } // if (x) { // sb.append('x'); // } else { // sb.append('-'); // } // } // // /** // * @return the string representation of the file // */ // public static String toString(PosixFileAttributes attr) { // Set<PosixFilePermission> perms = attr.permissions(); // StringBuilder sb = new StringBuilder(10); // if(attr.isDirectory()) // sb.append('d'); // else if(attr.isSymbolicLink()) // sb.append('l'); // else // sb.append('-'); // // writeBits(sb, perms.contains(OWNER_READ), perms.contains(OWNER_WRITE), // perms.contains(OWNER_EXECUTE)); // writeBits(sb, perms.contains(GROUP_READ), perms.contains(GROUP_WRITE), // perms.contains(GROUP_EXECUTE)); // writeBits(sb, perms.contains(OTHERS_READ), perms.contains(OTHERS_WRITE), // perms.contains(OTHERS_EXECUTE)); // return sb.toString(); // } // } // Path: aesh/src/main/java/org/aesh/extensions/ls/Ls.java import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.aesh.command.shell.Shell; import org.aesh.comparators.PosixFileNameComparator; import org.aesh.extensions.tty.AeshPosixFilePermissions; import org.aesh.io.Resource; import org.aesh.io.filter.NoDotNamesFilter; import org.aesh.readline.terminal.formatting.Color; import org.aesh.readline.terminal.formatting.TerminalColor; import org.aesh.readline.terminal.formatting.TerminalString; import org.aesh.readline.util.Parser; import org.aesh.terminal.utils.Config; import java.io.IOException; import java.math.RoundingMode; import java.nio.file.LinkOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.DosFileAttributes; import java.nio.file.attribute.PosixFileAttributes; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; } private void displayFile(Resource input, Shell shell) { if(longListing) { List<Resource> resourceList = new ArrayList<>(1); resourceList.add(input); shell.write(displayLongListing(resourceList)); } else { List<Resource> resourceList = new ArrayList<>(1); resourceList.add(input); shell.write(Parser.formatDisplayListTerminalString( formatFileList(resourceList), shell.size().getHeight(), shell.size().getWidth())); } } private String displayLongListing(List<Resource> files) { StringGroup access = new StringGroup(files.size()); StringGroup size = new StringGroup(files.size()); StringGroup owner = new StringGroup(files.size()); StringGroup group = new StringGroup(files.size()); StringGroup modified = new StringGroup(files.size()); try { int counter = 0; for(Resource file : files) { BasicFileAttributes attr = file.readAttributes(fileAttributes, LinkOption.NOFOLLOW_LINKS); if (Config.isOSPOSIXCompatible()) {
access.addString(AeshPosixFilePermissions.toString(((PosixFileAttributes) attr)), counter);
aeshell/aesh-extensions
aesh/src/main/java/org/aesh/extensions/highlight/Scanner.java
// Path: aesh/src/main/java/org/aesh/extensions/highlight/scanner/PlainScanner.java // public class PlainScanner implements Scanner { // private static final Pattern ALL = Pattern.compile(".*", Pattern.DOTALL); // // // Never match a File, only match by default if no one else does. Handled in Scanner.Factory // public static final Type TYPE = new Type("PLAIN", (Pattern)null); // // @Override // public Type getType() { // return TYPE; // } // // @Override // public void scan(StringScanner source, Encoder encoder, Map<String, Object> options) { // MatchResult m = source.scan(ALL); // if (m != null) { // encoder.textToken(m.group(), TokenType.plain); // } // } // // }
import org.aesh.extensions.highlight.scanner.PlainScanner; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern;
this.registry = new LinkedHashMap<String, Scanner>(); } private static Factory instance() { if (factory == null) { factory = new Factory(); } return factory; } public static void registrer(Class<? extends Scanner> scanner) { Scanner scannerInst = create(scanner); instance().registry.put(scannerInst.getType().getName(), scannerInst); } public static Scanner byType(String typeName) { for (Scanner scanner : instance().registry.values()) { if (scanner.getType().getName().equalsIgnoreCase(typeName)) { return scanner; } } return null; } public static Scanner byFileName(String fileName) { for (Scanner scanner : instance().registry.values()) { if (scanner.getType().supports(fileName)) { return scanner; } }
// Path: aesh/src/main/java/org/aesh/extensions/highlight/scanner/PlainScanner.java // public class PlainScanner implements Scanner { // private static final Pattern ALL = Pattern.compile(".*", Pattern.DOTALL); // // // Never match a File, only match by default if no one else does. Handled in Scanner.Factory // public static final Type TYPE = new Type("PLAIN", (Pattern)null); // // @Override // public Type getType() { // return TYPE; // } // // @Override // public void scan(StringScanner source, Encoder encoder, Map<String, Object> options) { // MatchResult m = source.scan(ALL); // if (m != null) { // encoder.textToken(m.group(), TokenType.plain); // } // } // // } // Path: aesh/src/main/java/org/aesh/extensions/highlight/Scanner.java import org.aesh.extensions.highlight.scanner.PlainScanner; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern; this.registry = new LinkedHashMap<String, Scanner>(); } private static Factory instance() { if (factory == null) { factory = new Factory(); } return factory; } public static void registrer(Class<? extends Scanner> scanner) { Scanner scannerInst = create(scanner); instance().registry.put(scannerInst.getType().getName(), scannerInst); } public static Scanner byType(String typeName) { for (Scanner scanner : instance().registry.values()) { if (scanner.getType().getName().equalsIgnoreCase(typeName)) { return scanner; } } return null; } public static Scanner byFileName(String fileName) { for (Scanner scanner : instance().registry.values()) { if (scanner.getType().supports(fileName)) { return scanner; } }
return instance().registry.get(PlainScanner.TYPE);
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/AhoCorasickMap.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.io.IOException; import java.nio.CharBuffer; import java.util.Arrays; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Standard Aho-Corasick map // It matches all occurences of the strings in the map anywhere. // It is highly optimized for this particular use. public class AhoCorasickMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; public AhoCorasickMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/AhoCorasickMap.java import java.io.IOException; import java.nio.CharBuffer; import java.util.Arrays; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Standard Aho-Corasick map // It matches all occurences of the strings in the map anywhere. // It is highly optimized for this particular use. public class AhoCorasickMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; public AhoCorasickMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) {
this(keywords, values, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/AhoCorasickMap.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.io.IOException; import java.nio.CharBuffer; import java.util.Arrays; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Standard Aho-Corasick map // It matches all occurences of the strings in the map anywhere. // It is highly optimized for this particular use. public class AhoCorasickMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; public AhoCorasickMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) { this(keywords, values, caseSensitive, new RangeNodeThreshold()); }
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/AhoCorasickMap.java import java.io.IOException; import java.nio.CharBuffer; import java.util.Arrays; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Standard Aho-Corasick map // It matches all occurences of the strings in the map anywhere. // It is highly optimized for this particular use. public class AhoCorasickMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; public AhoCorasickMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) { this(keywords, values, caseSensitive, new RangeNodeThreshold()); }
public AhoCorasickMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, final Thresholder thresholdStrategy) {
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/AhoCorasickSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Standard Aho-Corasick set // It matches all occurences of the strings in the set anywhere. // It is highly optimized for this particular use. public class AhoCorasickSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public AhoCorasickSet(final Iterable<String> keywords, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/AhoCorasickSet.java import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Standard Aho-Corasick set // It matches all occurences of the strings in the set anywhere. // It is highly optimized for this particular use. public class AhoCorasickSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public AhoCorasickSet(final Iterable<String> keywords, boolean caseSensitive) {
this(keywords, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/AhoCorasickSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Standard Aho-Corasick set // It matches all occurences of the strings in the set anywhere. // It is highly optimized for this particular use. public class AhoCorasickSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public AhoCorasickSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); }
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/AhoCorasickSet.java import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Standard Aho-Corasick set // It matches all occurences of the strings in the set anywhere. // It is highly optimized for this particular use. public class AhoCorasickSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public AhoCorasickSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); }
public AhoCorasickSet(final Iterable<String> keywords, boolean caseSensitive, final Thresholder thresholdStrategy) {
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/ShortestMatchSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Matches leftmost shortest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class ShortestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public ShortestMatchSet(final Iterable<String> keywords, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/ShortestMatchSet.java import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Matches leftmost shortest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class ShortestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public ShortestMatchSet(final Iterable<String> keywords, boolean caseSensitive) {
this(keywords, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/ShortestMatchSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Matches leftmost shortest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class ShortestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public ShortestMatchSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); }
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/ShortestMatchSet.java import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Matches leftmost shortest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class ShortestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public ShortestMatchSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); }
public ShortestMatchSet(final Iterable<String> keywords, boolean caseSensitive, final Thresholder thresholdStrategy) {
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/WholeWordLongestMatchMap.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters are allowed in the keywords. public class WholeWordLongestMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/WholeWordLongestMatchMap.java import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters are allowed in the keywords. public class WholeWordLongestMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) {
this(keywords, values, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/WholeWordLongestMatchMap.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters are allowed in the keywords. public class WholeWordLongestMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) { this(keywords, values, caseSensitive, new RangeNodeThreshold()); } // Set where the characters in the given array are considered word characters public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters) { this(keywords, values, caseSensitive, wordCharacters, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags) { this(keywords, values, caseSensitive, wordCharacters, toggleFlags, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters,
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/WholeWordLongestMatchMap.java import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters are allowed in the keywords. public class WholeWordLongestMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) { this(keywords, values, caseSensitive, new RangeNodeThreshold()); } // Set where the characters in the given array are considered word characters public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters) { this(keywords, values, caseSensitive, wordCharacters, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags) { this(keywords, values, caseSensitive, wordCharacters, toggleFlags, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordLongestMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters,
boolean[] toggleFlags, Thresholder thresholdStrategy) {
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/WholeWordMatchSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/WholeWordMatchSet.java import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive) {
this(keywords, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/WholeWordMatchSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); } // Set where the characters in the given array are considered word characters public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive, char[] wordCharacters) { this(keywords, caseSensitive, wordCharacters, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags) { this(keywords, caseSensitive, wordCharacters, toggleFlags, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/WholeWordMatchSet.java import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); } // Set where the characters in the given array are considered word characters public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive, char[] wordCharacters) { this(keywords, caseSensitive, wordCharacters, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags) { this(keywords, caseSensitive, wordCharacters, toggleFlags, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays
public WholeWordMatchSet(final Iterable<String> keywords, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags, Thresholder thresholdStrategy) {
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/LongestMatchSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Matches leftmost longest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class LongestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public LongestMatchSet(final Iterable<String> keywords, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/LongestMatchSet.java import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Matches leftmost longest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class LongestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public LongestMatchSet(final Iterable<String> keywords, boolean caseSensitive) {
this(keywords, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/LongestMatchSet.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // Matches leftmost longest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class LongestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public LongestMatchSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); }
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/LongestMatchSet.java import java.util.Arrays; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // Matches leftmost longest matches. Useful when you want non-overlapping // matches with a string set that doesn't have strings that are prefix to other strings in the set. public class LongestMatchSet implements StringSet { private boolean caseSensitive = true; private TrieNode root; public LongestMatchSet(final Iterable<String> keywords, boolean caseSensitive) { this(keywords, caseSensitive, new RangeNodeThreshold()); }
public LongestMatchSet(final Iterable<String> keywords, boolean caseSensitive, final Thresholder thresholdStrategy) {
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/WholeWordMatchMap.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) {
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/WholeWordMatchMap.java import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) {
this(keywords, values, caseSensitive, new RangeNodeThreshold());
RokLenarcic/AhoCorasick
src/main/java/com/roklenarcic/util/strings/WholeWordMatchMap.java
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // }
import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder;
package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) { this(keywords, values, caseSensitive, new RangeNodeThreshold()); } // Set where the characters in the given array are considered word characters public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters) { this(keywords, values, caseSensitive, wordCharacters, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags) { this(keywords, values, caseSensitive, wordCharacters, toggleFlags, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters,
// Path: src/main/java/com/roklenarcic/util/strings/threshold/RangeNodeThreshold.java // public class RangeNodeThreshold implements Thresholder { // // private double exponent, linearFactor, maxValue, constantFactor; // // public RangeNodeThreshold() { // this(1); // } // // public RangeNodeThreshold(double exponent) { // this(exponent, 1, 0.65, 2); // } // // public RangeNodeThreshold(double exponent, double linearFactor, double maxValue, double constantFactor) { // super(); // this.exponent = exponent; // this.linearFactor = linearFactor; // this.maxValue = maxValue; // this.constantFactor = constantFactor; // } // // public boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize) { // if (keyIntervalSize <= 8) { // return true; // } // int charArrayCost = (nodeSize / 4) + 3; // Char array costs 24 bytes + 2 bytes per char // return nodeSize + charArrayCost > keyIntervalSize * (maxValue - linearFactor / Math.pow(constantFactor + nodeLevel, exponent)); // } // // } // // Path: src/main/java/com/roklenarcic/util/strings/threshold/Thresholder.java // public interface Thresholder { // boolean isOverThreshold(int nodeSize, int nodeLevel, int keyIntervalSize); // } // Path: src/main/java/com/roklenarcic/util/strings/WholeWordMatchMap.java import java.io.IOException; import java.nio.CharBuffer; import java.util.Iterator; import com.roklenarcic.util.strings.threshold.RangeNodeThreshold; import com.roklenarcic.util.strings.threshold.Thresholder; package com.roklenarcic.util.strings; // A set that matches only whole word matches. Non-word characters are user defined (with a default). // Any non-word characters around input strings get trimmed. Non-word characters not allowed in the keywords // and they will produce an IllegalArgumentException. public class WholeWordMatchMap<T> implements StringMap<T> { private boolean caseSensitive = true; private int charBufferSize = 0; private TrieNode<T> root; private boolean[] wordChars; // Set where digits and letters, '-' and '_' are considered word characters. public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive) { this(keywords, values, caseSensitive, new RangeNodeThreshold()); } // Set where the characters in the given array are considered word characters public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters) { this(keywords, values, caseSensitive, wordCharacters, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters, boolean[] toggleFlags) { this(keywords, values, caseSensitive, wordCharacters, toggleFlags, new RangeNodeThreshold()); } // Set where digits and letters and '-' and '_' are considered word characters but modified by the two // given arrays public WholeWordMatchMap(final Iterable<String> keywords, final Iterable<? extends T> values, boolean caseSensitive, char[] wordCharacters,
boolean[] toggleFlags, Thresholder thresholdStrategy) {