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
chicm/CmRaft
cmraft-core/src/test/java/com/chicm/cmraft/core/TestClusterMemberManager.java
// Path: cmraft-core/src/main/java/com/chicm/cmraft/common/CmRaftConfiguration.java // public class CmRaftConfiguration implements Configuration { // static final Log LOG = LogFactory.getLog(CmRaftConfiguration.class); // private PropertiesConfiguration conf; // // public CmRaftConfiguration() throws ConfigurationException { // conf = new PropertiesConfiguration("cmraft.properties"); // // } // // public static Configuration create() { // try { // CmRaftConfiguration raftConfig = new CmRaftConfiguration(); // return raftConfig; // } catch(ConfigurationException e) { // return null; // } // } // // @Override // public void useResource(String resourceName) { // try { // conf = new PropertiesConfiguration(resourceName); // } catch(ConfigurationException e) { // LOG.error("load resource exception", e); // } // } // // @Override // public Object clone() { // Configuration obj = CmRaftConfiguration.create(); // obj.clear(); // for(String key: this.getKeys()) { // obj.set(key, this.getString(key)); // } // return (Object)obj; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // for(String key: this.getKeys()) { // sb.append(key + ":" + conf.getString(key)+"\n"); // } // return sb.toString(); // } // // @Override // public String getString(String key) { // return conf.getString(key); // } // // @Override // public String getString(String key, String defaultValue) { // return conf.getString(key, defaultValue); // } // // @Override // public int getInt(String key) { // return conf.getInt(key); // } // // @Override // public int getInt(String key, int defaultValue) { // return conf.getInt(key, defaultValue); // } // @Override // public Iterable<String> getKeys() { // return this.new ConfigurationIterableImpl(); // } // // @Override // public Iterable<String> getKeys(String prefix) { // return this.new ConfigurationIterableImplForPrefix(prefix); // } // // @Override // public void set(String key, String value) { // conf.setProperty(key, value); // } // // @Override // public void clear() { // conf.clear(); // } // // @Override // public void remove(String key) { // conf.clearProperty(key); // } // // private class ConfigurationIterableImpl implements Iterable<String> { // public Iterator<String> iterator() { // return conf.getKeys(); // } // } // // private class ConfigurationIterableImplForPrefix implements Iterable<String> { // private String prefix ; // ConfigurationIterableImplForPrefix(String prefix) { // this.prefix = prefix; // } // public Iterator<String> iterator() { // return conf.getKeys(prefix); // } // } // } // // Path: cmraft-core/src/main/java/com/chicm/cmraft/common/Configuration.java // public interface Configuration { // // void useResource(String resourceName); // // String getString(String key); // // String getString(String key, String defaultValue); // // int getInt(String key); // // int getInt(String key, int defaultValue); // // void set(String key, String value); // // void clear(); // // void remove(String key); // // Iterable<String> getKeys(); // // Iterable<String> getKeys(String prefix); // }
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import org.junit.Test; import com.chicm.cmraft.common.CmRaftConfiguration; import com.chicm.cmraft.common.Configuration;
package com.chicm.cmraft.core; public class TestClusterMemberManager { public Configuration createConf1() {
// Path: cmraft-core/src/main/java/com/chicm/cmraft/common/CmRaftConfiguration.java // public class CmRaftConfiguration implements Configuration { // static final Log LOG = LogFactory.getLog(CmRaftConfiguration.class); // private PropertiesConfiguration conf; // // public CmRaftConfiguration() throws ConfigurationException { // conf = new PropertiesConfiguration("cmraft.properties"); // // } // // public static Configuration create() { // try { // CmRaftConfiguration raftConfig = new CmRaftConfiguration(); // return raftConfig; // } catch(ConfigurationException e) { // return null; // } // } // // @Override // public void useResource(String resourceName) { // try { // conf = new PropertiesConfiguration(resourceName); // } catch(ConfigurationException e) { // LOG.error("load resource exception", e); // } // } // // @Override // public Object clone() { // Configuration obj = CmRaftConfiguration.create(); // obj.clear(); // for(String key: this.getKeys()) { // obj.set(key, this.getString(key)); // } // return (Object)obj; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // for(String key: this.getKeys()) { // sb.append(key + ":" + conf.getString(key)+"\n"); // } // return sb.toString(); // } // // @Override // public String getString(String key) { // return conf.getString(key); // } // // @Override // public String getString(String key, String defaultValue) { // return conf.getString(key, defaultValue); // } // // @Override // public int getInt(String key) { // return conf.getInt(key); // } // // @Override // public int getInt(String key, int defaultValue) { // return conf.getInt(key, defaultValue); // } // @Override // public Iterable<String> getKeys() { // return this.new ConfigurationIterableImpl(); // } // // @Override // public Iterable<String> getKeys(String prefix) { // return this.new ConfigurationIterableImplForPrefix(prefix); // } // // @Override // public void set(String key, String value) { // conf.setProperty(key, value); // } // // @Override // public void clear() { // conf.clear(); // } // // @Override // public void remove(String key) { // conf.clearProperty(key); // } // // private class ConfigurationIterableImpl implements Iterable<String> { // public Iterator<String> iterator() { // return conf.getKeys(); // } // } // // private class ConfigurationIterableImplForPrefix implements Iterable<String> { // private String prefix ; // ConfigurationIterableImplForPrefix(String prefix) { // this.prefix = prefix; // } // public Iterator<String> iterator() { // return conf.getKeys(prefix); // } // } // } // // Path: cmraft-core/src/main/java/com/chicm/cmraft/common/Configuration.java // public interface Configuration { // // void useResource(String resourceName); // // String getString(String key); // // String getString(String key, String defaultValue); // // int getInt(String key); // // int getInt(String key, int defaultValue); // // void set(String key, String value); // // void clear(); // // void remove(String key); // // Iterable<String> getKeys(); // // Iterable<String> getKeys(String prefix); // } // Path: cmraft-core/src/test/java/com/chicm/cmraft/core/TestClusterMemberManager.java import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import org.junit.Test; import com.chicm.cmraft.common.CmRaftConfiguration; import com.chicm.cmraft.common.Configuration; package com.chicm.cmraft.core; public class TestClusterMemberManager { public Configuration createConf1() {
Configuration conf1 = CmRaftConfiguration.create();
chicm/CmRaft
cmraft-core/src/test/java/com/chicm/cmraft/TestKeyValueStore.java
// Path: cmraft-core/src/test/java/com/chicm/cmraft/core/LocalCluster.java // public class LocalCluster { // // private static LocalCluster instance = null; // // private static final int NODE_NUMBER = 3; // private static final int START_PORT = 12888; // // private int nodeNumber = NODE_NUMBER; // private int nodeStartNumber; // private int startPort = START_PORT; // // private Configuration[] confs; // private RaftNode[] nodes; // // private Connection connection; // // private LocalCluster() { // } // // public static synchronized LocalCluster create(int n, int nStart, int startPort) { // if(instance == null) { // instance = new LocalCluster(); // instance.createCluster(n, nStart, startPort); // } // return instance; // } // // public Connection getConnection() { // if(connection == null) { // connection = ConnectionManager.getConnection(getConf(0)); // } // return connection; // } // // public Configuration getConf(int index) { // return confs[index]; // } // // public RaftNode[] getNodes() { // return nodes; // } // // private void createCluster(int n, int nStart, int startPort) { // this.nodeNumber = n; // this.nodeStartNumber = nStart; // this.startPort = startPort; // // createConfiguration(); // // nodes = new RaftNode[nodeStartNumber]; // for(int i = 0; i < nodeStartNumber; i++) { // nodes[i] = new RaftNode(confs[i]); // } // } // // public void checkNodesState() { // int nLeader = 0; // int nFollower = 0; // // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // if(nodes[i].getState() == State.LEADER) { // nLeader++; // } else if(nodes[i].getState() == State.FOLLOWER) { // nFollower++; // } // } // assertTrue(nLeader == 1); // assertTrue(nFollower == (nodeStartNumber -1)); // } // // public void printNodesState() { // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // } // } // // public void checkGetCurrentLeader() { // // for (int i =0; i < nodeStartNumber; i++) { // if(i != 0) { // assertTrue(nodes[i].getCurrentLeader().equals(nodes[i-1].getCurrentLeader())); // } // } // } // // public void killLeader() { // for(RaftNode node: nodes) { // //System.out.println(node.getName() + ":" + node.getState() + ":" + node.getCurrentTerm()); // if(node.isLeader()) { // System.out.println(node.getServerInfo() + " is leader, killing it"); // node.kill(); // } // } // } // // private void createConfiguration() { // confs = new Configuration[nodeNumber]; // for(int i = 0; i < nodeNumber; i++) { // confs[i] = CmRaftConfiguration.create(); // confs[i].useResource("cmraft_cluster_test.properties"); // for(int j=0; j < nodeNumber;j++) { // confs[i].set("raft.server.server" + j, "localhost:" + (startPort+j)); // } // confs[i].remove("raft.server.server" + i); // confs[i].set("raft.local.server", "localhost:" + (startPort+i)); // // System.out.println("confs[" + i + "]:\n" + confs[i].toString()); // } // } // // }
import static org.junit.Assert.*; import org.apache.log4j.Level; import org.junit.Test; import com.chicm.cmraft.core.LocalCluster; import com.google.common.base.Preconditions;
/** * Copyright 2014 The CmRaft Project * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.chicm.cmraft; public class TestKeyValueStore { private static final int TESTS_NUMBER = 500; public static void main(String[] args) throws Exception { TestKeyValueStore t = new TestKeyValueStore(); t.testKeyValueStore(); }
// Path: cmraft-core/src/test/java/com/chicm/cmraft/core/LocalCluster.java // public class LocalCluster { // // private static LocalCluster instance = null; // // private static final int NODE_NUMBER = 3; // private static final int START_PORT = 12888; // // private int nodeNumber = NODE_NUMBER; // private int nodeStartNumber; // private int startPort = START_PORT; // // private Configuration[] confs; // private RaftNode[] nodes; // // private Connection connection; // // private LocalCluster() { // } // // public static synchronized LocalCluster create(int n, int nStart, int startPort) { // if(instance == null) { // instance = new LocalCluster(); // instance.createCluster(n, nStart, startPort); // } // return instance; // } // // public Connection getConnection() { // if(connection == null) { // connection = ConnectionManager.getConnection(getConf(0)); // } // return connection; // } // // public Configuration getConf(int index) { // return confs[index]; // } // // public RaftNode[] getNodes() { // return nodes; // } // // private void createCluster(int n, int nStart, int startPort) { // this.nodeNumber = n; // this.nodeStartNumber = nStart; // this.startPort = startPort; // // createConfiguration(); // // nodes = new RaftNode[nodeStartNumber]; // for(int i = 0; i < nodeStartNumber; i++) { // nodes[i] = new RaftNode(confs[i]); // } // } // // public void checkNodesState() { // int nLeader = 0; // int nFollower = 0; // // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // if(nodes[i].getState() == State.LEADER) { // nLeader++; // } else if(nodes[i].getState() == State.FOLLOWER) { // nFollower++; // } // } // assertTrue(nLeader == 1); // assertTrue(nFollower == (nodeStartNumber -1)); // } // // public void printNodesState() { // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // } // } // // public void checkGetCurrentLeader() { // // for (int i =0; i < nodeStartNumber; i++) { // if(i != 0) { // assertTrue(nodes[i].getCurrentLeader().equals(nodes[i-1].getCurrentLeader())); // } // } // } // // public void killLeader() { // for(RaftNode node: nodes) { // //System.out.println(node.getName() + ":" + node.getState() + ":" + node.getCurrentTerm()); // if(node.isLeader()) { // System.out.println(node.getServerInfo() + " is leader, killing it"); // node.kill(); // } // } // } // // private void createConfiguration() { // confs = new Configuration[nodeNumber]; // for(int i = 0; i < nodeNumber; i++) { // confs[i] = CmRaftConfiguration.create(); // confs[i].useResource("cmraft_cluster_test.properties"); // for(int j=0; j < nodeNumber;j++) { // confs[i].set("raft.server.server" + j, "localhost:" + (startPort+j)); // } // confs[i].remove("raft.server.server" + i); // confs[i].set("raft.local.server", "localhost:" + (startPort+i)); // // System.out.println("confs[" + i + "]:\n" + confs[i].toString()); // } // } // // } // Path: cmraft-core/src/test/java/com/chicm/cmraft/TestKeyValueStore.java import static org.junit.Assert.*; import org.apache.log4j.Level; import org.junit.Test; import com.chicm.cmraft.core.LocalCluster; import com.google.common.base.Preconditions; /** * Copyright 2014 The CmRaft Project * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.chicm.cmraft; public class TestKeyValueStore { private static final int TESTS_NUMBER = 500; public static void main(String[] args) throws Exception { TestKeyValueStore t = new TestKeyValueStore(); t.testKeyValueStore(); }
public Connection getConnection(LocalCluster cluster, int timeout) throws Exception {
chicm/CmRaft
cmraft-core/src/test/java/com/chicm/cmraft/TestPerformance.java
// Path: cmraft-core/src/test/java/com/chicm/cmraft/core/LocalCluster.java // public class LocalCluster { // // private static LocalCluster instance = null; // // private static final int NODE_NUMBER = 3; // private static final int START_PORT = 12888; // // private int nodeNumber = NODE_NUMBER; // private int nodeStartNumber; // private int startPort = START_PORT; // // private Configuration[] confs; // private RaftNode[] nodes; // // private Connection connection; // // private LocalCluster() { // } // // public static synchronized LocalCluster create(int n, int nStart, int startPort) { // if(instance == null) { // instance = new LocalCluster(); // instance.createCluster(n, nStart, startPort); // } // return instance; // } // // public Connection getConnection() { // if(connection == null) { // connection = ConnectionManager.getConnection(getConf(0)); // } // return connection; // } // // public Configuration getConf(int index) { // return confs[index]; // } // // public RaftNode[] getNodes() { // return nodes; // } // // private void createCluster(int n, int nStart, int startPort) { // this.nodeNumber = n; // this.nodeStartNumber = nStart; // this.startPort = startPort; // // createConfiguration(); // // nodes = new RaftNode[nodeStartNumber]; // for(int i = 0; i < nodeStartNumber; i++) { // nodes[i] = new RaftNode(confs[i]); // } // } // // public void checkNodesState() { // int nLeader = 0; // int nFollower = 0; // // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // if(nodes[i].getState() == State.LEADER) { // nLeader++; // } else if(nodes[i].getState() == State.FOLLOWER) { // nFollower++; // } // } // assertTrue(nLeader == 1); // assertTrue(nFollower == (nodeStartNumber -1)); // } // // public void printNodesState() { // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // } // } // // public void checkGetCurrentLeader() { // // for (int i =0; i < nodeStartNumber; i++) { // if(i != 0) { // assertTrue(nodes[i].getCurrentLeader().equals(nodes[i-1].getCurrentLeader())); // } // } // } // // public void killLeader() { // for(RaftNode node: nodes) { // //System.out.println(node.getName() + ":" + node.getState() + ":" + node.getCurrentTerm()); // if(node.isLeader()) { // System.out.println(node.getServerInfo() + " is leader, killing it"); // node.kill(); // } // } // } // // private void createConfiguration() { // confs = new Configuration[nodeNumber]; // for(int i = 0; i < nodeNumber; i++) { // confs[i] = CmRaftConfiguration.create(); // confs[i].useResource("cmraft_cluster_test.properties"); // for(int j=0; j < nodeNumber;j++) { // confs[i].set("raft.server.server" + j, "localhost:" + (startPort+j)); // } // confs[i].remove("raft.server.server" + i); // confs[i].set("raft.local.server", "localhost:" + (startPort+i)); // // System.out.println("confs[" + i + "]:\n" + confs[i].toString()); // } // } // // }
import com.chicm.cmraft.core.LocalCluster; import org.apache.log4j.Level; import org.junit.Test;
/** * Copyright 2014 The CmRaft Project * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.chicm.cmraft; public class TestPerformance { private static final int TEST_NUMBERS = 2000; public static void main(String[] args) throws Exception { TestPerformance t = new TestPerformance(); t.testAllNodes(); } @Test public void testAllNodes() throws Exception { long tm = doTests(5, 5); System.out.println("all nodes total time:" + tm); } @Test public void testPartialNodes() throws Exception { long tm = doTests(5, 3); System.out.println("partial nodes total time:" + tm); } public long doTests(int nNodes, int startNodes) throws Exception { org.apache.log4j.LogManager.getRootLogger().setLevel(Level.DEBUG);
// Path: cmraft-core/src/test/java/com/chicm/cmraft/core/LocalCluster.java // public class LocalCluster { // // private static LocalCluster instance = null; // // private static final int NODE_NUMBER = 3; // private static final int START_PORT = 12888; // // private int nodeNumber = NODE_NUMBER; // private int nodeStartNumber; // private int startPort = START_PORT; // // private Configuration[] confs; // private RaftNode[] nodes; // // private Connection connection; // // private LocalCluster() { // } // // public static synchronized LocalCluster create(int n, int nStart, int startPort) { // if(instance == null) { // instance = new LocalCluster(); // instance.createCluster(n, nStart, startPort); // } // return instance; // } // // public Connection getConnection() { // if(connection == null) { // connection = ConnectionManager.getConnection(getConf(0)); // } // return connection; // } // // public Configuration getConf(int index) { // return confs[index]; // } // // public RaftNode[] getNodes() { // return nodes; // } // // private void createCluster(int n, int nStart, int startPort) { // this.nodeNumber = n; // this.nodeStartNumber = nStart; // this.startPort = startPort; // // createConfiguration(); // // nodes = new RaftNode[nodeStartNumber]; // for(int i = 0; i < nodeStartNumber; i++) { // nodes[i] = new RaftNode(confs[i]); // } // } // // public void checkNodesState() { // int nLeader = 0; // int nFollower = 0; // // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // if(nodes[i].getState() == State.LEADER) { // nLeader++; // } else if(nodes[i].getState() == State.FOLLOWER) { // nFollower++; // } // } // assertTrue(nLeader == 1); // assertTrue(nFollower == (nodeStartNumber -1)); // } // // public void printNodesState() { // System.out.println("******************"); // for (int i =0; i < nodeStartNumber; i++) { // System.out.println(nodes[i].getName() + ":" + nodes[i].getState() // + "(" + nodes[i].getCurrentTerm() + ")"); // } // } // // public void checkGetCurrentLeader() { // // for (int i =0; i < nodeStartNumber; i++) { // if(i != 0) { // assertTrue(nodes[i].getCurrentLeader().equals(nodes[i-1].getCurrentLeader())); // } // } // } // // public void killLeader() { // for(RaftNode node: nodes) { // //System.out.println(node.getName() + ":" + node.getState() + ":" + node.getCurrentTerm()); // if(node.isLeader()) { // System.out.println(node.getServerInfo() + " is leader, killing it"); // node.kill(); // } // } // } // // private void createConfiguration() { // confs = new Configuration[nodeNumber]; // for(int i = 0; i < nodeNumber; i++) { // confs[i] = CmRaftConfiguration.create(); // confs[i].useResource("cmraft_cluster_test.properties"); // for(int j=0; j < nodeNumber;j++) { // confs[i].set("raft.server.server" + j, "localhost:" + (startPort+j)); // } // confs[i].remove("raft.server.server" + i); // confs[i].set("raft.local.server", "localhost:" + (startPort+i)); // // System.out.println("confs[" + i + "]:\n" + confs[i].toString()); // } // } // // } // Path: cmraft-core/src/test/java/com/chicm/cmraft/TestPerformance.java import com.chicm.cmraft.core.LocalCluster; import org.apache.log4j.Level; import org.junit.Test; /** * Copyright 2014 The CmRaft Project * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.chicm.cmraft; public class TestPerformance { private static final int TEST_NUMBERS = 2000; public static void main(String[] args) throws Exception { TestPerformance t = new TestPerformance(); t.testAllNodes(); } @Test public void testAllNodes() throws Exception { long tm = doTests(5, 5); System.out.println("all nodes total time:" + tm); } @Test public void testPartialNodes() throws Exception { long tm = doTests(5, 3); System.out.println("partial nodes total time:" + tm); } public long doTests(int nNodes, int startNodes) throws Exception { org.apache.log4j.LogManager.getRootLogger().setLevel(Level.DEBUG);
LocalCluster cluster = LocalCluster.create(nNodes, startNodes, 14688);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/accessor/Accessor.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue;
package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // } // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue; package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) {
Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/accessor/Accessor.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue;
package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // } // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue; package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) {
Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/accessor/Accessor.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue;
package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) { Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); fieldMap = fieldMapPair.getFirst(); leastCapacity = fieldMapPair.getSecond(); } public Map<String, Integer> getFieldMap() { return fieldMap; } public Integer getLeastCapacity() { return leastCapacity; }
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // } // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue; package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) { Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); fieldMap = fieldMapPair.getFirst(); leastCapacity = fieldMapPair.getSecond(); } public Map<String, Integer> getFieldMap() { return fieldMap; } public Integer getLeastCapacity() { return leastCapacity; }
public RecordWrapper<T> create(Accessible<T> record) {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/accessor/Accessor.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue;
package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) { Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); fieldMap = fieldMapPair.getFirst(); leastCapacity = fieldMapPair.getSecond(); } public Map<String, Integer> getFieldMap() { return fieldMap; } public Integer getLeastCapacity() { return leastCapacity; } public RecordWrapper<T> create(Accessible<T> record) {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public class Lexer { // public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); // // // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // // private static boolean buildFieldMaps(Map<String, Integer> accessorMap, // Iterable<FieldType> accessors, // int index, int factor) { // boolean reversed = false; // for (FieldType accessor : accessors) { // if (accessor instanceof FieldNameToken) { // accessorMap.put(((FieldNameToken) accessor).getName(), index); // index += factor; // } else if (accessor instanceof PaddingToken) { // index += factor * ((PaddingToken) accessor).getSize(); // } else if (accessor instanceof PlaceholderToken) { // reversed = true; // break; // } // } // return reversed; // } // // public static Pair<List<FieldType>, Integer> lex(String[] fields) { // // int segmentSize = 1; // int currentSegmentSize = 0; // ArrayList<FieldType> accessors = new ArrayList<>(); // for (String field : fields) { // if (field.trim().startsWith("{")) { // Matcher matcher = PADDING_PATTERN.matcher(field); // if (matcher.matches()) { // int amount = Integer.parseInt(matcher.group(1)); // currentSegmentSize += amount; // accessors.add(new PaddingToken(amount)); // } else { // throw new UnsupportedOperationException("Unknown format for padding: " + field); // } // } else if ("...".equals(field.trim())) { // accessors.add(new PlaceholderToken(field.trim())); // segmentSize = Math.max(currentSegmentSize, segmentSize); // currentSegmentSize = 0; // } else { // accessors.add(new FieldNameToken(field.trim())); // currentSegmentSize++; // } // } // // return new Pair<>(accessors, Math.max(currentSegmentSize, segmentSize)); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Accessible.java // public interface Accessible<T> { // T get(int index); // // int size(); // // } // // Path: src/main/java/net/kimleo/rec/common/exception/Assert.java // public static void assertTrue(boolean test) { // if (!test) { // throw new AssertionError("Expected to be true, but got false."); // } // } // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.v2.accessor.lexer.Lexer; import net.kimleo.rec.common.concept.Accessible; import java.util.Map; import static net.kimleo.rec.common.exception.Assert.assertTrue; package net.kimleo.rec.v2.accessor; public class Accessor<T> { private final Map<String, Integer> fieldMap; private final Integer leastCapacity; public Accessor(String[] fields) { Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); fieldMap = fieldMapPair.getFirst(); leastCapacity = fieldMapPair.getSecond(); } public Map<String, Integer> getFieldMap() { return fieldMap; } public Integer getLeastCapacity() { return leastCapacity; } public RecordWrapper<T> create(Accessible<T> record) {
assertTrue (record.size() >= leastCapacity);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/utils/PersistenceTest.java
// Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java // public final class NativeExecutionContext implements ExecutionContext, Serializable { // public static final long serialVersionUID = 1453356753764L; // private int count = 0; // private final int baseCount; // // private static final Logger LOGGER = LoggerFactory.getLogger(NativeExecutionContext.class); // private String scriptPath; // private transient Context jsContext; // private transient boolean enableRetry; // private String retryFile = null; // // public NativeExecutionContext(int baseCount) { // this.baseCount = baseCount; // LOGGER.info(format("Initialize execution context based on count %d", baseCount)); // } // // public int state() { // return baseCount; // } // // @Override // public void commit() { // count ++; // } // // public void persist(Throwable causedBy) { // try { // String filename = String.valueOf(new Date().getTime()).concat(".retry"); // Persistence.saveObjectToFile(this, filename); // LOGGER.info(format("Successfully save context to [%s]", filename)); // } catch (IOException e) { // LOGGER.error(format("Unable to save execution context and the count is %d", count)); // throw new ResourceAccessException("Cannot persist execution context", e); // } // throw new ResourceAccessException(format("Need retry on count %d", baseCount + count), causedBy); // } // // public String scriptPath() { // return scriptPath; // } // // public boolean enableRetry() { // return enableRetry; // } // // public String retryFile() { // return retryFile; // } // // public int count() { // return count; // } // // public static NativeExecutionContext initialContext() { // return new NativeExecutionContext(0); // } // // @Override // public String toString() { // return "NativeExecutionContext{" + // "count=" + count + // ", baseCount=" + baseCount + // '}'; // } // // @Override // public ExecutionContext restart() { // NativeExecutionContext context = new NativeExecutionContext(count + baseCount); // context.setJsContext(jsContext); // context.setScriptPath(scriptPath); // context.setEnableRetry(enableRetry); // return context; // } // // @Override // public boolean isNative() { // return true; // } // // @Override // public boolean isCloud() { // return !isNative(); // } // // @Override // public Context jsContext() { // return jsContext; // } // // public void setScriptPath(String scriptPath) { // this.scriptPath = scriptPath; // } // // public void setJsContext(Context jsContext) { // this.jsContext = jsContext; // } // // public void setEnableRetry(boolean enableRetry) { // this.enableRetry = enableRetry; // } // // public void setRetryFile(String retryFile) { // this.retryFile = retryFile; // } // }
import net.kimleo.rec.v2.execution.impl.NativeExecutionContext; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Paths; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package net.kimleo.rec.v2.utils; public class PersistenceTest { @Test public void shouldPersistObject() throws Exception { Files.deleteIfExists(Paths.get("file.out"));
// Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java // public final class NativeExecutionContext implements ExecutionContext, Serializable { // public static final long serialVersionUID = 1453356753764L; // private int count = 0; // private final int baseCount; // // private static final Logger LOGGER = LoggerFactory.getLogger(NativeExecutionContext.class); // private String scriptPath; // private transient Context jsContext; // private transient boolean enableRetry; // private String retryFile = null; // // public NativeExecutionContext(int baseCount) { // this.baseCount = baseCount; // LOGGER.info(format("Initialize execution context based on count %d", baseCount)); // } // // public int state() { // return baseCount; // } // // @Override // public void commit() { // count ++; // } // // public void persist(Throwable causedBy) { // try { // String filename = String.valueOf(new Date().getTime()).concat(".retry"); // Persistence.saveObjectToFile(this, filename); // LOGGER.info(format("Successfully save context to [%s]", filename)); // } catch (IOException e) { // LOGGER.error(format("Unable to save execution context and the count is %d", count)); // throw new ResourceAccessException("Cannot persist execution context", e); // } // throw new ResourceAccessException(format("Need retry on count %d", baseCount + count), causedBy); // } // // public String scriptPath() { // return scriptPath; // } // // public boolean enableRetry() { // return enableRetry; // } // // public String retryFile() { // return retryFile; // } // // public int count() { // return count; // } // // public static NativeExecutionContext initialContext() { // return new NativeExecutionContext(0); // } // // @Override // public String toString() { // return "NativeExecutionContext{" + // "count=" + count + // ", baseCount=" + baseCount + // '}'; // } // // @Override // public ExecutionContext restart() { // NativeExecutionContext context = new NativeExecutionContext(count + baseCount); // context.setJsContext(jsContext); // context.setScriptPath(scriptPath); // context.setEnableRetry(enableRetry); // return context; // } // // @Override // public boolean isNative() { // return true; // } // // @Override // public boolean isCloud() { // return !isNative(); // } // // @Override // public Context jsContext() { // return jsContext; // } // // public void setScriptPath(String scriptPath) { // this.scriptPath = scriptPath; // } // // public void setJsContext(Context jsContext) { // this.jsContext = jsContext; // } // // public void setEnableRetry(boolean enableRetry) { // this.enableRetry = enableRetry; // } // // public void setRetryFile(String retryFile) { // this.retryFile = retryFile; // } // } // Path: src/test/java/net/kimleo/rec/v2/utils/PersistenceTest.java import net.kimleo.rec.v2.execution.impl.NativeExecutionContext; import org.junit.Test; import java.nio.file.Files; import java.nio.file.Paths; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package net.kimleo.rec.v2.utils; public class PersistenceTest { @Test public void shouldPersistObject() throws Exception { Files.deleteIfExists(Paths.get("file.out"));
NativeExecutionContext context = new NativeExecutionContext(15);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/ReactiveTeeTest.java
// Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // }
import net.kimleo.rec.v2.scripting.Scripting; import org.junit.Test; import java.io.File;
package net.kimleo.rec.v2.model.impl; public class ReactiveTeeTest { @Test public void test() throws Exception {
// Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/ReactiveTeeTest.java import net.kimleo.rec.v2.scripting.Scripting; import org.junit.Test; import java.io.File; package net.kimleo.rec.v2.model.impl; public class ReactiveTeeTest { @Test public void test() throws Exception {
Scripting.runfile(new File("src/test/resources/reactive.js"), "reactive.js", false, "");
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/CSVFileSource.java
// Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // }
import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.stream.Stream;
package net.kimleo.rec.v2.model.impl; public class CSVFileSource implements Source<Mapped<String>> { private final Stream<String> lines;
// Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/CSVFileSource.java import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.stream.Stream; package net.kimleo.rec.v2.model.impl; public class CSVFileSource implements Source<Mapped<String>> { private final Stream<String> lines;
private final Accessor<String> accessor;
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/CSVFileSource.java
// Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // }
import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.stream.Stream;
package net.kimleo.rec.v2.model.impl; public class CSVFileSource implements Source<Mapped<String>> { private final Stream<String> lines; private final Accessor<String> accessor;
// Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/CSVFileSource.java import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.stream.Stream; package net.kimleo.rec.v2.model.impl; public class CSVFileSource implements Source<Mapped<String>> { private final Stream<String> lines; private final Accessor<String> accessor;
private final SimpleParser csvParser;
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/execution/RestartableSource.java
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Target;
package net.kimleo.rec.v2.execution; public interface RestartableSource<T> extends Source<T> { ExecutionContext context(); @Override
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/main/java/net/kimleo/rec/v2/execution/RestartableSource.java import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Target; package net.kimleo.rec.v2.execution; public interface RestartableSource<T> extends Source<T> { ExecutionContext context(); @Override
default void to(Target<T> target) {
rec-framework/rec-core
src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // }
import net.kimleo.rec.sepval.SepValEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList;
package net.kimleo.rec.sepval.parser; public class SimpleParser { private final ParseConfig config; private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); public SimpleParser(ParseConfig config) { this.config = config; } public SimpleParser() { this(ParseConfig.DEFAULT); }
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java import net.kimleo.rec.sepval.SepValEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; package net.kimleo.rec.sepval.parser; public class SimpleParser { private final ParseConfig config; private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); public SimpleParser(ParseConfig config) { this.config = config; } public SimpleParser() { this(ParseConfig.DEFAULT); }
public SepValEntry parse(String input) {
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/CSVSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.model.impl; public class CSVSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()),
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/CSVSourceTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.model.impl; public class CSVSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()),
"id, name, dob, illegal", ParseConfig.DEFAULT);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/CSVSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.model.impl; public class CSVSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()), "id, name, dob, illegal", ParseConfig.DEFAULT);
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/CSVSourceTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.model.impl; public class CSVSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()), "id, name, dob, illegal", ParseConfig.DEFAULT);
CollectTee<Mapped<String>> collector = new CollectTee<>(new ArrayList<>());
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/CSVSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.model.impl; public class CSVSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()), "id, name, dob, illegal", ParseConfig.DEFAULT); CollectTee<Mapped<String>> collector = new CollectTee<>(new ArrayList<>()); HashSet<String> strings = new HashSet<>(); ItemCounterTee<Mapped<String>> counter = new ItemCounterTee<>(it -> true);
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/CSVSourceTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.model.impl; public class CSVSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()), "id, name, dob, illegal", ParseConfig.DEFAULT); CollectTee<Mapped<String>> collector = new CollectTee<>(new ArrayList<>()); HashSet<String> strings = new HashSet<>(); ItemCounterTee<Mapped<String>> counter = new ItemCounterTee<>(it -> true);
Target<Mapped<String>> target = record ->
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSourceTest.java
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // }
import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Persistence; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.stream.Stream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSourceTest { @Test public void shouldJustRunAsExpected() throws Exception { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // } // Path: src/test/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSourceTest.java import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Persistence; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.stream.Stream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSourceTest { @Test public void shouldJustRunAsExpected() throws Exception { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
Source<Integer> restartable = CountBasedRestartableSource.from(stream);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSourceTest.java
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // }
import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Persistence; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.stream.Stream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSourceTest { @Test public void shouldJustRunAsExpected() throws Exception { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Source<Integer> restartable = CountBasedRestartableSource.from(stream); restartable.stream().findFirst().get().equals(1); } @Test public void shouldReturnLastRun() throws Exception { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Source<Integer> restartable = CountBasedRestartableSource.from(stream, new NativeExecutionContext(2)); restartable.stream().findFirst().get().equals(3); } @Test public void restartabilityTest() throws Exception {
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // } // Path: src/test/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSourceTest.java import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Persistence; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.stream.Stream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSourceTest { @Test public void shouldJustRunAsExpected() throws Exception { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Source<Integer> restartable = CountBasedRestartableSource.from(stream); restartable.stream().findFirst().get().equals(1); } @Test public void shouldReturnLastRun() throws Exception { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Source<Integer> restartable = CountBasedRestartableSource.from(stream, new NativeExecutionContext(2)); restartable.stream().findFirst().get().equals(3); } @Test public void restartabilityTest() throws Exception {
Scripting.runfile(new File("src/test/resources/restartability.js"),
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSourceTest.java
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // }
import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Persistence; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.stream.Stream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
@Test public void restartabilityTest() throws Exception { Scripting.runfile(new File("src/test/resources/restartability.js"), "restartability.js", true, "src/test/resources/restartability.retry"); } @Test public void shouldGenerateRetryFile() throws Exception { Files.list(Paths.get(".")).filter(path -> path.toString().endsWith(".retry")).forEach(deleteFile()); try { Scripting.runfile(new File("src/test/resources/restartability.js"), "restartability.js", false, ""); fail(); } catch (Exception ex) { assertTrue(ex instanceof RuntimeException); } assertTrue(Files.find(Paths.get("."), 1, (file, attr) -> file.toString().endsWith(".retry")) .count() == 1); } @Test public void persisit() throws Exception { NativeExecutionContext context = NativeExecutionContext.initialContext(); context.commit(); context.commit(); context.commit(); context.commit();
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // } // Path: src/test/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSourceTest.java import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Persistence; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.stream.Stream; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @Test public void restartabilityTest() throws Exception { Scripting.runfile(new File("src/test/resources/restartability.js"), "restartability.js", true, "src/test/resources/restartability.retry"); } @Test public void shouldGenerateRetryFile() throws Exception { Files.list(Paths.get(".")).filter(path -> path.toString().endsWith(".retry")).forEach(deleteFile()); try { Scripting.runfile(new File("src/test/resources/restartability.js"), "restartability.js", false, ""); fail(); } catch (Exception ex) { assertTrue(ex instanceof RuntimeException); } assertTrue(Files.find(Paths.get("."), 1, (file, attr) -> file.toString().endsWith(".retry")) .count() == 1); } @Test public void persisit() throws Exception { NativeExecutionContext context = NativeExecutionContext.initialContext(); context.commit(); context.commit(); context.commit(); context.commit();
Persistence.saveObjectToFile(context, "default.retry");
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/stream/MergeIteratorTest.java
// Path: src/main/java/net/kimleo/rec/v2/utils/Streams.java // public class Streams { // public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, // Stream<T> second) { // MergeIterator<T> iterator = new MergeIterator<>( // first.iterator(), second.iterator(), Comparable::compareTo); // IteratingSpliteratorAdapter<T> adapter = new IteratingSpliteratorAdapter<>(iterator); // return StreamSupport.stream(adapter, false); // } // // public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, // Stream<T> second, // Comparator<T> comparator) { // MergeIterator<T> iterator = new MergeIterator<>( // first.iterator(), second.iterator(), comparator); // IteratingSpliteratorAdapter<T> adapter = new IteratingSpliteratorAdapter<>(iterator); // return StreamSupport.stream(adapter, false); // } // // }
import net.kimleo.rec.v2.utils.Streams; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.stream; public class MergeIteratorTest { private final List<Integer> first = Arrays.asList(1, 2, 3, 4, 5); private final List<Integer> second = Arrays.asList(2, 4, 6, 8, 10); @Test public void shouldMerge() throws Exception { MergeIterator<Integer> merged = new MergeIterator<>( first.iterator(), second.iterator(), Integer::compareTo); ArrayList<Integer> ints = new ArrayList<>(); while (merged.hasNext()) { ints.add(merged.next()); } assertThat(ints.get(0), is(1)); assertThat(ints.get(9), is(10)); assertThat(ints.get(5), is(4)); } @Test public void shouldMergeStream() throws Exception {
// Path: src/main/java/net/kimleo/rec/v2/utils/Streams.java // public class Streams { // public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, // Stream<T> second) { // MergeIterator<T> iterator = new MergeIterator<>( // first.iterator(), second.iterator(), Comparable::compareTo); // IteratingSpliteratorAdapter<T> adapter = new IteratingSpliteratorAdapter<>(iterator); // return StreamSupport.stream(adapter, false); // } // // public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, // Stream<T> second, // Comparator<T> comparator) { // MergeIterator<T> iterator = new MergeIterator<>( // first.iterator(), second.iterator(), comparator); // IteratingSpliteratorAdapter<T> adapter = new IteratingSpliteratorAdapter<>(iterator); // return StreamSupport.stream(adapter, false); // } // // } // Path: src/test/java/net/kimleo/rec/v2/stream/MergeIteratorTest.java import net.kimleo.rec.v2.utils.Streams; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.stream; public class MergeIteratorTest { private final List<Integer> first = Arrays.asList(1, 2, 3, 4, 5); private final List<Integer> second = Arrays.asList(2, 4, 6, 8, 10); @Test public void shouldMerge() throws Exception { MergeIterator<Integer> merged = new MergeIterator<>( first.iterator(), second.iterator(), Integer::compareTo); ArrayList<Integer> ints = new ArrayList<>(); while (merged.hasNext()) { ints.add(merged.next()); } assertThat(ints.get(0), is(1)); assertThat(ints.get(9), is(10)); assertThat(ints.get(5), is(4)); } @Test public void shouldMergeStream() throws Exception {
Stream<Integer> merged = Streams.merge(first.stream(), second.stream());
rec-framework/rec-core
src/main/java/net/kimleo/rec/App.java
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // }
import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die;
package net.kimleo.rec; public class App { private final static Logger LOGGER = LoggerFactory.getLogger(App.class); public static final String MSG_NO_SIZE_SPECIFIED = "Cannot infer binary file column size, please specify one."; public static void main(String[] args) throws Exception { LOGGER.info("Application started"); LOGGER.info("Args:" + Arrays.toString(args)); System.out.println("=> Rec v2"); if (args.length <= 0) {
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // } // Path: src/main/java/net/kimleo/rec/App.java import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die; package net.kimleo.rec; public class App { private final static Logger LOGGER = LoggerFactory.getLogger(App.class); public static final String MSG_NO_SIZE_SPECIFIED = "Cannot infer binary file column size, please specify one."; public static void main(String[] args) throws Exception { LOGGER.info("Application started"); LOGGER.info("Args:" + Arrays.toString(args)); System.out.println("=> Rec v2"); if (args.length <= 0) {
die("You should provide a script file or using commands");
rec-framework/rec-core
src/main/java/net/kimleo/rec/App.java
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // }
import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die;
if (args.length >= 2) { dispatch(args); } LOGGER.info("Application ended"); } private static void dispatch(String[] args) throws Exception { String retryFile = null; int retry = Arrays.asList(args).indexOf("--retry"); if (retry > 0 && args.length >= retry) { retryFile = args[retry + 1]; } String command = args[0]; switch (command) { case "js": case "script": execute(args[1], retryFile != null, retryFile); break; case "dump": String fileName = args[1]; File binFile = new File(fileName); int size; if (args.length == 3) { size = Integer.parseInt(args[2]); } else { size = inferSizeFromFileName(fileName); }
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // } // Path: src/main/java/net/kimleo/rec/App.java import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die; if (args.length >= 2) { dispatch(args); } LOGGER.info("Application ended"); } private static void dispatch(String[] args) throws Exception { String retryFile = null; int retry = Arrays.asList(args).indexOf("--retry"); if (retry > 0 && args.length >= retry) { retryFile = args[retry + 1]; } String command = args[0]; switch (command) { case "js": case "script": execute(args[1], retryFile != null, retryFile); break; case "dump": String fileName = args[1]; File binFile = new File(fileName); int size; if (args.length == 3) { size = Integer.parseInt(args[2]); } else { size = inferSizeFromFileName(fileName); }
Records.dump(binFile, size);
rec-framework/rec-core
src/main/java/net/kimleo/rec/App.java
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // }
import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die;
int retry = Arrays.asList(args).indexOf("--retry"); if (retry > 0 && args.length >= retry) { retryFile = args[retry + 1]; } String command = args[0]; switch (command) { case "js": case "script": execute(args[1], retryFile != null, retryFile); break; case "dump": String fileName = args[1]; File binFile = new File(fileName); int size; if (args.length == 3) { size = Integer.parseInt(args[2]); } else { size = inferSizeFromFileName(fileName); } Records.dump(binFile, size); break; } } private static int inferSizeFromFileName(String fileName) { return Integer.parseInt( Arrays.stream(fileName.split("\\.")) .findFirst() .orElseThrow(() ->
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // } // Path: src/main/java/net/kimleo/rec/App.java import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die; int retry = Arrays.asList(args).indexOf("--retry"); if (retry > 0 && args.length >= retry) { retryFile = args[retry + 1]; } String command = args[0]; switch (command) { case "js": case "script": execute(args[1], retryFile != null, retryFile); break; case "dump": String fileName = args[1]; File binFile = new File(fileName); int size; if (args.length == 3) { size = Integer.parseInt(args[2]); } else { size = inferSizeFromFileName(fileName); } Records.dump(binFile, size); break; } } private static int inferSizeFromFileName(String fileName) { return Integer.parseInt( Arrays.stream(fileName.split("\\.")) .findFirst() .orElseThrow(() ->
new InitializationException(MSG_NO_SIZE_SPECIFIED)));
rec-framework/rec-core
src/main/java/net/kimleo/rec/App.java
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // }
import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die;
case "js": case "script": execute(args[1], retryFile != null, retryFile); break; case "dump": String fileName = args[1]; File binFile = new File(fileName); int size; if (args.length == 3) { size = Integer.parseInt(args[2]); } else { size = inferSizeFromFileName(fileName); } Records.dump(binFile, size); break; } } private static int inferSizeFromFileName(String fileName) { return Integer.parseInt( Arrays.stream(fileName.split("\\.")) .findFirst() .orElseThrow(() -> new InitializationException(MSG_NO_SIZE_SPECIFIED))); } private static void execute(String fileName, boolean b, String retryFile) throws Exception { File file = new File(fileName); if (!file.exists()) die("File %s not found!", fileName);
// Path: src/main/java/net/kimleo/rec/common/exception/InitializationException.java // public class InitializationException extends RuntimeException { // public InitializationException(String s, Exception ex) { // super(s, ex); // } // // public InitializationException(String message) { // super(message); // } // } // // Path: src/main/java/net/kimleo/rec/v2/scripting/Scripting.java // public class Scripting { // public static void runfile(File file, // String filename, // boolean enableRetry, // String retryFile) throws Exception { // Context ctx = Context.enter(); // ctx.putThreadLocal("SCRIPT_PATH", file.getAbsoluteFile().getParent()); // // ScriptableObject scope = ctx.initStandardObjects(); // // NativeExecutionContext executionContext = initializeNativeExecutionContext( // file, // enableRetry, // retryFile, // ctx); // // scope.putConst("context", scope, javaToJS(executionContext, scope)); // // ctx.setLanguageVersion(VERSION_1_8); // Require require = new RequireBuilder() // .setModuleScriptProvider(new SoftCachingModuleScriptProvider(new NativeModuleSourceProvider())) // .createRequire(ctx, scope); // require.install(scope); // require.requireMain(ctx, filename); // } // // private static NativeExecutionContext initializeNativeExecutionContext(File file, // boolean enableRetry, // String retryFile, // Context ctx) { // NativeExecutionContext executionContext = initialContext(); // // executionContext.setScriptPath(file.getAbsoluteFile().getParent()); // executionContext.setJsContext(ctx); // executionContext.setEnableRetry(enableRetry); // executionContext.setRetryFile(retryFile); // return executionContext; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public class Records { // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // // private static int sizeof(Mapped<String> record, List<String> keys) { // int size = 4; // // for (String key : keys) { // size += 4; // size += record.get(key).getBytes().length; // } // return size; // } // // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // public static void dump(File file, int expectSize) { // try { // long length = file.length(); // MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) // .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); // // int readPos = 0; // // while (readPos < byteBuffer.limit()) { // Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); // if (result == null) break; // readPos += result.second; // // System.out.println(result.first.stream().collect(Collectors.joining(", "))); // } // } catch (IOException e) { // throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e); // } // } // // } // // Path: src/main/java/net/kimleo/rec/util/Sys.java // public static void die(String format, String... args) { // System.err.println(new Formatter().format(format, (Object[]) args)); // exit(-1); // } // Path: src/main/java/net/kimleo/rec/App.java import net.kimleo.rec.common.exception.InitializationException; import net.kimleo.rec.v2.scripting.Scripting; import net.kimleo.rec.v2.utils.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Arrays; import static net.kimleo.rec.util.Sys.die; case "js": case "script": execute(args[1], retryFile != null, retryFile); break; case "dump": String fileName = args[1]; File binFile = new File(fileName); int size; if (args.length == 3) { size = Integer.parseInt(args[2]); } else { size = inferSizeFromFileName(fileName); } Records.dump(binFile, size); break; } } private static int inferSizeFromFileName(String fileName) { return Integer.parseInt( Arrays.stream(fileName.split("\\.")) .findFirst() .orElseThrow(() -> new InitializationException(MSG_NO_SIZE_SPECIFIED))); } private static void execute(String fileName, boolean b, String retryFile) throws Exception { File file = new File(fileName); if (!file.exists()) die("File %s not found!", fileName);
Scripting.runfile(file, fileName, b, retryFile);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/CSVSource.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.model.Source; import java.io.BufferedReader; import java.io.Reader; import java.util.stream.Stream;
package net.kimleo.rec.v2.model.impl; public class CSVSource implements Source<Mapped<String>> { private final BufferedReader reader;
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/CSVSource.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.model.Source; import java.io.BufferedReader; import java.io.Reader; import java.util.stream.Stream; package net.kimleo.rec.v2.model.impl; public class CSVSource implements Source<Mapped<String>> { private final BufferedReader reader;
private final Accessor<String> accessor;
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/CSVSource.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.model.Source; import java.io.BufferedReader; import java.io.Reader; import java.util.stream.Stream;
package net.kimleo.rec.v2.model.impl; public class CSVSource implements Source<Mapped<String>> { private final BufferedReader reader; private final Accessor<String> accessor;
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/CSVSource.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.model.Source; import java.io.BufferedReader; import java.io.Reader; import java.util.stream.Stream; package net.kimleo.rec.v2.model.impl; public class CSVSource implements Source<Mapped<String>> { private final BufferedReader reader; private final Accessor<String> accessor;
private final SimpleParser csvParser;
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/CSVSource.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.model.Source; import java.io.BufferedReader; import java.io.Reader; import java.util.stream.Stream;
package net.kimleo.rec.v2.model.impl; public class CSVSource implements Source<Mapped<String>> { private final BufferedReader reader; private final Accessor<String> accessor; private final SimpleParser csvParser; private final int skipLimit; private CSVSource(BufferedReader reader, Accessor<String> accessor, SimpleParser csvParser, int skipLimit) { this.reader = reader; this.accessor = accessor; this.csvParser = csvParser; this.skipLimit = skipLimit; }
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/CSVSource.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.model.Source; import java.io.BufferedReader; import java.io.Reader; import java.util.stream.Stream; package net.kimleo.rec.v2.model.impl; public class CSVSource implements Source<Mapped<String>> { private final BufferedReader reader; private final Accessor<String> accessor; private final SimpleParser csvParser; private final int skipLimit; private CSVSource(BufferedReader reader, Accessor<String> accessor, SimpleParser csvParser, int skipLimit) { this.reader = reader; this.accessor = accessor; this.csvParser = csvParser; this.skipLimit = skipLimit; }
public CSVSource(Reader reader, String accessors, ParseConfig config) {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java
// Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // }
import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.utils.Persistence; import org.mozilla.javascript.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.util.Date; import static java.lang.String.format;
package net.kimleo.rec.v2.execution.impl; public final class NativeExecutionContext implements ExecutionContext, Serializable { public static final long serialVersionUID = 1453356753764L; private int count = 0; private final int baseCount; private static final Logger LOGGER = LoggerFactory.getLogger(NativeExecutionContext.class); private String scriptPath; private transient Context jsContext; private transient boolean enableRetry; private String retryFile = null; public NativeExecutionContext(int baseCount) { this.baseCount = baseCount; LOGGER.info(format("Initialize execution context based on count %d", baseCount)); } public int state() { return baseCount; } @Override public void commit() { count ++; } public void persist(Throwable causedBy) { try { String filename = String.valueOf(new Date().getTime()).concat(".retry");
// Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // } // Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.utils.Persistence; import org.mozilla.javascript.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.util.Date; import static java.lang.String.format; package net.kimleo.rec.v2.execution.impl; public final class NativeExecutionContext implements ExecutionContext, Serializable { public static final long serialVersionUID = 1453356753764L; private int count = 0; private final int baseCount; private static final Logger LOGGER = LoggerFactory.getLogger(NativeExecutionContext.class); private String scriptPath; private transient Context jsContext; private transient boolean enableRetry; private String retryFile = null; public NativeExecutionContext(int baseCount) { this.baseCount = baseCount; LOGGER.info(format("Initialize execution context based on count %d", baseCount)); } public int state() { return baseCount; } @Override public void commit() { count ++; } public void persist(Throwable causedBy) { try { String filename = String.valueOf(new Date().getTime()).concat(".retry");
Persistence.saveObjectToFile(this, filename);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java
// Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // }
import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.utils.Persistence; import org.mozilla.javascript.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.util.Date; import static java.lang.String.format;
package net.kimleo.rec.v2.execution.impl; public final class NativeExecutionContext implements ExecutionContext, Serializable { public static final long serialVersionUID = 1453356753764L; private int count = 0; private final int baseCount; private static final Logger LOGGER = LoggerFactory.getLogger(NativeExecutionContext.class); private String scriptPath; private transient Context jsContext; private transient boolean enableRetry; private String retryFile = null; public NativeExecutionContext(int baseCount) { this.baseCount = baseCount; LOGGER.info(format("Initialize execution context based on count %d", baseCount)); } public int state() { return baseCount; } @Override public void commit() { count ++; } public void persist(Throwable causedBy) { try { String filename = String.valueOf(new Date().getTime()).concat(".retry"); Persistence.saveObjectToFile(this, filename); LOGGER.info(format("Successfully save context to [%s]", filename)); } catch (IOException e) { LOGGER.error(format("Unable to save execution context and the count is %d", count));
// Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Persistence.java // public class Persistence { // public static void saveObjectToFile(Object serializable, String file) throws IOException { // ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file)); // stream.writeObject(serializable); // } // // public static Object loadObjectFromFile(String file) throws IOException, ClassNotFoundException { // ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // // return in.readObject(); // } // } // Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.utils.Persistence; import org.mozilla.javascript.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.util.Date; import static java.lang.String.format; package net.kimleo.rec.v2.execution.impl; public final class NativeExecutionContext implements ExecutionContext, Serializable { public static final long serialVersionUID = 1453356753764L; private int count = 0; private final int baseCount; private static final Logger LOGGER = LoggerFactory.getLogger(NativeExecutionContext.class); private String scriptPath; private transient Context jsContext; private transient boolean enableRetry; private String retryFile = null; public NativeExecutionContext(int baseCount) { this.baseCount = baseCount; LOGGER.info(format("Initialize execution context based on count %d", baseCount)); } public int state() { return baseCount; } @Override public void commit() { count ++; } public void persist(Throwable causedBy) { try { String filename = String.valueOf(new Date().getTime()).concat(".retry"); Persistence.saveObjectToFile(this, filename); LOGGER.info(format("Successfully save context to [%s]", filename)); } catch (IOException e) { LOGGER.error(format("Unable to save execution context and the count is %d", count));
throw new ResourceAccessException("Cannot persist execution context", e);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/accessor/RecordWrapperTest.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // }
import net.kimleo.rec.common.Pair; import org.junit.Test; import java.util.Map; import static net.kimleo.rec.v2.accessor.lexer.Lexer.buildFieldMapPair; import static org.junit.Assert.assertTrue;
package net.kimleo.rec.v2.accessor; public class RecordWrapperTest { @Test public void shouldBuildMapPairSuccessfully() throws Exception {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // Path: src/test/java/net/kimleo/rec/v2/accessor/RecordWrapperTest.java import net.kimleo.rec.common.Pair; import org.junit.Test; import java.util.Map; import static net.kimleo.rec.v2.accessor.lexer.Lexer.buildFieldMapPair; import static org.junit.Assert.assertTrue; package net.kimleo.rec.v2.accessor; public class RecordWrapperTest { @Test public void shouldBuildMapPairSuccessfully() throws Exception {
Pair<Map<String, Integer>, Integer> pair = buildFieldMapPair(
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/accessor/RecordWrapperTest.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // }
import net.kimleo.rec.common.Pair; import org.junit.Test; import java.util.Map; import static net.kimleo.rec.v2.accessor.lexer.Lexer.buildFieldMapPair; import static org.junit.Assert.assertTrue;
package net.kimleo.rec.v2.accessor; public class RecordWrapperTest { @Test public void shouldBuildMapPairSuccessfully() throws Exception {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java // public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { // final Map<String, Integer> accessorMap = new LinkedHashMap<>(); // final Pair<List<FieldType>, Integer> lex = lex(fields); // final List<FieldType> accessors = lex.getFirst(); // final Integer leastCapacity = lex.getSecond(); // boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1); // // if (reversed) { // buildFieldMaps(accessorMap, reversed(accessors), -1,-1); // } // // return new Pair<>(accessorMap, leastCapacity); // } // Path: src/test/java/net/kimleo/rec/v2/accessor/RecordWrapperTest.java import net.kimleo.rec.common.Pair; import org.junit.Test; import java.util.Map; import static net.kimleo.rec.v2.accessor.lexer.Lexer.buildFieldMapPair; import static org.junit.Assert.assertTrue; package net.kimleo.rec.v2.accessor; public class RecordWrapperTest { @Test public void shouldBuildMapPairSuccessfully() throws Exception {
Pair<Map<String, Integer>, Integer> pair = buildFieldMapPair(
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/issue/Issue36Test.java
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/RecordWrapper.java // public class RecordWrapper<T> implements Accessible<T>, Mapped<T> { // // private final Map<String, Integer> fieldNames; // // private final Accessible<T> record; // // public RecordWrapper(Map<String, Integer> fieldNames, Accessible<T> record) { // this.fieldNames = fieldNames; // this.record = record; // } // // @Override // public T get(int index) { // return getByIndex(index, record); // } // // @Override // public int size() { // return record.size(); // } // // @Override // public T get(String field) { // if (fieldNames.containsKey(field)) { // return getByIndex(fieldNames.get(field), record); // } // return null; // } // // private T getByIndex(Integer index, Accessible<T> record) { // if (index >= 0) { // return record.get(index); // } else { // return record.get(record.size() + index); // } // } // // @Override // public List<String> keys() { // return fieldNames.keySet().stream().collect(Collectors.toList()); // } // // @Override // public String toString() { // return record.toString(); // } // }
import net.kimleo.rec.sepval.SepValEntry; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.accessor.RecordWrapper; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package net.kimleo.rec.v2.issue; // See https://github.com/rec-framework/rec-core/issues/36 public class Issue36Test { private final SimpleParser parser = new SimpleParser(); @Test public void shouldOriginallyPass() throws Exception {
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/Accessor.java // public class Accessor<T> { // // private final Map<String, Integer> fieldMap; // private final Integer leastCapacity; // // public Accessor(String[] fields) { // Pair<Map<String, Integer>, Integer> fieldMapPair = Lexer.buildFieldMapPair(fields); // fieldMap = fieldMapPair.getFirst(); // leastCapacity = fieldMapPair.getSecond(); // } // // public Map<String, Integer> getFieldMap() { // return fieldMap; // } // // public Integer getLeastCapacity() { // return leastCapacity; // } // // public RecordWrapper<T> create(Accessible<T> record) { // assertTrue (record.size() >= leastCapacity); // // return new RecordWrapper<>(fieldMap, record); // } // // public RecordWrapper<T> of(Accessible<T> record) { // return create(record); // } // } // // Path: src/main/java/net/kimleo/rec/v2/accessor/RecordWrapper.java // public class RecordWrapper<T> implements Accessible<T>, Mapped<T> { // // private final Map<String, Integer> fieldNames; // // private final Accessible<T> record; // // public RecordWrapper(Map<String, Integer> fieldNames, Accessible<T> record) { // this.fieldNames = fieldNames; // this.record = record; // } // // @Override // public T get(int index) { // return getByIndex(index, record); // } // // @Override // public int size() { // return record.size(); // } // // @Override // public T get(String field) { // if (fieldNames.containsKey(field)) { // return getByIndex(fieldNames.get(field), record); // } // return null; // } // // private T getByIndex(Integer index, Accessible<T> record) { // if (index >= 0) { // return record.get(index); // } else { // return record.get(record.size() + index); // } // } // // @Override // public List<String> keys() { // return fieldNames.keySet().stream().collect(Collectors.toList()); // } // // @Override // public String toString() { // return record.toString(); // } // } // Path: src/test/java/net/kimleo/rec/v2/issue/Issue36Test.java import net.kimleo.rec.sepval.SepValEntry; import net.kimleo.rec.sepval.parser.SimpleParser; import net.kimleo.rec.v2.accessor.Accessor; import net.kimleo.rec.v2.accessor.RecordWrapper; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package net.kimleo.rec.v2.issue; // See https://github.com/rec-framework/rec-core/issues/36 public class Issue36Test { private final SimpleParser parser = new SimpleParser(); @Test public void shouldOriginallyPass() throws Exception {
SepValEntry entry = parser.parse("1, 2, 3, 4, 5,,,,123");
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/utils/Streams.java
// Path: src/main/java/net/kimleo/rec/v2/stream/MergeIterator.java // public class MergeIterator<T> implements Iterator<T> { // // private final Iterator<T> first; // private final Iterator<T> second; // private T next1; // private T next2; // // private final Comparator<T> comparator; // // public MergeIterator(Iterator<T> first, Iterator<T> second, Comparator<T> comparator) { // this.first = first; // this.second = second; // next1 = first.hasNext() ? first.next() : null; // next2 = second.hasNext() ? second.next() : null; // this.comparator = comparator; // } // // @Override // public T next() { // // if(!hasNext()) { // return null; // } // // boolean useStream1 = (next1 != null && next2 == null) || // (next1 != null && comparator.compare(next1, next2) <= 0); // // if(useStream1) { // T returnObject = next1; // next1 = first.hasNext() ? first.next() : null; // return returnObject; // } // else { // T returnObject = next2; // next2 = second.hasNext() ? second.next() : null; // return returnObject; // } // } // // @Override // public boolean hasNext() { // return next1 != null || next2 != null; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/IteratingSpliteratorAdapter.java // public class IteratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // private final Iterator<T> iterator; // // public IteratingSpliteratorAdapter(Iterator<T> iterator) { // super(Long.MAX_VALUE, 0); // this.iterator = iterator; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // if (iterator.hasNext()) { // action.accept(iterator.next()); // return true; // } // return false; // } // }
import net.kimleo.rec.v2.stream.MergeIterator; import net.kimleo.rec.v2.stream.adapter.IteratingSpliteratorAdapter; import java.util.Comparator; import java.util.stream.Stream; import java.util.stream.StreamSupport;
package net.kimleo.rec.v2.utils; public class Streams { public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, Stream<T> second) {
// Path: src/main/java/net/kimleo/rec/v2/stream/MergeIterator.java // public class MergeIterator<T> implements Iterator<T> { // // private final Iterator<T> first; // private final Iterator<T> second; // private T next1; // private T next2; // // private final Comparator<T> comparator; // // public MergeIterator(Iterator<T> first, Iterator<T> second, Comparator<T> comparator) { // this.first = first; // this.second = second; // next1 = first.hasNext() ? first.next() : null; // next2 = second.hasNext() ? second.next() : null; // this.comparator = comparator; // } // // @Override // public T next() { // // if(!hasNext()) { // return null; // } // // boolean useStream1 = (next1 != null && next2 == null) || // (next1 != null && comparator.compare(next1, next2) <= 0); // // if(useStream1) { // T returnObject = next1; // next1 = first.hasNext() ? first.next() : null; // return returnObject; // } // else { // T returnObject = next2; // next2 = second.hasNext() ? second.next() : null; // return returnObject; // } // } // // @Override // public boolean hasNext() { // return next1 != null || next2 != null; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/IteratingSpliteratorAdapter.java // public class IteratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // private final Iterator<T> iterator; // // public IteratingSpliteratorAdapter(Iterator<T> iterator) { // super(Long.MAX_VALUE, 0); // this.iterator = iterator; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // if (iterator.hasNext()) { // action.accept(iterator.next()); // return true; // } // return false; // } // } // Path: src/main/java/net/kimleo/rec/v2/utils/Streams.java import net.kimleo.rec.v2.stream.MergeIterator; import net.kimleo.rec.v2.stream.adapter.IteratingSpliteratorAdapter; import java.util.Comparator; import java.util.stream.Stream; import java.util.stream.StreamSupport; package net.kimleo.rec.v2.utils; public class Streams { public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, Stream<T> second) {
MergeIterator<T> iterator = new MergeIterator<>(
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/utils/Streams.java
// Path: src/main/java/net/kimleo/rec/v2/stream/MergeIterator.java // public class MergeIterator<T> implements Iterator<T> { // // private final Iterator<T> first; // private final Iterator<T> second; // private T next1; // private T next2; // // private final Comparator<T> comparator; // // public MergeIterator(Iterator<T> first, Iterator<T> second, Comparator<T> comparator) { // this.first = first; // this.second = second; // next1 = first.hasNext() ? first.next() : null; // next2 = second.hasNext() ? second.next() : null; // this.comparator = comparator; // } // // @Override // public T next() { // // if(!hasNext()) { // return null; // } // // boolean useStream1 = (next1 != null && next2 == null) || // (next1 != null && comparator.compare(next1, next2) <= 0); // // if(useStream1) { // T returnObject = next1; // next1 = first.hasNext() ? first.next() : null; // return returnObject; // } // else { // T returnObject = next2; // next2 = second.hasNext() ? second.next() : null; // return returnObject; // } // } // // @Override // public boolean hasNext() { // return next1 != null || next2 != null; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/IteratingSpliteratorAdapter.java // public class IteratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // private final Iterator<T> iterator; // // public IteratingSpliteratorAdapter(Iterator<T> iterator) { // super(Long.MAX_VALUE, 0); // this.iterator = iterator; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // if (iterator.hasNext()) { // action.accept(iterator.next()); // return true; // } // return false; // } // }
import net.kimleo.rec.v2.stream.MergeIterator; import net.kimleo.rec.v2.stream.adapter.IteratingSpliteratorAdapter; import java.util.Comparator; import java.util.stream.Stream; import java.util.stream.StreamSupport;
package net.kimleo.rec.v2.utils; public class Streams { public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, Stream<T> second) { MergeIterator<T> iterator = new MergeIterator<>( first.iterator(), second.iterator(), Comparable::compareTo);
// Path: src/main/java/net/kimleo/rec/v2/stream/MergeIterator.java // public class MergeIterator<T> implements Iterator<T> { // // private final Iterator<T> first; // private final Iterator<T> second; // private T next1; // private T next2; // // private final Comparator<T> comparator; // // public MergeIterator(Iterator<T> first, Iterator<T> second, Comparator<T> comparator) { // this.first = first; // this.second = second; // next1 = first.hasNext() ? first.next() : null; // next2 = second.hasNext() ? second.next() : null; // this.comparator = comparator; // } // // @Override // public T next() { // // if(!hasNext()) { // return null; // } // // boolean useStream1 = (next1 != null && next2 == null) || // (next1 != null && comparator.compare(next1, next2) <= 0); // // if(useStream1) { // T returnObject = next1; // next1 = first.hasNext() ? first.next() : null; // return returnObject; // } // else { // T returnObject = next2; // next2 = second.hasNext() ? second.next() : null; // return returnObject; // } // } // // @Override // public boolean hasNext() { // return next1 != null || next2 != null; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/IteratingSpliteratorAdapter.java // public class IteratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // private final Iterator<T> iterator; // // public IteratingSpliteratorAdapter(Iterator<T> iterator) { // super(Long.MAX_VALUE, 0); // this.iterator = iterator; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // if (iterator.hasNext()) { // action.accept(iterator.next()); // return true; // } // return false; // } // } // Path: src/main/java/net/kimleo/rec/v2/utils/Streams.java import net.kimleo.rec.v2.stream.MergeIterator; import net.kimleo.rec.v2.stream.adapter.IteratingSpliteratorAdapter; import java.util.Comparator; import java.util.stream.Stream; import java.util.stream.StreamSupport; package net.kimleo.rec.v2.utils; public class Streams { public static <T extends Comparable<T>> Stream<T> merge(Stream<T> first, Stream<T> second) { MergeIterator<T> iterator = new MergeIterator<>( first.iterator(), second.iterator(), Comparable::compareTo);
IteratingSpliteratorAdapter<T> adapter = new IteratingSpliteratorAdapter<>(iterator);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/ResultSetSource.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/mapper/ResultSetMapper.java // public class ResultSetMapper implements Mapped<String> { // // private final ResultSet rs; // // public ResultSetMapper(ResultSet rs) { // this.rs = rs; // } // // @Override // public String get(String field) { // try { // return rs.getObject(field).toString(); // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // @Override // public List<String> keys() { // ArrayList<String> keys = new ArrayList<>(); // try { // ResultSetMetaData metaData = rs.getMetaData(); // for (int i = 0; i < metaData.getColumnCount(); i++) { // keys.add(metaData.getColumnName(i + 1)); // } // } catch (SQLException ignored) { // ignored.printStackTrace(); // } // return keys; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.mapper.ResultSetMapper; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.lang.String.format;
package net.kimleo.rec.v2.model.impl; public class ResultSetSource implements Source<Mapped<String>> { private final ResultSet rs; private static final Logger LOGGER = LoggerFactory.getLogger(ResultSetSource.class); public ResultSetSource(ResultSet rs) { this.rs = rs; } @Override public Stream<Mapped<String>> stream() {
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/mapper/ResultSetMapper.java // public class ResultSetMapper implements Mapped<String> { // // private final ResultSet rs; // // public ResultSetMapper(ResultSet rs) { // this.rs = rs; // } // // @Override // public String get(String field) { // try { // return rs.getObject(field).toString(); // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // @Override // public List<String> keys() { // ArrayList<String> keys = new ArrayList<>(); // try { // ResultSetMetaData metaData = rs.getMetaData(); // for (int i = 0; i < metaData.getColumnCount(); i++) { // keys.add(metaData.getColumnName(i + 1)); // } // } catch (SQLException ignored) { // ignored.printStackTrace(); // } // return keys; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/ResultSetSource.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.mapper.ResultSetMapper; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.lang.String.format; package net.kimleo.rec.v2.model.impl; public class ResultSetSource implements Source<Mapped<String>> { private final ResultSet rs; private static final Logger LOGGER = LoggerFactory.getLogger(ResultSetSource.class); public ResultSetSource(ResultSet rs) { this.rs = rs; } @Override public Stream<Mapped<String>> stream() {
return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/ResultSetSource.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/mapper/ResultSetMapper.java // public class ResultSetMapper implements Mapped<String> { // // private final ResultSet rs; // // public ResultSetMapper(ResultSet rs) { // this.rs = rs; // } // // @Override // public String get(String field) { // try { // return rs.getObject(field).toString(); // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // @Override // public List<String> keys() { // ArrayList<String> keys = new ArrayList<>(); // try { // ResultSetMetaData metaData = rs.getMetaData(); // for (int i = 0; i < metaData.getColumnCount(); i++) { // keys.add(metaData.getColumnName(i + 1)); // } // } catch (SQLException ignored) { // ignored.printStackTrace(); // } // return keys; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.mapper.ResultSetMapper; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.lang.String.format;
package net.kimleo.rec.v2.model.impl; public class ResultSetSource implements Source<Mapped<String>> { private final ResultSet rs; private static final Logger LOGGER = LoggerFactory.getLogger(ResultSetSource.class); public ResultSetSource(ResultSet rs) { this.rs = rs; } @Override public Stream<Mapped<String>> stream() { return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> { try { if (rs.next()) { LOGGER.info(format("Get next item in result set #[%d]", rs.hashCode()));
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/mapper/ResultSetMapper.java // public class ResultSetMapper implements Mapped<String> { // // private final ResultSet rs; // // public ResultSetMapper(ResultSet rs) { // this.rs = rs; // } // // @Override // public String get(String field) { // try { // return rs.getObject(field).toString(); // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // @Override // public List<String> keys() { // ArrayList<String> keys = new ArrayList<>(); // try { // ResultSetMetaData metaData = rs.getMetaData(); // for (int i = 0; i < metaData.getColumnCount(); i++) { // keys.add(metaData.getColumnName(i + 1)); // } // } catch (SQLException ignored) { // ignored.printStackTrace(); // } // return keys; // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/ResultSetSource.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.mapper.ResultSetMapper; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.ResultSet; import java.sql.SQLException; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.lang.String.format; package net.kimleo.rec.v2.model.impl; public class ResultSetSource implements Source<Mapped<String>> { private final ResultSet rs; private static final Logger LOGGER = LoggerFactory.getLogger(ResultSetSource.class); public ResultSetSource(ResultSet rs) { this.rs = rs; } @Override public Stream<Mapped<String>> stream() { return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> { try { if (rs.next()) { LOGGER.info(format("Get next item in result set #[%d]", rs.hashCode()));
return new ResultSetMapper(rs);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/util/CollectUtils.java // public static <T> Iterable<T> reversed(List<T> list) { // // // return () -> { // ListIterator<T> li = list.listIterator(list.size()); // // return new Iterator<T>() { // @Override // public boolean hasNext() { // return li.hasPrevious(); // } // // @Override // public T next() { // return li.previous(); // } // }; // }; // }
import net.kimleo.rec.common.Pair; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static net.kimleo.rec.util.CollectUtils.reversed;
package net.kimleo.rec.v2.accessor.lexer; public class Lexer { public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}");
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/util/CollectUtils.java // public static <T> Iterable<T> reversed(List<T> list) { // // // return () -> { // ListIterator<T> li = list.listIterator(list.size()); // // return new Iterator<T>() { // @Override // public boolean hasNext() { // return li.hasPrevious(); // } // // @Override // public T next() { // return li.previous(); // } // }; // }; // } // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java import net.kimleo.rec.common.Pair; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static net.kimleo.rec.util.CollectUtils.reversed; package net.kimleo.rec.v2.accessor.lexer; public class Lexer { public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}");
public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/util/CollectUtils.java // public static <T> Iterable<T> reversed(List<T> list) { // // // return () -> { // ListIterator<T> li = list.listIterator(list.size()); // // return new Iterator<T>() { // @Override // public boolean hasNext() { // return li.hasPrevious(); // } // // @Override // public T next() { // return li.previous(); // } // }; // }; // }
import net.kimleo.rec.common.Pair; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static net.kimleo.rec.util.CollectUtils.reversed;
package net.kimleo.rec.v2.accessor.lexer; public class Lexer { public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { final Map<String, Integer> accessorMap = new LinkedHashMap<>(); final Pair<List<FieldType>, Integer> lex = lex(fields); final List<FieldType> accessors = lex.getFirst(); final Integer leastCapacity = lex.getSecond();
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/util/CollectUtils.java // public static <T> Iterable<T> reversed(List<T> list) { // // // return () -> { // ListIterator<T> li = list.listIterator(list.size()); // // return new Iterator<T>() { // @Override // public boolean hasNext() { // return li.hasPrevious(); // } // // @Override // public T next() { // return li.previous(); // } // }; // }; // } // Path: src/main/java/net/kimleo/rec/v2/accessor/lexer/Lexer.java import net.kimleo.rec.common.Pair; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import static net.kimleo.rec.util.CollectUtils.reversed; package net.kimleo.rec.v2.accessor.lexer; public class Lexer { public static final Pattern PADDING_PATTERN = Pattern.compile("\\{(\\d+)}"); public static Pair<Map<String, Integer>, Integer> buildFieldMapPair(String... fields) { final Map<String, Integer> accessorMap = new LinkedHashMap<>(); final Pair<List<FieldType>, Integer> lex = lex(fields); final List<FieldType> accessors = lex.getFirst(); final Integer leastCapacity = lex.getSecond();
boolean reversed = buildFieldMaps(accessorMap, accessors, 0, 1);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/FlatFileTarget.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Target; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.util.stream.Collectors;
package net.kimleo.rec.v2.model.impl; public class FlatFileTarget implements Target<Mapped<String>>, Closeable { private final PrintWriter writer; public FlatFileTarget(File file) { try { writer = new PrintWriter(Files.newBufferedWriter(file.toPath())); } catch (IOException e) {
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/FlatFileTarget.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Target; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.util.stream.Collectors; package net.kimleo.rec.v2.model.impl; public class FlatFileTarget implements Target<Mapped<String>>, Closeable { private final PrintWriter writer; public FlatFileTarget(File file) { try { writer = new PrintWriter(Files.newBufferedWriter(file.toPath())); } catch (IOException e) {
throw new ResourceAccessException(String.format("Cannot open output file: [%s]", file.getName()), e);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/FlatFileTarget.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Target; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.util.stream.Collectors;
package net.kimleo.rec.v2.model.impl; public class FlatFileTarget implements Target<Mapped<String>>, Closeable { private final PrintWriter writer; public FlatFileTarget(File file) { try { writer = new PrintWriter(Files.newBufferedWriter(file.toPath())); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot open output file: [%s]", file.getName()), e); } } @Override public void put(Mapped<String> record) { writer.println(record.keys().stream().map(record::get).collect(Collectors.joining(", "))); } @Override
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/FlatFileTarget.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Target; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.util.stream.Collectors; package net.kimleo.rec.v2.model.impl; public class FlatFileTarget implements Target<Mapped<String>>, Closeable { private final PrintWriter writer; public FlatFileTarget(File file) { try { writer = new PrintWriter(Files.newBufferedWriter(file.toPath())); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot open output file: [%s]", file.getName()), e); } } @Override public void put(Mapped<String> record) { writer.println(record.keys().stream().map(record::get).collect(Collectors.joining(", "))); } @Override
public void putAll(Source<Mapped<String>> source) {
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/SimpleParserTest.java
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // }
import net.kimleo.rec.sepval.SepValEntry; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package net.kimleo.rec.v2; public class SimpleParserTest { private final SimpleParser parser = new SimpleParser(); @Test public void shouldParseSimpleCSV() throws Exception {
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // Path: src/test/java/net/kimleo/rec/v2/SimpleParserTest.java import net.kimleo.rec.sepval.SepValEntry; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package net.kimleo.rec.v2; public class SimpleParserTest { private final SimpleParser parser = new SimpleParser(); @Test public void shouldParseSimpleCSV() throws Exception {
SepValEntry tuple = parser.parse("a, b, c");
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/SimpleParserTest.java
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // }
import net.kimleo.rec.sepval.SepValEntry; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull;
package net.kimleo.rec.v2; public class SimpleParserTest { private final SimpleParser parser = new SimpleParser(); @Test public void shouldParseSimpleCSV() throws Exception { SepValEntry tuple = parser.parse("a, b, c"); assertEquals(tuple.size(), 3); assertEquals(tuple.get(1), "b"); } @Test public void shouldParseQuotedString() throws Exception { SepValEntry tuple = parser.parse("\"abc\", \" \"\" \t\r\n\\\b def \" , g"); assertEquals(tuple.size(), 3); assertEquals(tuple.get(1), " \" \t\r\n\\\b def "); assertEquals(tuple.get(2), "g"); } @Test public void shouldParseDifferentDelimiter() throws Exception {
// Path: src/main/java/net/kimleo/rec/sepval/SepValEntry.java // public class SepValEntry implements Accessible<String> { // // private final List<String> values; // private final String source; // // public SepValEntry(List<String> values, String source) { // this.values = values; // this.source = source; // } // // @Override // public String get(int index) { // return values.get(index); // } // // @Override // public int size() { // return values.size(); // } // // public List<String> getValues() { // return values; // } // // public String getSource() { // return source; // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/SimpleParser.java // public class SimpleParser { // private final ParseConfig config; // // private final static Logger LOGGER = LoggerFactory.getLogger(SimpleParser.class); // // public SimpleParser(ParseConfig config) { // this.config = config; // } // // public SimpleParser() { // this(ParseConfig.DEFAULT); // } // // public SepValEntry parse(String input) { // ParseState state = new ParseState(input); // ArrayList<String> fields = new ArrayList<>(); // while (!state.eof()) { // fields.add(parseField(state)); // } // // if (state.of(state.getSize() - 1) == config.delimiter) { // LOGGER.warn(String.format("Found delimiter [%s] at end of record", config.delimiter)); // fields.add(""); // } // // return new SepValEntry(fields, input); // } // // private String parseField(ParseState state) { // StringBuilder builder = new StringBuilder(); // Character c = state.current(); // while (c != null && c != config.delimiter) { // if (builder.length() == 0) { // if (isSpace(c)) { // c = state.next(); // continue; // } // if (c == config.escape) { // return parseEscaped(state); // } // } // builder.append(c); // c = state.next(); // } // state.next(); // return builder.toString().trim(); // } // // private String parseEscaped(ParseState state) { // // StringBuilder builder = new StringBuilder(); // assert (state.current() == config.escape); // // Character c = state.next(); // while (!state.eof() || c != config.delimiter) { // if (c == config.escape) { // c = state.next(); // if (c == null || c != config.escape) { // expectDelimiter(state); // state.next(); // break; // } // } // builder.append(c); // c = state.next(); // } // return builder.toString(); // } // // private void expectDelimiter(ParseState state) { // while (isSpace(state.current())) { // state.next(); // } // // assert((state.current() == null || state.current() == config.delimiter)); // } // // private boolean isSpace(Character c) { // return c != null && (c == ' ' || c == '\t'); // } // } // Path: src/test/java/net/kimleo/rec/v2/SimpleParserTest.java import net.kimleo.rec.sepval.SepValEntry; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.sepval.parser.SimpleParser; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; package net.kimleo.rec.v2; public class SimpleParserTest { private final SimpleParser parser = new SimpleParser(); @Test public void shouldParseSimpleCSV() throws Exception { SepValEntry tuple = parser.parse("a, b, c"); assertEquals(tuple.size(), 3); assertEquals(tuple.get(1), "b"); } @Test public void shouldParseQuotedString() throws Exception { SepValEntry tuple = parser.parse("\"abc\", \" \"\" \t\r\n\\\b def \" , g"); assertEquals(tuple.size(), 3); assertEquals(tuple.get(1), " \" \t\r\n\\\b def "); assertEquals(tuple.get(2), "g"); } @Test public void shouldParseDifferentDelimiter() throws Exception {
SepValEntry tuple = new SimpleParser(new ParseConfig('|'))
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/CSVFileSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.model.impl; public class CSVFileSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI());
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/CSVFileSourceTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.model.impl; public class CSVFileSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI());
CSVFileSource source = new CSVFileSource(file, "id, name, dob, illegal", ParseConfig.DEFAULT);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/CSVFileSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.model.impl; public class CSVFileSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVFileSource source = new CSVFileSource(file, "id, name, dob, illegal", ParseConfig.DEFAULT);
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/CSVFileSourceTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.model.impl; public class CSVFileSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVFileSource source = new CSVFileSource(file, "id, name, dob, illegal", ParseConfig.DEFAULT);
CollectTee<Mapped<String>> collector = new CollectTee<>(new ArrayList<>());
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/CSVFileSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is;
package net.kimleo.rec.v2.model.impl; public class CSVFileSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVFileSource source = new CSVFileSource(file, "id, name, dob, illegal", ParseConfig.DEFAULT); CollectTee<Mapped<String>> collector = new CollectTee<>(new ArrayList<>()); HashSet<String> strings = new HashSet<>(); ItemCounterTee<Mapped<String>> counter = new ItemCounterTee<>(it -> true);
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Target.java // public interface Target<T> { // void put(T record); // // default Target<T> tee(Tee<T> tee) { // return record -> this.put(tee.emit(record)); // } // // default void putAll(Source<T> source) { // source.stream().forEach(this::put); // } // // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/CSVFileSourceTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import net.kimleo.rec.v2.model.Target; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; package net.kimleo.rec.v2.model.impl; public class CSVFileSourceTest { @Test public void shouldSuccessfullyParseAStream() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVFileSource source = new CSVFileSource(file, "id, name, dob, illegal", ParseConfig.DEFAULT); CollectTee<Mapped<String>> collector = new CollectTee<>(new ArrayList<>()); HashSet<String> strings = new HashSet<>(); ItemCounterTee<Mapped<String>> counter = new ItemCounterTee<>(it -> true);
Target<Mapped<String>> target = record ->
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/LinkedMultiHashMapTest.java
// Path: src/main/java/net/kimleo/rec/common/collection/LinkedMultiHashMap.java // public class LinkedMultiHashMap<K, V> implements MultiMap<K, V> { // // private final Map<K, Collection<V>> map = new LinkedHashMap<>(); // // @Override // public int size() { // int sum = 0; // for (Collection<V> vs : map.values()) { // if (vs != null) { // sum += vs.size(); // } // } // return sum; // } // // @Override // public boolean isEmpty() { // return map.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return map.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // for (Collection<V> vs : map.values()) { // if (vs != null && vs.contains(value)) // return true; // } // return false; // } // // @Override // public Collection<V> get(Object key) { // return map.get(key); // } // // @Override // public Collection<V> put(K key, Collection<V> value) { // if (map.containsKey(key)) { // map.get(key).addAll(value); // } else { // map.put(key, value); // } // return value; // } // // @Override // public Collection<V> remove(Object key) { // return map.remove(key); // } // // @Override // public void putAll(Map<? extends K, ? extends Collection<V>> m) { // for (K key : m.keySet()) { // if (map.containsKey(key)) { // map.get(key).addAll(m.get(key)); // } else { // map.put(key, m.get(key)); // } // } // } // // @Override // public void clear() { // map.clear(); // } // // @Override // public Set<K> keySet() { // return map.keySet(); // } // // @Override // public Collection<Collection<V>> values() { // return map.values(); // } // // @Override // public Set<Entry<K, Collection<V>>> entrySet() { // return map.entrySet(); // } // // @Override // public boolean equals(Object o) { // return o instanceof LinkedMultiHashMap && map.equals(((LinkedMultiHashMap) o).map); // } // // @Override // public int hashCode() { // return map.hashCode(); // } // // @Override // public int keyCount() { // return map.size(); // } // // @Override // public int valueCount() { // return size(); // } // // @Override // public V put1(K key, V value) { // if (map.containsKey(key)) { // map.get(key).add(value); // } else { // Set<V> vs = new HashSet<>(); // vs.add(value); // map.put(key, vs); // } // return value; // } // // public static <V, U> MultiMap<V, U> from(Stream<V> collection, Function<V, U> transform) { // LinkedMultiHashMap<V, U> multiMap = new LinkedMultiHashMap<>(); // collection.forEach(item -> multiMap.put1(item, transform.apply(item))); // // return multiMap; // } // } // // Path: src/main/java/net/kimleo/rec/common/collection/MultiMap.java // public interface MultiMap<K, V> extends Map<K, Collection<V>> { // int keyCount(); // // int valueCount(); // // V put1(K key, V value); // }
import net.kimleo.rec.common.collection.LinkedMultiHashMap; import net.kimleo.rec.common.collection.MultiMap; import org.junit.Test; import java.util.Arrays; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue;
package net.kimleo.rec.v2; public class LinkedMultiHashMapTest { @Test public void shouldBuildAMapSuccessfully() throws Exception {
// Path: src/main/java/net/kimleo/rec/common/collection/LinkedMultiHashMap.java // public class LinkedMultiHashMap<K, V> implements MultiMap<K, V> { // // private final Map<K, Collection<V>> map = new LinkedHashMap<>(); // // @Override // public int size() { // int sum = 0; // for (Collection<V> vs : map.values()) { // if (vs != null) { // sum += vs.size(); // } // } // return sum; // } // // @Override // public boolean isEmpty() { // return map.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return map.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // for (Collection<V> vs : map.values()) { // if (vs != null && vs.contains(value)) // return true; // } // return false; // } // // @Override // public Collection<V> get(Object key) { // return map.get(key); // } // // @Override // public Collection<V> put(K key, Collection<V> value) { // if (map.containsKey(key)) { // map.get(key).addAll(value); // } else { // map.put(key, value); // } // return value; // } // // @Override // public Collection<V> remove(Object key) { // return map.remove(key); // } // // @Override // public void putAll(Map<? extends K, ? extends Collection<V>> m) { // for (K key : m.keySet()) { // if (map.containsKey(key)) { // map.get(key).addAll(m.get(key)); // } else { // map.put(key, m.get(key)); // } // } // } // // @Override // public void clear() { // map.clear(); // } // // @Override // public Set<K> keySet() { // return map.keySet(); // } // // @Override // public Collection<Collection<V>> values() { // return map.values(); // } // // @Override // public Set<Entry<K, Collection<V>>> entrySet() { // return map.entrySet(); // } // // @Override // public boolean equals(Object o) { // return o instanceof LinkedMultiHashMap && map.equals(((LinkedMultiHashMap) o).map); // } // // @Override // public int hashCode() { // return map.hashCode(); // } // // @Override // public int keyCount() { // return map.size(); // } // // @Override // public int valueCount() { // return size(); // } // // @Override // public V put1(K key, V value) { // if (map.containsKey(key)) { // map.get(key).add(value); // } else { // Set<V> vs = new HashSet<>(); // vs.add(value); // map.put(key, vs); // } // return value; // } // // public static <V, U> MultiMap<V, U> from(Stream<V> collection, Function<V, U> transform) { // LinkedMultiHashMap<V, U> multiMap = new LinkedMultiHashMap<>(); // collection.forEach(item -> multiMap.put1(item, transform.apply(item))); // // return multiMap; // } // } // // Path: src/main/java/net/kimleo/rec/common/collection/MultiMap.java // public interface MultiMap<K, V> extends Map<K, Collection<V>> { // int keyCount(); // // int valueCount(); // // V put1(K key, V value); // } // Path: src/test/java/net/kimleo/rec/v2/LinkedMultiHashMapTest.java import net.kimleo.rec.common.collection.LinkedMultiHashMap; import net.kimleo.rec.common.collection.MultiMap; import org.junit.Test; import java.util.Arrays; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; package net.kimleo.rec.v2; public class LinkedMultiHashMapTest { @Test public void shouldBuildAMapSuccessfully() throws Exception {
MultiMap<Integer, Integer> map = LinkedMultiHashMap.from(Stream.of(1, 1, 1, 2, 2, 2, 3, 3, 3), x -> x);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/LinkedMultiHashMapTest.java
// Path: src/main/java/net/kimleo/rec/common/collection/LinkedMultiHashMap.java // public class LinkedMultiHashMap<K, V> implements MultiMap<K, V> { // // private final Map<K, Collection<V>> map = new LinkedHashMap<>(); // // @Override // public int size() { // int sum = 0; // for (Collection<V> vs : map.values()) { // if (vs != null) { // sum += vs.size(); // } // } // return sum; // } // // @Override // public boolean isEmpty() { // return map.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return map.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // for (Collection<V> vs : map.values()) { // if (vs != null && vs.contains(value)) // return true; // } // return false; // } // // @Override // public Collection<V> get(Object key) { // return map.get(key); // } // // @Override // public Collection<V> put(K key, Collection<V> value) { // if (map.containsKey(key)) { // map.get(key).addAll(value); // } else { // map.put(key, value); // } // return value; // } // // @Override // public Collection<V> remove(Object key) { // return map.remove(key); // } // // @Override // public void putAll(Map<? extends K, ? extends Collection<V>> m) { // for (K key : m.keySet()) { // if (map.containsKey(key)) { // map.get(key).addAll(m.get(key)); // } else { // map.put(key, m.get(key)); // } // } // } // // @Override // public void clear() { // map.clear(); // } // // @Override // public Set<K> keySet() { // return map.keySet(); // } // // @Override // public Collection<Collection<V>> values() { // return map.values(); // } // // @Override // public Set<Entry<K, Collection<V>>> entrySet() { // return map.entrySet(); // } // // @Override // public boolean equals(Object o) { // return o instanceof LinkedMultiHashMap && map.equals(((LinkedMultiHashMap) o).map); // } // // @Override // public int hashCode() { // return map.hashCode(); // } // // @Override // public int keyCount() { // return map.size(); // } // // @Override // public int valueCount() { // return size(); // } // // @Override // public V put1(K key, V value) { // if (map.containsKey(key)) { // map.get(key).add(value); // } else { // Set<V> vs = new HashSet<>(); // vs.add(value); // map.put(key, vs); // } // return value; // } // // public static <V, U> MultiMap<V, U> from(Stream<V> collection, Function<V, U> transform) { // LinkedMultiHashMap<V, U> multiMap = new LinkedMultiHashMap<>(); // collection.forEach(item -> multiMap.put1(item, transform.apply(item))); // // return multiMap; // } // } // // Path: src/main/java/net/kimleo/rec/common/collection/MultiMap.java // public interface MultiMap<K, V> extends Map<K, Collection<V>> { // int keyCount(); // // int valueCount(); // // V put1(K key, V value); // }
import net.kimleo.rec.common.collection.LinkedMultiHashMap; import net.kimleo.rec.common.collection.MultiMap; import org.junit.Test; import java.util.Arrays; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue;
package net.kimleo.rec.v2; public class LinkedMultiHashMapTest { @Test public void shouldBuildAMapSuccessfully() throws Exception {
// Path: src/main/java/net/kimleo/rec/common/collection/LinkedMultiHashMap.java // public class LinkedMultiHashMap<K, V> implements MultiMap<K, V> { // // private final Map<K, Collection<V>> map = new LinkedHashMap<>(); // // @Override // public int size() { // int sum = 0; // for (Collection<V> vs : map.values()) { // if (vs != null) { // sum += vs.size(); // } // } // return sum; // } // // @Override // public boolean isEmpty() { // return map.isEmpty(); // } // // @Override // public boolean containsKey(Object key) { // return map.containsKey(key); // } // // @Override // public boolean containsValue(Object value) { // for (Collection<V> vs : map.values()) { // if (vs != null && vs.contains(value)) // return true; // } // return false; // } // // @Override // public Collection<V> get(Object key) { // return map.get(key); // } // // @Override // public Collection<V> put(K key, Collection<V> value) { // if (map.containsKey(key)) { // map.get(key).addAll(value); // } else { // map.put(key, value); // } // return value; // } // // @Override // public Collection<V> remove(Object key) { // return map.remove(key); // } // // @Override // public void putAll(Map<? extends K, ? extends Collection<V>> m) { // for (K key : m.keySet()) { // if (map.containsKey(key)) { // map.get(key).addAll(m.get(key)); // } else { // map.put(key, m.get(key)); // } // } // } // // @Override // public void clear() { // map.clear(); // } // // @Override // public Set<K> keySet() { // return map.keySet(); // } // // @Override // public Collection<Collection<V>> values() { // return map.values(); // } // // @Override // public Set<Entry<K, Collection<V>>> entrySet() { // return map.entrySet(); // } // // @Override // public boolean equals(Object o) { // return o instanceof LinkedMultiHashMap && map.equals(((LinkedMultiHashMap) o).map); // } // // @Override // public int hashCode() { // return map.hashCode(); // } // // @Override // public int keyCount() { // return map.size(); // } // // @Override // public int valueCount() { // return size(); // } // // @Override // public V put1(K key, V value) { // if (map.containsKey(key)) { // map.get(key).add(value); // } else { // Set<V> vs = new HashSet<>(); // vs.add(value); // map.put(key, vs); // } // return value; // } // // public static <V, U> MultiMap<V, U> from(Stream<V> collection, Function<V, U> transform) { // LinkedMultiHashMap<V, U> multiMap = new LinkedMultiHashMap<>(); // collection.forEach(item -> multiMap.put1(item, transform.apply(item))); // // return multiMap; // } // } // // Path: src/main/java/net/kimleo/rec/common/collection/MultiMap.java // public interface MultiMap<K, V> extends Map<K, Collection<V>> { // int keyCount(); // // int valueCount(); // // V put1(K key, V value); // } // Path: src/test/java/net/kimleo/rec/v2/LinkedMultiHashMapTest.java import net.kimleo.rec.common.collection.LinkedMultiHashMap; import net.kimleo.rec.common.collection.MultiMap; import org.junit.Test; import java.util.Arrays; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertTrue; package net.kimleo.rec.v2; public class LinkedMultiHashMapTest { @Test public void shouldBuildAMapSuccessfully() throws Exception {
MultiMap<Integer, Integer> map = LinkedMultiHashMap.from(Stream.of(1, 1, 1, 2, 2, 2, 3, 3, 3), x -> x);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/ResultSetSourceTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // }
import net.kimleo.rec.common.concept.Mapped; import org.junit.Test; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package net.kimleo.rec.v2.model.impl; public class ResultSetSourceTest { @Test public void shouldPass() throws Exception { ResultSet mockedResultSet = mock(ResultSet.class); when(mockedResultSet.getObject("key")).thenReturn("1").thenReturn("2"); when(mockedResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/ResultSetSourceTest.java import net.kimleo.rec.common.concept.Mapped; import org.junit.Test; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package net.kimleo.rec.v2.model.impl; public class ResultSetSourceTest { @Test public void shouldPass() throws Exception { ResultSet mockedResultSet = mock(ResultSet.class); when(mockedResultSet.getObject("key")).thenReturn("1").thenReturn("2"); when(mockedResultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
List<Mapped<String>> list = new ResultSetSource(mockedResultSet)
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/utils/Records.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
package net.kimleo.rec.v2.utils; public class Records { public static ByteBuffer encode(Mapped<String> record, List<String> keys) { int size = keys.size(); ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); byteBuffer.putInt(size); for (String key : keys) { String field = record.get(key); byteBuffer.putInt(field.getBytes().length); byteBuffer.put(field.getBytes()); } return byteBuffer; } private static int sizeof(Mapped<String> record, List<String> keys) { int size = 4; for (String key : keys) { size += 4; size += record.get(key).getBytes().length; } return size; }
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; package net.kimleo.rec.v2.utils; public class Records { public static ByteBuffer encode(Mapped<String> record, List<String> keys) { int size = keys.size(); ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); byteBuffer.putInt(size); for (String key : keys) { String field = record.get(key); byteBuffer.putInt(field.getBytes().length); byteBuffer.put(field.getBytes()); } return byteBuffer; } private static int sizeof(Mapped<String> record, List<String> keys) { int size = 4; for (String key : keys) { size += 4; size += record.get(key).getBytes().length; } return size; }
public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/utils/Records.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
if (size != expectedSize) return null; ArrayList<String> items = new ArrayList<>(size); for (int i = 0; i < size; i++) { int length = buffer.getInt(); byte[] bytes = new byte[length]; buffer.get(bytes, 0, length); items.add(new String(bytes)); } return new Pair<>(items, buffer.position() - readPos); } public static void dump(File file, int expectSize) { try { long length = file.length(); MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); int readPos = 0; while (readPos < byteBuffer.limit()) { Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); if (result == null) break; readPos += result.second; System.out.println(result.first.stream().collect(Collectors.joining(", "))); } } catch (IOException e) {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; if (size != expectedSize) return null; ArrayList<String> items = new ArrayList<>(size); for (int i = 0; i < size; i++) { int length = buffer.getInt(); byte[] bytes = new byte[length]; buffer.get(bytes, 0, length); items.add(new String(bytes)); } return new Pair<>(items, buffer.position() - readPos); } public static void dump(File file, int expectSize) { try { long length = file.length(); MappedByteBuffer byteBuffer = FileChannel.open(file.toPath(), StandardOpenOption.READ) .map(FileChannel.MapMode.READ_ONLY, 0, (int) length); int readPos = 0; while (readPos < byteBuffer.limit()) { Pair<List<String>, Integer> result = decode(byteBuffer, readPos, expectSize); if (result == null) break; readPos += result.second; System.out.println(result.first.stream().collect(Collectors.joining(", "))); } } catch (IOException e) {
throw new ResourceAccessException("Unable to dump file: [" + file.getName() + "]", e);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSource.java
// Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/execution/RestartableSource.java // public interface RestartableSource<T> extends Source<T> { // // ExecutionContext context(); // // @Override // default void to(Target<T> target) { // try { // stream().forEach(target::put); // } catch (Throwable ex) { // context().persist(ex); // } // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java // public static NativeExecutionContext initialContext() { // return new NativeExecutionContext(0); // }
import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.execution.RestartableSource; import net.kimleo.rec.v2.model.Source; import java.util.stream.Stream; import static net.kimleo.rec.v2.execution.impl.NativeExecutionContext.initialContext;
package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSource<T> implements RestartableSource<T> { private final Source<T> source; private final NativeExecutionContext context; public CountBasedRestartableSource(Source<T> source, NativeExecutionContext context) { this.source = source; this.context = context; } @Override
// Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/execution/RestartableSource.java // public interface RestartableSource<T> extends Source<T> { // // ExecutionContext context(); // // @Override // default void to(Target<T> target) { // try { // stream().forEach(target::put); // } catch (Throwable ex) { // context().persist(ex); // } // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java // public static NativeExecutionContext initialContext() { // return new NativeExecutionContext(0); // } // Path: src/main/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSource.java import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.execution.RestartableSource; import net.kimleo.rec.v2.model.Source; import java.util.stream.Stream; import static net.kimleo.rec.v2.execution.impl.NativeExecutionContext.initialContext; package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSource<T> implements RestartableSource<T> { private final Source<T> source; private final NativeExecutionContext context; public CountBasedRestartableSource(Source<T> source, NativeExecutionContext context) { this.source = source; this.context = context; } @Override
public ExecutionContext context() {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSource.java
// Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/execution/RestartableSource.java // public interface RestartableSource<T> extends Source<T> { // // ExecutionContext context(); // // @Override // default void to(Target<T> target) { // try { // stream().forEach(target::put); // } catch (Throwable ex) { // context().persist(ex); // } // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java // public static NativeExecutionContext initialContext() { // return new NativeExecutionContext(0); // }
import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.execution.RestartableSource; import net.kimleo.rec.v2.model.Source; import java.util.stream.Stream; import static net.kimleo.rec.v2.execution.impl.NativeExecutionContext.initialContext;
package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSource<T> implements RestartableSource<T> { private final Source<T> source; private final NativeExecutionContext context; public CountBasedRestartableSource(Source<T> source, NativeExecutionContext context) { this.source = source; this.context = context; } @Override public ExecutionContext context() { return this.context; } @Override public Source<T> skip(int n) { return source.skip(n); } @Override public Stream<T> stream() { return source.skip(context.state()).stream().map(it -> { context.commit(); return it; }); } public static <T> Source<T> from(Stream<T> stream) {
// Path: src/main/java/net/kimleo/rec/v2/execution/ExecutionContext.java // public interface ExecutionContext { // void commit(); // void persist(Throwable causedBy); // // ExecutionContext restart(); // // boolean isNative(); // boolean isCloud(); // // Context jsContext(); // } // // Path: src/main/java/net/kimleo/rec/v2/execution/RestartableSource.java // public interface RestartableSource<T> extends Source<T> { // // ExecutionContext context(); // // @Override // default void to(Target<T> target) { // try { // stream().forEach(target::put); // } catch (Throwable ex) { // context().persist(ex); // } // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/execution/impl/NativeExecutionContext.java // public static NativeExecutionContext initialContext() { // return new NativeExecutionContext(0); // } // Path: src/main/java/net/kimleo/rec/v2/execution/impl/CountBasedRestartableSource.java import net.kimleo.rec.v2.execution.ExecutionContext; import net.kimleo.rec.v2.execution.RestartableSource; import net.kimleo.rec.v2.model.Source; import java.util.stream.Stream; import static net.kimleo.rec.v2.execution.impl.NativeExecutionContext.initialContext; package net.kimleo.rec.v2.execution.impl; public class CountBasedRestartableSource<T> implements RestartableSource<T> { private final Source<T> source; private final NativeExecutionContext context; public CountBasedRestartableSource(Source<T> source, NativeExecutionContext context) { this.source = source; this.context = context; } @Override public ExecutionContext context() { return this.context; } @Override public Source<T> skip(int n) { return source.skip(n); } @Override public Stream<T> stream() { return source.skip(context.state()).stream().map(it -> { context.commit(); return it; }); } public static <T> Source<T> from(Stream<T> stream) {
return new CountBasedRestartableSource<>(() -> stream, initialContext());
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/BufferedCachingTeeTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package net.kimleo.rec.v2.model.impl; public class BufferedCachingTeeTest { private int sum = 0; @Test public void shouldCachingAsExpected() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()),
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/BufferedCachingTeeTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package net.kimleo.rec.v2.model.impl; public class BufferedCachingTeeTest { private int sum = 0; @Test public void shouldCachingAsExpected() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()),
"question, answer, duration", ParseConfig.DEFAULT);
rec-framework/rec-core
src/test/java/net/kimleo/rec/v2/model/impl/BufferedCachingTeeTest.java
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // }
import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package net.kimleo.rec.v2.model.impl; public class BufferedCachingTeeTest { private int sum = 0; @Test public void shouldCachingAsExpected() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()), "question, answer, duration", ParseConfig.DEFAULT); BufferedCachingTee catching = new BufferedCachingTee(100 * 1024 * 1024); source.tee(catching).to(record -> sum(record.get("question"))); catching.source().to(record -> sum(record.get("answer"))); assertThat(sum, is(1333248)); // 8 * 166656
// Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/sepval/parser/ParseConfig.java // public class ParseConfig { // public final char delimiter; // public final char escape; // // public static final ParseConfig DEFAULT = new ParseConfig(); // public static final ParseConfig BY_PIPE = new ParseConfig('|'); // // public ParseConfig(char delimiter, char escape) { // this.delimiter = delimiter; // this.escape = escape; // } // // public ParseConfig(char delimiter) { // this(delimiter, '"'); // } // // public ParseConfig() { // this(',', '"'); // } // } // Path: src/test/java/net/kimleo/rec/v2/model/impl/BufferedCachingTeeTest.java import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.sepval.parser.ParseConfig; import org.junit.Test; import java.io.File; import java.net.URL; import java.nio.file.Files; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package net.kimleo.rec.v2.model.impl; public class BufferedCachingTeeTest { private int sum = 0; @Test public void shouldCachingAsExpected() throws Exception { URL resource = this.getClass().getClassLoader().getResource("CSVFileSource.csv"); assert resource != null; File file = new File(resource.toURI()); CSVSource source = new CSVSource(Files.newBufferedReader(file.toPath()), "question, answer, duration", ParseConfig.DEFAULT); BufferedCachingTee catching = new BufferedCachingTee(100 * 1024 * 1024); source.tee(catching).to(record -> sum(record.get("question"))); catching.source().to(record -> sum(record.get("answer"))); assertThat(sum, is(1333248)); // 8 * 166656
ItemCounterTee<Mapped<String>> counter = new ItemCounterTee<>(it -> true);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/CollectTee.java
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // }
import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import java.util.Collection;
package net.kimleo.rec.v2.model.impl; public class CollectTee<T> implements Tee<T> { private final Collection<T> collection; public CollectTee(Collection<T> collection) { this.collection = collection; } public Collection<T> collect() { return collection; } @Override public T emit(T record) { collection.add(record); return record; } @Override
// Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/CollectTee.java import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import java.util.Collection; package net.kimleo.rec.v2.model.impl; public class CollectTee<T> implements Tee<T> { private final Collection<T> collection; public CollectTee(Collection<T> collection) { this.collection = collection; } public Collection<T> collect() { return collection; } @Override public T emit(T record) { collection.add(record); return record; } @Override
public Source<T> source() {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode;
package net.kimleo.rec.v2.model.impl; public class BufferedCachingTee implements Tee<Mapped<String>> { private static final Logger LOGGER = LoggerFactory.getLogger(BufferedCachingTee.class); private final Path tempFile; private final ByteBuffer buffer; private List<String> keys; private int writePos; public BufferedCachingTee(int size) { try { tempFile = Files.createTempFile(Paths.get("."),"rec-caching", ".bin"); buffer = ByteBuffer.allocateDirect(size); } catch (IOException e) {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode; package net.kimleo.rec.v2.model.impl; public class BufferedCachingTee implements Tee<Mapped<String>> { private static final Logger LOGGER = LoggerFactory.getLogger(BufferedCachingTee.class); private final Path tempFile; private final ByteBuffer buffer; private List<String> keys; private int writePos; public BufferedCachingTee(int size) { try { tempFile = Files.createTempFile(Paths.get("."),"rec-caching", ".bin"); buffer = ByteBuffer.allocateDirect(size); } catch (IOException e) {
throw new ResourceAccessException("Unable to create new temporary file.", e);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode;
package net.kimleo.rec.v2.model.impl; public class BufferedCachingTee implements Tee<Mapped<String>> { private static final Logger LOGGER = LoggerFactory.getLogger(BufferedCachingTee.class); private final Path tempFile; private final ByteBuffer buffer; private List<String> keys; private int writePos; public BufferedCachingTee(int size) { try { tempFile = Files.createTempFile(Paths.get("."),"rec-caching", ".bin"); buffer = ByteBuffer.allocateDirect(size); } catch (IOException e) { throw new ResourceAccessException("Unable to create new temporary file.", e); } } @Override public Mapped<String> emit(Mapped<String> record) { if (keys == null) keys = record.keys();
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode; package net.kimleo.rec.v2.model.impl; public class BufferedCachingTee implements Tee<Mapped<String>> { private static final Logger LOGGER = LoggerFactory.getLogger(BufferedCachingTee.class); private final Path tempFile; private final ByteBuffer buffer; private List<String> keys; private int writePos; public BufferedCachingTee(int size) { try { tempFile = Files.createTempFile(Paths.get("."),"rec-caching", ".bin"); buffer = ByteBuffer.allocateDirect(size); } catch (IOException e) { throw new ResourceAccessException("Unable to create new temporary file.", e); } } @Override public Mapped<String> emit(Mapped<String> record) { if (keys == null) keys = record.keys();
ByteBuffer bytes = encode(record, keys);
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode;
package net.kimleo.rec.v2.model.impl; public class BufferedCachingTee implements Tee<Mapped<String>> { private static final Logger LOGGER = LoggerFactory.getLogger(BufferedCachingTee.class); private final Path tempFile; private final ByteBuffer buffer; private List<String> keys; private int writePos; public BufferedCachingTee(int size) { try { tempFile = Files.createTempFile(Paths.get("."),"rec-caching", ".bin"); buffer = ByteBuffer.allocateDirect(size); } catch (IOException e) { throw new ResourceAccessException("Unable to create new temporary file.", e); } } @Override public Mapped<String> emit(Mapped<String> record) { if (keys == null) keys = record.keys(); ByteBuffer bytes = encode(record, keys); bytes.position(0); buffer.position(writePos); buffer.put(bytes); writePos = buffer.position(); return record; } @Override
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode; package net.kimleo.rec.v2.model.impl; public class BufferedCachingTee implements Tee<Mapped<String>> { private static final Logger LOGGER = LoggerFactory.getLogger(BufferedCachingTee.class); private final Path tempFile; private final ByteBuffer buffer; private List<String> keys; private int writePos; public BufferedCachingTee(int size) { try { tempFile = Files.createTempFile(Paths.get("."),"rec-caching", ".bin"); buffer = ByteBuffer.allocateDirect(size); } catch (IOException e) { throw new ResourceAccessException("Unable to create new temporary file.", e); } } @Override public Mapped<String> emit(Mapped<String> record) { if (keys == null) keys = record.keys(); ByteBuffer bytes = encode(record, keys); bytes.position(0); buffer.position(writePos); buffer.put(bytes); writePos = buffer.position(); return record; } @Override
public Source<Mapped<String>> source() {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode;
private void persist() { try { int original = buffer.limit(); buffer.limit(writePos).position(0); byte[] bytes = new byte[writePos]; buffer.get(bytes); Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING).write(ByteBuffer.wrap(bytes)); buffer.limit(original); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot access temp file: [%s]", tempFile.getFileName()), e); } } static class BufferedCachingSource implements Source<Mapped<String>> { private final BufferedCachingTee tee; private final ByteBuffer buffer; private int readPos = 0; BufferedCachingSource(BufferedCachingTee tee) { this.tee = tee; this.buffer = tee.buffer; } @Override public Stream<Mapped<String>> stream() {
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode; private void persist() { try { int original = buffer.limit(); buffer.limit(writePos).position(0); byte[] bytes = new byte[writePos]; buffer.get(bytes); Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING).write(ByteBuffer.wrap(bytes)); buffer.limit(original); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot access temp file: [%s]", tempFile.getFileName()), e); } } static class BufferedCachingSource implements Source<Mapped<String>> { private final BufferedCachingTee tee; private final ByteBuffer buffer; private int readPos = 0; BufferedCachingSource(BufferedCachingTee tee) { this.tee = tee; this.buffer = tee.buffer; } @Override public Stream<Mapped<String>> stream() {
return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> {
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode;
try { int original = buffer.limit(); buffer.limit(writePos).position(0); byte[] bytes = new byte[writePos]; buffer.get(bytes); Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING).write(ByteBuffer.wrap(bytes)); buffer.limit(original); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot access temp file: [%s]", tempFile.getFileName()), e); } } static class BufferedCachingSource implements Source<Mapped<String>> { private final BufferedCachingTee tee; private final ByteBuffer buffer; private int readPos = 0; BufferedCachingSource(BufferedCachingTee tee) { this.tee = tee; this.buffer = tee.buffer; } @Override public Stream<Mapped<String>> stream() { return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> { if (readPos >= tee.writePos) return null;
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode; try { int original = buffer.limit(); buffer.limit(writePos).position(0); byte[] bytes = new byte[writePos]; buffer.get(bytes); Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING).write(ByteBuffer.wrap(bytes)); buffer.limit(original); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot access temp file: [%s]", tempFile.getFileName()), e); } } static class BufferedCachingSource implements Source<Mapped<String>> { private final BufferedCachingTee tee; private final ByteBuffer buffer; private int readPos = 0; BufferedCachingSource(BufferedCachingTee tee) { this.tee = tee; this.buffer = tee.buffer; } @Override public Stream<Mapped<String>> stream() { return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> { if (readPos >= tee.writePos) return null;
Pair<List<String>, Integer> pair = decode(buffer, readPos, tee.keys.size());
rec-framework/rec-core
src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // }
import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode;
try { int original = buffer.limit(); buffer.limit(writePos).position(0); byte[] bytes = new byte[writePos]; buffer.get(bytes); Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING).write(ByteBuffer.wrap(bytes)); buffer.limit(original); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot access temp file: [%s]", tempFile.getFileName()), e); } } static class BufferedCachingSource implements Source<Mapped<String>> { private final BufferedCachingTee tee; private final ByteBuffer buffer; private int readPos = 0; BufferedCachingSource(BufferedCachingTee tee) { this.tee = tee; this.buffer = tee.buffer; } @Override public Stream<Mapped<String>> stream() { return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> { if (readPos >= tee.writePos) return null;
// Path: src/main/java/net/kimleo/rec/common/Pair.java // public class Pair<K, V> { // public final K first; // public final V second; // // // public Pair(K first, V second) { // this.first = first; // this.second = second; // } // // public K getFirst() { // return first; // } // // public V getSecond() { // return second; // } // // } // // Path: src/main/java/net/kimleo/rec/common/concept/Mapped.java // public interface Mapped<T> { // T get(String field); // // List<String> keys(); // } // // Path: src/main/java/net/kimleo/rec/common/exception/ResourceAccessException.java // public class ResourceAccessException extends RuntimeException { // public ResourceAccessException(String message, Throwable ex) { // super(message, ex); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Source.java // public interface Source<T> { // Stream<T> stream(); // default Source<T> tee(Tee<T> tee) { // return () -> this.stream().map(tee::emit); // } // // default Source<T> filter(Predicate<T> predicate) { // return () -> this.stream().filter(predicate); // } // // default Source<T> skip(int n) { // return from(stream().skip(n)); // } // // static <T> Source<T> from(Stream<T> records) { // return () -> records; // } // // default void to(Target<T> target) { // target.putAll(this); // } // } // // Path: src/main/java/net/kimleo/rec/v2/model/Tee.java // public interface Tee<T> { // T emit(T record); // // default Source<T> source() { // return Source.from(Stream.empty()); // } // default void to(Target<T> target) { // source().to(target); // } // } // // Path: src/main/java/net/kimleo/rec/v2/stream/adapter/GeneratingSpliteratorAdapter.java // public class GeneratingSpliteratorAdapter<T> extends Spliterators.AbstractSpliterator<T> { // // // private final Supplier<T> supplier; // // public GeneratingSpliteratorAdapter(Supplier<T> supplier) { // super(Long.MAX_VALUE, 0); // this.supplier = supplier; // } // // @Override // public boolean tryAdvance(Consumer<? super T> action) { // T item = supplier.get(); // if (item != null) { // action.accept(item); // return true; // } // // return false; // } // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static Pair<List<String>, Integer> decode(ByteBuffer buffer, int readPos, int expectedSize) { // // buffer.position(readPos); // int size = buffer.getInt(); // if (size != expectedSize) return null; // ArrayList<String> items = new ArrayList<>(size); // // for (int i = 0; i < size; i++) { // int length = buffer.getInt(); // byte[] bytes = new byte[length]; // buffer.get(bytes, 0, length); // items.add(new String(bytes)); // // } // // return new Pair<>(items, buffer.position() - readPos); // } // // Path: src/main/java/net/kimleo/rec/v2/utils/Records.java // public static ByteBuffer encode(Mapped<String> record, List<String> keys) { // int size = keys.size(); // ByteBuffer byteBuffer = ByteBuffer.allocate(sizeof(record, keys)); // // byteBuffer.putInt(size); // for (String key : keys) { // String field = record.get(key); // byteBuffer.putInt(field.getBytes().length); // byteBuffer.put(field.getBytes()); // } // return byteBuffer; // } // Path: src/main/java/net/kimleo/rec/v2/model/impl/BufferedCachingTee.java import net.kimleo.rec.common.Pair; import net.kimleo.rec.common.concept.Mapped; import net.kimleo.rec.common.exception.ResourceAccessException; import net.kimleo.rec.v2.model.Source; import net.kimleo.rec.v2.model.Tee; import net.kimleo.rec.v2.stream.adapter.GeneratingSpliteratorAdapter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static net.kimleo.rec.v2.utils.Records.decode; import static net.kimleo.rec.v2.utils.Records.encode; try { int original = buffer.limit(); buffer.limit(writePos).position(0); byte[] bytes = new byte[writePos]; buffer.get(bytes); Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING).write(ByteBuffer.wrap(bytes)); buffer.limit(original); } catch (IOException e) { throw new ResourceAccessException(String.format("Cannot access temp file: [%s]", tempFile.getFileName()), e); } } static class BufferedCachingSource implements Source<Mapped<String>> { private final BufferedCachingTee tee; private final ByteBuffer buffer; private int readPos = 0; BufferedCachingSource(BufferedCachingTee tee) { this.tee = tee; this.buffer = tee.buffer; } @Override public Stream<Mapped<String>> stream() { return StreamSupport.stream(new GeneratingSpliteratorAdapter<Mapped<String>>(() -> { if (readPos >= tee.writePos) return null;
Pair<List<String>, Integer> pair = decode(buffer, readPos, tee.keys.size());
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/dictionary/LexiconSet.java
// Path: src/main/java/com/worksap/nlp/sudachi/WordId.java // public class WordId { // private WordId() { // } // // /** // * Internal word ids can't be larger than this number // */ // public static final int MAX_WORD_ID = 0x0fffffff; // // /** // * Dictionary ids can't be larger than this number // */ // public static final int MAX_DIC_ID = 0xe; // // public static int makeUnchecked(int dic, int word) { // int dicPart = dic << 28; // return dicPart | word; // } // // /** // * Make combined WordId from dictionary and internal parts. This method does // * bound checking. // * // * @param dic // * dictionary id. 0 is system, 1 and above are user. // * @param word // * word id inside the dictionary. // * @return combined word id. // */ // public static int make(int dic, int word) { // if (word > MAX_WORD_ID) { // throw new IndexOutOfBoundsException("wordId is too large: " + word); // } // if (dic > MAX_DIC_ID) { // throw new IndexOutOfBoundsException("dictionaryId is too large: " + dic); // } // return makeUnchecked(dic, word); // } // // /** // * Extract dictionary number from the combined word id // * // * @param wordId // * combined word id // * @return dictionary number // */ // public static int dic(int wordId) { // return wordId >>> 28; // } // // /** // * Extract internal word id from the combined word id // * // * @param wordId // * combined word id // * @return internal word id // */ // public static int word(int wordId) { // return wordId & MAX_WORD_ID; // } // }
import com.worksap.nlp.sudachi.WordId; import java.util.*;
} @Override public int getWordId(String headword, short posId, String readingForm) { for (int dictId = 1; dictId < lexicons.size(); dictId++) { int wid = lexicons.get(dictId).getWordId(headword, posId, readingForm); if (wid >= 0) { return buildWordId(dictId, wid); } } return lexicons.get(0).getWordId(headword, posId, readingForm); } @Override public short getLeftId(int wordId) { return lexicons.get(getDictionaryId(wordId)).getLeftId(getWordId(wordId)); } @Override public short getRightId(int wordId) { return lexicons.get(getDictionaryId(wordId)).getRightId(getWordId(wordId)); } @Override public short getCost(int wordId) { return lexicons.get(getDictionaryId(wordId)).getCost(getWordId(wordId)); } @Override public WordInfo getWordInfo(int wordId) {
// Path: src/main/java/com/worksap/nlp/sudachi/WordId.java // public class WordId { // private WordId() { // } // // /** // * Internal word ids can't be larger than this number // */ // public static final int MAX_WORD_ID = 0x0fffffff; // // /** // * Dictionary ids can't be larger than this number // */ // public static final int MAX_DIC_ID = 0xe; // // public static int makeUnchecked(int dic, int word) { // int dicPart = dic << 28; // return dicPart | word; // } // // /** // * Make combined WordId from dictionary and internal parts. This method does // * bound checking. // * // * @param dic // * dictionary id. 0 is system, 1 and above are user. // * @param word // * word id inside the dictionary. // * @return combined word id. // */ // public static int make(int dic, int word) { // if (word > MAX_WORD_ID) { // throw new IndexOutOfBoundsException("wordId is too large: " + word); // } // if (dic > MAX_DIC_ID) { // throw new IndexOutOfBoundsException("dictionaryId is too large: " + dic); // } // return makeUnchecked(dic, word); // } // // /** // * Extract dictionary number from the combined word id // * // * @param wordId // * combined word id // * @return dictionary number // */ // public static int dic(int wordId) { // return wordId >>> 28; // } // // /** // * Extract internal word id from the combined word id // * // * @param wordId // * combined word id // * @return internal word id // */ // public static int word(int wordId) { // return wordId & MAX_WORD_ID; // } // } // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/LexiconSet.java import com.worksap.nlp.sudachi.WordId; import java.util.*; } @Override public int getWordId(String headword, short posId, String readingForm) { for (int dictId = 1; dictId < lexicons.size(); dictId++) { int wid = lexicons.get(dictId).getWordId(headword, posId, readingForm); if (wid >= 0) { return buildWordId(dictId, wid); } } return lexicons.get(0).getWordId(headword, posId, readingForm); } @Override public short getLeftId(int wordId) { return lexicons.get(getDictionaryId(wordId)).getLeftId(getWordId(wordId)); } @Override public short getRightId(int wordId) { return lexicons.get(getDictionaryId(wordId)).getRightId(getWordId(wordId)); } @Override public short getCost(int wordId) { return lexicons.get(getDictionaryId(wordId)).getCost(getWordId(wordId)); } @Override public WordInfo getWordInfo(int wordId) {
int dictionaryId = WordId.dic(wordId);
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/ProlongedSoundMarkInputTextPlugin.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // }
import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.List; import com.worksap.nlp.sudachi.dictionary.Grammar;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; /** * A plugin that rewrites the Katakana-Hiragana Prolonged Sound Mark (Chōonpu) * and similar symbols. * * <p> * This plugin combines the continuous sequence of prolonged sound marks to 1 * character. * * <p> * {@link Dictionary} initialize this plugin with {@link Settings}. It can be * referred as {@link Plugin#settings}. * * <p> * The following is an example of settings. * * <pre> * {@code * { * "class" : "com.worksap.nlp.sudachi.ProlongedSoundMarkInputTextPlugin", "prolongedSoundMarks": ["ー", "〜", "〰"], "replacementSymbol": "ー" * } * } * </pre> * * {@code prolongedSoundMarks} is the list of symbols to be combined. * {@code replacementSymbol} is the symbol for replacement, after combining * prolonged sound mark sequences. * * <p> * With above setting example, the plugin rewrites input "エーービ〜〜〜シ〰〰〰〰" to * "エービーシー". */ class ProlongedSoundMarkInputTextPlugin extends InputTextPlugin { private Set<Integer> prolongedSoundMarkSet = new HashSet<>(); private String replacementSymbol; @Override
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // } // Path: src/main/java/com/worksap/nlp/sudachi/ProlongedSoundMarkInputTextPlugin.java import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.List; import com.worksap.nlp.sudachi.dictionary.Grammar; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; /** * A plugin that rewrites the Katakana-Hiragana Prolonged Sound Mark (Chōonpu) * and similar symbols. * * <p> * This plugin combines the continuous sequence of prolonged sound marks to 1 * character. * * <p> * {@link Dictionary} initialize this plugin with {@link Settings}. It can be * referred as {@link Plugin#settings}. * * <p> * The following is an example of settings. * * <pre> * {@code * { * "class" : "com.worksap.nlp.sudachi.ProlongedSoundMarkInputTextPlugin", "prolongedSoundMarks": ["ー", "〜", "〰"], "replacementSymbol": "ー" * } * } * </pre> * * {@code prolongedSoundMarks} is the list of symbols to be combined. * {@code replacementSymbol} is the symbol for replacement, after combining * prolonged sound mark sequences. * * <p> * With above setting example, the plugin rewrites input "エーービ〜〜〜シ〰〰〰〰" to * "エービーシー". */ class ProlongedSoundMarkInputTextPlugin extends InputTextPlugin { private Set<Integer> prolongedSoundMarkSet = new HashSet<>(); private String replacementSymbol; @Override
public void setUp(Grammar Grammar) throws IOException {
WorksApplications/Sudachi
src/test/java/com/worksap/nlp/sudachi/dictionary/DictionaryHeaderPrinterTest.java
// Path: src/test/java/com/worksap/nlp/sudachi/Utils.java // public class Utils { // public static void copyResource(Path folder, String... files) throws IOException { // for (String file : files) { // try { // URL src = Utils.class.getResource(file); // Path dest = Paths.get(src.toURI()).getFileName(); // Files.copy(src.openStream(), folder.resolve(dest)); // } catch (URISyntaxException e) { // throw new IOException(e); // } // } // } // }
import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import com.worksap.nlp.sudachi.TestDictionary; import com.worksap.nlp.sudachi.Utils; import org.junit.Before; import org.junit.Rule;
/* * Copyright (c) 2017-2022 Works Applications Co., 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.worksap.nlp.sudachi.dictionary; public class DictionaryHeaderPrinterTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() throws IOException { TestDictionary.INSTANCE.getSystemDictData().writeData(temporaryFolder.getRoot().toPath().resolve("system.dic")); TestDictionary.INSTANCE.getUserDict1Data().writeData(temporaryFolder.getRoot().toPath().resolve("user.dic"));
// Path: src/test/java/com/worksap/nlp/sudachi/Utils.java // public class Utils { // public static void copyResource(Path folder, String... files) throws IOException { // for (String file : files) { // try { // URL src = Utils.class.getResource(file); // Path dest = Paths.get(src.toURI()).getFileName(); // Files.copy(src.openStream(), folder.resolve(dest)); // } catch (URISyntaxException e) { // throw new IOException(e); // } // } // } // } // Path: src/test/java/com/worksap/nlp/sudachi/dictionary/DictionaryHeaderPrinterTest.java import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.hamcrest.core.StringStartsWith.startsWith; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import com.worksap.nlp.sudachi.TestDictionary; import com.worksap.nlp.sudachi.Utils; import org.junit.Before; import org.junit.Rule; /* * Copyright (c) 2017-2022 Works Applications Co., 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.worksap.nlp.sudachi.dictionary; public class DictionaryHeaderPrinterTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() throws IOException { TestDictionary.INSTANCE.getSystemDictData().writeData(temporaryFolder.getRoot().toPath().resolve("system.dic")); TestDictionary.INSTANCE.getUserDict1Data().writeData(temporaryFolder.getRoot().toPath().resolve("user.dic"));
Utils.copyResource(temporaryFolder.getRoot().toPath(), "/unk.def");
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/dictionary/build/ConnectionMatrix.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Connection.java // public final class Connection { // private final ShortBuffer matrix; // private final int leftSize; // private final int rightSize; // // public Connection(ShortBuffer matrix, int leftSize, int rightSize) { // this.matrix = matrix; // this.leftSize = leftSize; // this.rightSize = rightSize; // } // // private int ix(int left, int right) { // assert left < leftSize; // assert right < rightSize; // return right * leftSize + left; // } // // /** // * // * @param left // * left connection index // * @param right // * right connection index // * @return connection weight in the matrix // */ // public short cost(int left, int right) { // return matrix.get(ix(left, right)); // } // // public int getLeftSize() { // return leftSize; // } // // public int getRightSize() { // return rightSize; // } // // public void setCost(int left, int right, short cost) { // matrix.put(ix(left, right), cost); // } // // /** // * @return a copy of itself with the buffer owned, instead of slice // */ // public Connection ownedCopy() { // ShortBuffer copy = ShortBuffer.allocate(matrix.limit()); // copy.put(matrix); // // return new Connection(copy, leftSize, rightSize); // } // // public void validate(int leftId) { // if (matrix == null) { // // should never happen, but elides compiler checks // throw new NullPointerException("matrix"); // } // // if (leftId >= leftSize) { // // should never happen, but adds a compiler precondition to the inlined method // throw new IllegalArgumentException(String.format("leftId < leftSize: (%d, %d)", leftId, leftSize)); // } // } // }
import com.worksap.nlp.sudachi.dictionary.Connection; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern;
* when IO fails */ public long readEntries(InputStream data) throws IOException { LineNumberReader reader = new LineNumberReader(new InputStreamReader(data, StandardCharsets.UTF_8)); String header = reader.readLine(); if (header == null) { throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber()); } String[] lr = WHITESPACE.split(header, 2); if (lr.length != 2) { throw new IllegalArgumentException("invalid header " + header + ", expected two 16-bit integers"); } try { numLeft = Short.parseShort(lr[0]); numRight = Short.parseShort(lr[1]); } catch (NumberFormatException ignored) { throw new IllegalArgumentException("invalid header " + header + ", expected two 16-bit integers"); } ByteBuffer buffer = ByteBuffer.allocate(2 * numLeft * numRight + 4); buffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer matrix = buffer.asShortBuffer(); matrix.put(numLeft); matrix.put(numRight); matrix = matrix.slice();
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Connection.java // public final class Connection { // private final ShortBuffer matrix; // private final int leftSize; // private final int rightSize; // // public Connection(ShortBuffer matrix, int leftSize, int rightSize) { // this.matrix = matrix; // this.leftSize = leftSize; // this.rightSize = rightSize; // } // // private int ix(int left, int right) { // assert left < leftSize; // assert right < rightSize; // return right * leftSize + left; // } // // /** // * // * @param left // * left connection index // * @param right // * right connection index // * @return connection weight in the matrix // */ // public short cost(int left, int right) { // return matrix.get(ix(left, right)); // } // // public int getLeftSize() { // return leftSize; // } // // public int getRightSize() { // return rightSize; // } // // public void setCost(int left, int right, short cost) { // matrix.put(ix(left, right), cost); // } // // /** // * @return a copy of itself with the buffer owned, instead of slice // */ // public Connection ownedCopy() { // ShortBuffer copy = ShortBuffer.allocate(matrix.limit()); // copy.put(matrix); // // return new Connection(copy, leftSize, rightSize); // } // // public void validate(int leftId) { // if (matrix == null) { // // should never happen, but elides compiler checks // throw new NullPointerException("matrix"); // } // // if (leftId >= leftSize) { // // should never happen, but adds a compiler precondition to the inlined method // throw new IllegalArgumentException(String.format("leftId < leftSize: (%d, %d)", leftId, leftSize)); // } // } // } // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/build/ConnectionMatrix.java import com.worksap.nlp.sudachi.dictionary.Connection; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ShortBuffer; import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; * when IO fails */ public long readEntries(InputStream data) throws IOException { LineNumberReader reader = new LineNumberReader(new InputStreamReader(data, StandardCharsets.UTF_8)); String header = reader.readLine(); if (header == null) { throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber()); } String[] lr = WHITESPACE.split(header, 2); if (lr.length != 2) { throw new IllegalArgumentException("invalid header " + header + ", expected two 16-bit integers"); } try { numLeft = Short.parseShort(lr[0]); numRight = Short.parseShort(lr[1]); } catch (NumberFormatException ignored) { throw new IllegalArgumentException("invalid header " + header + ", expected two 16-bit integers"); } ByteBuffer buffer = ByteBuffer.allocate(2 * numLeft * numRight + 4); buffer.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer matrix = buffer.asShortBuffer(); matrix.put(numLeft); matrix.put(numRight); matrix = matrix.slice();
Connection conn = new Connection(matrix, numLeft, numRight);
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/DefaultInputTextPlugin.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.nio.charset.StandardCharsets; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import com.worksap.nlp.sudachi.dictionary.Grammar;
/* * Copyright (c) 2017-2022 Works Applications Co., 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.worksap.nlp.sudachi; /** * A plugin that rewrites the characters of input texts. * * <p> * This plugin rewites the characters by the user-defined rules, converts them * to lower case by {@link Character#toLowerCase} and normalized by * {@link java.text.Normalizer#normalize} with {@code NFKC}. * * <p> * {@link Dictionary} initialize this plugin with {@link Settings}. It can be * refered as {@link Plugin#settings}. * * <p> * The following is an example of settings. * * <pre> * {@code * { * "class" : "com.worksap.nlp.sudachi.DefaultInputTextPlugin", * "rewriteDef" : "rewrite.def" * } * } * </pre> * * {@code rewriteDef} is the file path of the rules of character rewriting. If * {@code rewirteDef} is not defined, this plugin uses the default rules. * * <p> * The following is an example of rewriting rules. * * <pre> * {@code * # single code point: this character is skipped in character normalization * 髙 * # rewrite rule: <target> <replacement> * A' Ā * } * </pre> */ class DefaultInputTextPlugin extends InputTextPlugin { /** the file path of the rules */ Config.Resource<InputStream> rewriteDef; private Set<Integer> ignoreNormalizeSet = new HashSet<>(); private Map<Character, Integer> keyLengths = new HashMap<>(); private Map<String, String> replaceCharMap = new HashMap<>(); /** * Reads the rewriting rules from the specified file. * * @throws IOException * if the file is not available. */ @Override
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // } // Path: src/main/java/com/worksap/nlp/sudachi/DefaultInputTextPlugin.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.nio.charset.StandardCharsets; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import com.worksap.nlp.sudachi.dictionary.Grammar; /* * Copyright (c) 2017-2022 Works Applications Co., 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.worksap.nlp.sudachi; /** * A plugin that rewrites the characters of input texts. * * <p> * This plugin rewites the characters by the user-defined rules, converts them * to lower case by {@link Character#toLowerCase} and normalized by * {@link java.text.Normalizer#normalize} with {@code NFKC}. * * <p> * {@link Dictionary} initialize this plugin with {@link Settings}. It can be * refered as {@link Plugin#settings}. * * <p> * The following is an example of settings. * * <pre> * {@code * { * "class" : "com.worksap.nlp.sudachi.DefaultInputTextPlugin", * "rewriteDef" : "rewrite.def" * } * } * </pre> * * {@code rewriteDef} is the file path of the rules of character rewriting. If * {@code rewirteDef} is not defined, this plugin uses the default rules. * * <p> * The following is an example of rewriting rules. * * <pre> * {@code * # single code point: this character is skipped in character normalization * 髙 * # rewrite rule: <target> <replacement> * A' Ā * } * </pre> */ class DefaultInputTextPlugin extends InputTextPlugin { /** the file path of the rules */ Config.Resource<InputStream> rewriteDef; private Set<Integer> ignoreNormalizeSet = new HashSet<>(); private Map<Character, Integer> keyLengths = new HashMap<>(); private Map<String, String> replaceCharMap = new HashMap<>(); /** * Reads the rewriting rules from the specified file. * * @throws IOException * if the file is not available. */ @Override
public void setUp(Grammar grammar) throws IOException {
WorksApplications/Sudachi
src/test/java/com/worksap/nlp/sudachi/dictionary/DictionaryPrinterTest.java
// Path: src/test/java/com/worksap/nlp/sudachi/Utils.java // public class Utils { // public static void copyResource(Path folder, String... files) throws IOException { // for (String file : files) { // try { // URL src = Utils.class.getResource(file); // Path dest = Paths.get(src.toURI()).getFileName(); // Files.copy(src.openStream(), folder.resolve(dest)); // } catch (URISyntaxException e) { // throw new IOException(e); // } // } // } // }
import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Path; import com.worksap.nlp.sudachi.TestDictionary; import com.worksap.nlp.sudachi.Utils; import org.junit.Before; import org.junit.Rule;
/* * Copyright (c) 2017-2022 Works Applications Co., 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.worksap.nlp.sudachi.dictionary; public class DictionaryPrinterTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() throws IOException { TestDictionary td = TestDictionary.INSTANCE; Path folder = temporaryFolder.getRoot().toPath(); td.getSystemDictData().writeData(folder.resolve("system.dic")); td.getUserDict1Data().writeData(folder.resolve("user.dic"));
// Path: src/test/java/com/worksap/nlp/sudachi/Utils.java // public class Utils { // public static void copyResource(Path folder, String... files) throws IOException { // for (String file : files) { // try { // URL src = Utils.class.getResource(file); // Path dest = Paths.get(src.toURI()).getFileName(); // Files.copy(src.openStream(), folder.resolve(dest)); // } catch (URISyntaxException e) { // throw new IOException(e); // } // } // } // } // Path: src/test/java/com/worksap/nlp/sudachi/dictionary/DictionaryPrinterTest.java import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Path; import com.worksap.nlp.sudachi.TestDictionary; import com.worksap.nlp.sudachi.Utils; import org.junit.Before; import org.junit.Rule; /* * Copyright (c) 2017-2022 Works Applications Co., 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.worksap.nlp.sudachi.dictionary; public class DictionaryPrinterTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() throws IOException { TestDictionary td = TestDictionary.INSTANCE; Path folder = temporaryFolder.getRoot().toPath(); td.getSystemDictData().writeData(folder.resolve("system.dic")); td.getUserDict1Data().writeData(folder.resolve("user.dic"));
Utils.copyResource(folder, "/unk.def");
WorksApplications/Sudachi
src/test/java/com/worksap/nlp/sudachi/MeCabOovProviderPluginTest.java
// Path: src/main/java/com/worksap/nlp/sudachi/MeCabOovProviderPlugin.java // static class CategoryInfo { // CategoryType type; // boolean isInvoke; // boolean isGroup; // int length; // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // }
import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.worksap.nlp.sudachi.MeCabOovProviderPlugin.CategoryInfo; import com.worksap.nlp.sudachi.dictionary.CategoryType; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Rule;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; public class MeCabOovProviderPluginTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); MeCabOovProviderPlugin plugin; MockInputText inputText; @Before public void setUp() throws IOException { plugin = new MeCabOovProviderPlugin(); MeCabOovProviderPlugin.OOV oov1 = new MeCabOovProviderPlugin.OOV(); oov1.posId = 1; MeCabOovProviderPlugin.OOV oov2 = new MeCabOovProviderPlugin.OOV(); oov2.posId = 2;
// Path: src/main/java/com/worksap/nlp/sudachi/MeCabOovProviderPlugin.java // static class CategoryInfo { // CategoryType type; // boolean isInvoke; // boolean isGroup; // int length; // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // } // Path: src/test/java/com/worksap/nlp/sudachi/MeCabOovProviderPluginTest.java import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.worksap.nlp.sudachi.MeCabOovProviderPlugin.CategoryInfo; import com.worksap.nlp.sudachi.dictionary.CategoryType; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Rule; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; public class MeCabOovProviderPluginTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); MeCabOovProviderPlugin plugin; MockInputText inputText; @Before public void setUp() throws IOException { plugin = new MeCabOovProviderPlugin(); MeCabOovProviderPlugin.OOV oov1 = new MeCabOovProviderPlugin.OOV(); oov1.posId = 1; MeCabOovProviderPlugin.OOV oov2 = new MeCabOovProviderPlugin.OOV(); oov2.posId = 2;
plugin.oovList.put(CategoryType.KANJI, Collections.singletonList(oov1));
WorksApplications/Sudachi
src/test/java/com/worksap/nlp/sudachi/MeCabOovProviderPluginTest.java
// Path: src/main/java/com/worksap/nlp/sudachi/MeCabOovProviderPlugin.java // static class CategoryInfo { // CategoryType type; // boolean isInvoke; // boolean isGroup; // int length; // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // }
import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.worksap.nlp.sudachi.MeCabOovProviderPlugin.CategoryInfo; import com.worksap.nlp.sudachi.dictionary.CategoryType; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Rule;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; public class MeCabOovProviderPluginTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); MeCabOovProviderPlugin plugin; MockInputText inputText; @Before public void setUp() throws IOException { plugin = new MeCabOovProviderPlugin(); MeCabOovProviderPlugin.OOV oov1 = new MeCabOovProviderPlugin.OOV(); oov1.posId = 1; MeCabOovProviderPlugin.OOV oov2 = new MeCabOovProviderPlugin.OOV(); oov2.posId = 2; plugin.oovList.put(CategoryType.KANJI, Collections.singletonList(oov1)); plugin.oovList.put(CategoryType.KANJINUMERIC, Arrays.asList(oov1, oov2)); inputText = new MockInputText("あいうえお"); } @Test public void provideOOV000() {
// Path: src/main/java/com/worksap/nlp/sudachi/MeCabOovProviderPlugin.java // static class CategoryInfo { // CategoryType type; // boolean isInvoke; // boolean isGroup; // int length; // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // } // Path: src/test/java/com/worksap/nlp/sudachi/MeCabOovProviderPluginTest.java import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.worksap.nlp.sudachi.MeCabOovProviderPlugin.CategoryInfo; import com.worksap.nlp.sudachi.dictionary.CategoryType; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Rule; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; public class MeCabOovProviderPluginTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); MeCabOovProviderPlugin plugin; MockInputText inputText; @Before public void setUp() throws IOException { plugin = new MeCabOovProviderPlugin(); MeCabOovProviderPlugin.OOV oov1 = new MeCabOovProviderPlugin.OOV(); oov1.posId = 1; MeCabOovProviderPlugin.OOV oov2 = new MeCabOovProviderPlugin.OOV(); oov2.posId = 2; plugin.oovList.put(CategoryType.KANJI, Collections.singletonList(oov1)); plugin.oovList.put(CategoryType.KANJINUMERIC, Arrays.asList(oov1, oov2)); inputText = new MockInputText("あいうえお"); } @Test public void provideOOV000() {
MeCabOovProviderPlugin.CategoryInfo cinfo = new MeCabOovProviderPlugin.CategoryInfo();
WorksApplications/Sudachi
src/test/java/com/worksap/nlp/sudachi/InhibitConnectionPluginTest.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // }
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import com.worksap.nlp.sudachi.dictionary.Grammar;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; public class InhibitConnectionPluginTest { @Test public void edit() { short left = 0; short right = 0; MockGrammar grammar = new MockGrammar(); InhibitConnectionPlugin plugin = new InhibitConnectionPlugin(); plugin.inhibitedPairs = Collections.singletonList(Arrays.asList((int) left, (int) right)); plugin.edit(grammar);
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // } // Path: src/test/java/com/worksap/nlp/sudachi/InhibitConnectionPluginTest.java import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import com.worksap.nlp.sudachi.dictionary.Grammar; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; public class InhibitConnectionPluginTest { @Test public void edit() { short left = 0; short right = 0; MockGrammar grammar = new MockGrammar(); InhibitConnectionPlugin plugin = new InhibitConnectionPlugin(); plugin.inhibitedPairs = Collections.singletonList(Arrays.asList((int) left, (int) right)); plugin.edit(grammar);
assertThat(grammar.getConnectCost(left, right), is(Grammar.INHIBITED_CONNECTION));
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/dictionary/build/WordLookup.java
// Path: src/main/java/com/worksap/nlp/sudachi/WordId.java // public class WordId { // private WordId() { // } // // /** // * Internal word ids can't be larger than this number // */ // public static final int MAX_WORD_ID = 0x0fffffff; // // /** // * Dictionary ids can't be larger than this number // */ // public static final int MAX_DIC_ID = 0xe; // // public static int makeUnchecked(int dic, int word) { // int dicPart = dic << 28; // return dicPart | word; // } // // /** // * Make combined WordId from dictionary and internal parts. This method does // * bound checking. // * // * @param dic // * dictionary id. 0 is system, 1 and above are user. // * @param word // * word id inside the dictionary. // * @return combined word id. // */ // public static int make(int dic, int word) { // if (word > MAX_WORD_ID) { // throw new IndexOutOfBoundsException("wordId is too large: " + word); // } // if (dic > MAX_DIC_ID) { // throw new IndexOutOfBoundsException("dictionaryId is too large: " + dic); // } // return makeUnchecked(dic, word); // } // // /** // * Extract dictionary number from the combined word id // * // * @param wordId // * combined word id // * @return dictionary number // */ // public static int dic(int wordId) { // return wordId >>> 28; // } // // /** // * Extract internal word id from the combined word id // * // * @param wordId // * combined word id // * @return internal word id // */ // public static int word(int wordId) { // return wordId & MAX_WORD_ID; // } // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Lexicon.java // public interface Lexicon { // // Iterator<int[]> lookup(byte[] text, int offset); // // int getWordId(String headword, short posId, String readingForm); // // /** // * Returns the left-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the left-ID of the morpheme // */ // short getLeftId(int wordId); // // /** // * Returns the right-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the right-ID of the morpheme. // */ // short getRightId(int wordId); // // /** // * Returns the word occurrence cost of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the word occurrence cost // */ // short getCost(int wordId); // // /** // * Returns the informations of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the informations of the morpheme // * @see WordInfo // */ // WordInfo getWordInfo(int wordId); // // /** // * Returns the ID of the dictionary containing the morpheme specified by the // * word ID. // * // * If the morpheme is in the system dictionary, it returns {@code 0}. // * // * @param wordId // * the word ID of the morpheme // * @return the dictionary ID // */ // int getDictionaryId(int wordId); // // /** // * Returns the number of morphemes in the dictionary. // * // * @return the number of morphemes // */ // int size(); // }
import com.worksap.nlp.sudachi.WordId; import com.worksap.nlp.sudachi.dictionary.Lexicon; import java.util.List;
List<CsvLexicon.WordEntry> entries = lexicon.getEntries(); for (int i = 0; i < entries.size(); ++i) { CsvLexicon.WordEntry entry = entries.get(i); if (entry.wordInfo.getSurface().equals(headword) && entry.wordInfo.getPOSId() == posId && entry.wordInfo.getReadingForm().equals(reading)) { return i; } } return -1; } @Override public void validate(int wordId) { if (wordId < 0) { throw new IllegalArgumentException("wordId can't be negative, was " + wordId); } List<CsvLexicon.WordEntry> entries = lexicon.getEntries(); if (wordId >= entries.size()) { throw new IllegalArgumentException(String .format("wordId %d was larger than number of dictionary entries (%d)", wordId, entries.size())); } } @Override public boolean isUser() { return false; } } public static class Prebuilt implements WordIdResolver {
// Path: src/main/java/com/worksap/nlp/sudachi/WordId.java // public class WordId { // private WordId() { // } // // /** // * Internal word ids can't be larger than this number // */ // public static final int MAX_WORD_ID = 0x0fffffff; // // /** // * Dictionary ids can't be larger than this number // */ // public static final int MAX_DIC_ID = 0xe; // // public static int makeUnchecked(int dic, int word) { // int dicPart = dic << 28; // return dicPart | word; // } // // /** // * Make combined WordId from dictionary and internal parts. This method does // * bound checking. // * // * @param dic // * dictionary id. 0 is system, 1 and above are user. // * @param word // * word id inside the dictionary. // * @return combined word id. // */ // public static int make(int dic, int word) { // if (word > MAX_WORD_ID) { // throw new IndexOutOfBoundsException("wordId is too large: " + word); // } // if (dic > MAX_DIC_ID) { // throw new IndexOutOfBoundsException("dictionaryId is too large: " + dic); // } // return makeUnchecked(dic, word); // } // // /** // * Extract dictionary number from the combined word id // * // * @param wordId // * combined word id // * @return dictionary number // */ // public static int dic(int wordId) { // return wordId >>> 28; // } // // /** // * Extract internal word id from the combined word id // * // * @param wordId // * combined word id // * @return internal word id // */ // public static int word(int wordId) { // return wordId & MAX_WORD_ID; // } // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Lexicon.java // public interface Lexicon { // // Iterator<int[]> lookup(byte[] text, int offset); // // int getWordId(String headword, short posId, String readingForm); // // /** // * Returns the left-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the left-ID of the morpheme // */ // short getLeftId(int wordId); // // /** // * Returns the right-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the right-ID of the morpheme. // */ // short getRightId(int wordId); // // /** // * Returns the word occurrence cost of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the word occurrence cost // */ // short getCost(int wordId); // // /** // * Returns the informations of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the informations of the morpheme // * @see WordInfo // */ // WordInfo getWordInfo(int wordId); // // /** // * Returns the ID of the dictionary containing the morpheme specified by the // * word ID. // * // * If the morpheme is in the system dictionary, it returns {@code 0}. // * // * @param wordId // * the word ID of the morpheme // * @return the dictionary ID // */ // int getDictionaryId(int wordId); // // /** // * Returns the number of morphemes in the dictionary. // * // * @return the number of morphemes // */ // int size(); // } // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/build/WordLookup.java import com.worksap.nlp.sudachi.WordId; import com.worksap.nlp.sudachi.dictionary.Lexicon; import java.util.List; List<CsvLexicon.WordEntry> entries = lexicon.getEntries(); for (int i = 0; i < entries.size(); ++i) { CsvLexicon.WordEntry entry = entries.get(i); if (entry.wordInfo.getSurface().equals(headword) && entry.wordInfo.getPOSId() == posId && entry.wordInfo.getReadingForm().equals(reading)) { return i; } } return -1; } @Override public void validate(int wordId) { if (wordId < 0) { throw new IllegalArgumentException("wordId can't be negative, was " + wordId); } List<CsvLexicon.WordEntry> entries = lexicon.getEntries(); if (wordId >= entries.size()) { throw new IllegalArgumentException(String .format("wordId %d was larger than number of dictionary entries (%d)", wordId, entries.size())); } } @Override public boolean isUser() { return false; } } public static class Prebuilt implements WordIdResolver {
private final Lexicon lexicon;
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/dictionary/build/WordLookup.java
// Path: src/main/java/com/worksap/nlp/sudachi/WordId.java // public class WordId { // private WordId() { // } // // /** // * Internal word ids can't be larger than this number // */ // public static final int MAX_WORD_ID = 0x0fffffff; // // /** // * Dictionary ids can't be larger than this number // */ // public static final int MAX_DIC_ID = 0xe; // // public static int makeUnchecked(int dic, int word) { // int dicPart = dic << 28; // return dicPart | word; // } // // /** // * Make combined WordId from dictionary and internal parts. This method does // * bound checking. // * // * @param dic // * dictionary id. 0 is system, 1 and above are user. // * @param word // * word id inside the dictionary. // * @return combined word id. // */ // public static int make(int dic, int word) { // if (word > MAX_WORD_ID) { // throw new IndexOutOfBoundsException("wordId is too large: " + word); // } // if (dic > MAX_DIC_ID) { // throw new IndexOutOfBoundsException("dictionaryId is too large: " + dic); // } // return makeUnchecked(dic, word); // } // // /** // * Extract dictionary number from the combined word id // * // * @param wordId // * combined word id // * @return dictionary number // */ // public static int dic(int wordId) { // return wordId >>> 28; // } // // /** // * Extract internal word id from the combined word id // * // * @param wordId // * combined word id // * @return internal word id // */ // public static int word(int wordId) { // return wordId & MAX_WORD_ID; // } // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Lexicon.java // public interface Lexicon { // // Iterator<int[]> lookup(byte[] text, int offset); // // int getWordId(String headword, short posId, String readingForm); // // /** // * Returns the left-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the left-ID of the morpheme // */ // short getLeftId(int wordId); // // /** // * Returns the right-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the right-ID of the morpheme. // */ // short getRightId(int wordId); // // /** // * Returns the word occurrence cost of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the word occurrence cost // */ // short getCost(int wordId); // // /** // * Returns the informations of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the informations of the morpheme // * @see WordInfo // */ // WordInfo getWordInfo(int wordId); // // /** // * Returns the ID of the dictionary containing the morpheme specified by the // * word ID. // * // * If the morpheme is in the system dictionary, it returns {@code 0}. // * // * @param wordId // * the word ID of the morpheme // * @return the dictionary ID // */ // int getDictionaryId(int wordId); // // /** // * Returns the number of morphemes in the dictionary. // * // * @return the number of morphemes // */ // int size(); // }
import com.worksap.nlp.sudachi.WordId; import com.worksap.nlp.sudachi.dictionary.Lexicon; import java.util.List;
} List<CsvLexicon.WordEntry> entries = lexicon.getEntries(); if (wordId >= entries.size()) { throw new IllegalArgumentException(String .format("wordId %d was larger than number of dictionary entries (%d)", wordId, entries.size())); } } @Override public boolean isUser() { return false; } } public static class Prebuilt implements WordIdResolver { private final Lexicon lexicon; private final int prebuiltSize; public Prebuilt(Lexicon lexicon) { this.lexicon = lexicon; this.prebuiltSize = lexicon.size(); } @Override public int lookup(String headword, short posId, String reading) { return lexicon.getWordId(headword, posId, reading); } @Override public void validate(int wordId) {
// Path: src/main/java/com/worksap/nlp/sudachi/WordId.java // public class WordId { // private WordId() { // } // // /** // * Internal word ids can't be larger than this number // */ // public static final int MAX_WORD_ID = 0x0fffffff; // // /** // * Dictionary ids can't be larger than this number // */ // public static final int MAX_DIC_ID = 0xe; // // public static int makeUnchecked(int dic, int word) { // int dicPart = dic << 28; // return dicPart | word; // } // // /** // * Make combined WordId from dictionary and internal parts. This method does // * bound checking. // * // * @param dic // * dictionary id. 0 is system, 1 and above are user. // * @param word // * word id inside the dictionary. // * @return combined word id. // */ // public static int make(int dic, int word) { // if (word > MAX_WORD_ID) { // throw new IndexOutOfBoundsException("wordId is too large: " + word); // } // if (dic > MAX_DIC_ID) { // throw new IndexOutOfBoundsException("dictionaryId is too large: " + dic); // } // return makeUnchecked(dic, word); // } // // /** // * Extract dictionary number from the combined word id // * // * @param wordId // * combined word id // * @return dictionary number // */ // public static int dic(int wordId) { // return wordId >>> 28; // } // // /** // * Extract internal word id from the combined word id // * // * @param wordId // * combined word id // * @return internal word id // */ // public static int word(int wordId) { // return wordId & MAX_WORD_ID; // } // } // // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Lexicon.java // public interface Lexicon { // // Iterator<int[]> lookup(byte[] text, int offset); // // int getWordId(String headword, short posId, String readingForm); // // /** // * Returns the left-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the left-ID of the morpheme // */ // short getLeftId(int wordId); // // /** // * Returns the right-ID of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the right-ID of the morpheme. // */ // short getRightId(int wordId); // // /** // * Returns the word occurrence cost of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the word occurrence cost // */ // short getCost(int wordId); // // /** // * Returns the informations of the morpheme specified by the word ID. // * // * <p> // * when the word ID is out of range, the behavior is undefined. // * // * @param wordId // * the word ID of the morpheme // * @return the informations of the morpheme // * @see WordInfo // */ // WordInfo getWordInfo(int wordId); // // /** // * Returns the ID of the dictionary containing the morpheme specified by the // * word ID. // * // * If the morpheme is in the system dictionary, it returns {@code 0}. // * // * @param wordId // * the word ID of the morpheme // * @return the dictionary ID // */ // int getDictionaryId(int wordId); // // /** // * Returns the number of morphemes in the dictionary. // * // * @return the number of morphemes // */ // int size(); // } // Path: src/main/java/com/worksap/nlp/sudachi/dictionary/build/WordLookup.java import com.worksap.nlp.sudachi.WordId; import com.worksap.nlp.sudachi.dictionary.Lexicon; import java.util.List; } List<CsvLexicon.WordEntry> entries = lexicon.getEntries(); if (wordId >= entries.size()) { throw new IllegalArgumentException(String .format("wordId %d was larger than number of dictionary entries (%d)", wordId, entries.size())); } } @Override public boolean isUser() { return false; } } public static class Prebuilt implements WordIdResolver { private final Lexicon lexicon; private final int prebuiltSize; public Prebuilt(Lexicon lexicon) { this.lexicon = lexicon; this.prebuiltSize = lexicon.size(); } @Override public int lookup(String headword, short posId, String reading) { return lexicon.getWordId(headword, posId, reading); } @Override public void validate(int wordId) {
int word = WordId.word(wordId);
WorksApplications/Sudachi
src/test/java/com/worksap/nlp/sudachi/MockInputText.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // }
import java.util.EnumSet; import java.util.Set; import com.worksap.nlp.sudachi.dictionary.CategoryType;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; class MockInputText implements InputText { String text;
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // } // Path: src/test/java/com/worksap/nlp/sudachi/MockInputText.java import java.util.EnumSet; import java.util.Set; import com.worksap.nlp.sudachi.dictionary.CategoryType; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; class MockInputText implements InputText { String text;
EnumSet<CategoryType>[] types;
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/InhibitConnectionPlugin.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // }
import java.util.List; import com.worksap.nlp.sudachi.dictionary.Grammar;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; /** * A Plugin for inhibiting the connections. * * <p> * {@link Dictionary} initialize this plugin with {@link Settings}. It can be * referred as {@link Plugin#settings}. * * <p> * The following is an example of settings. * * <pre> * {@code * { * "class" : "com.worksap.nlp.sudachi.InhibitConnectionPlugin", * "inhibitedPair" : [ [ 0, 233 ], [435, 332] ] * } * } * </pre> * * {@code inhibitPair} is a list of lists of two numbers. At each pair, the * first number is right-ID of the left node and the second is left-ID of the * right node in a connection. */ class InhibitConnectionPlugin extends EditConnectionCostPlugin { List<List<Integer>> inhibitedPairs; @Override
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/Grammar.java // public interface Grammar { // // /** // * Returns the number of types of part-of-speech. // * // * The IDs of part-of-speech are within the range of 0 to // * {@code getPartOfSpeechSize() - 1}. // * // * @return the number of types of part-of-speech // */ // public int getPartOfSpeechSize(); // // /** // * Returns the array of strings of part-of-speech name. // * // * The name is divided into layers. // * // * @param posId // * the ID of the part-of-speech // * @return the list of strings of part-of-speech name // * @throws IndexOutOfBoundsException // * if {@code posId} is out of the range // */ // public POS getPartOfSpeechString(short posId); // // /** // * Returns the the ID corresponding to the part-of-speech name. // * // * <p> // * If there is not such the part-of-speech name, -1 is returned. // * // * @param pos // * the list of string of part-of-speech name // * @return the ID corresponding to the part-of-speech name, or -1 without // * corresponding one. // */ // public short getPartOfSpeechId(List<String> pos); // // /** // * Returns the cost of the specified connection. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @return the cost of the connection // */ // public short getConnectCost(short left, short right); // // /** // * Set the connection costs. // * // * <p> // * When the Id is out of the range, the behavior is undefined. // * // * @param left // * the right-ID of the left node // * @param right // * the left-ID of the right node // * @param cost // * the cost of the connection // */ // public void setConnectCost(short left, short right, short cost); // // /** // * Returns the parameter of the beginning of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the beginning of sentence // */ // public short[] getBOSParameter(); // // /** // * Returns the parameter of the end of sentence. // * // * <p> // * The following are the parameters. // * // * <pre> // * {@code { left-ID, rightID, cost } } // * </pre> // * // * @return the parameter of the end of sentence // */ // public short[] getEOSParameter(); // // public CharacterCategory getCharacterCategory(); // // public void setCharacterCategory(CharacterCategory charCategory); // // /** the cost of inhibited connections */ // public static final short INHIBITED_CONNECTION = Short.MAX_VALUE; // // default Connection getConnection() { // throw new UnsupportedOperationException(); // } // } // Path: src/main/java/com/worksap/nlp/sudachi/InhibitConnectionPlugin.java import java.util.List; import com.worksap.nlp.sudachi.dictionary.Grammar; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; /** * A Plugin for inhibiting the connections. * * <p> * {@link Dictionary} initialize this plugin with {@link Settings}. It can be * referred as {@link Plugin#settings}. * * <p> * The following is an example of settings. * * <pre> * {@code * { * "class" : "com.worksap.nlp.sudachi.InhibitConnectionPlugin", * "inhibitedPair" : [ [ 0, 233 ], [435, 332] ] * } * } * </pre> * * {@code inhibitPair} is a list of lists of two numbers. At each pair, the * first number is right-ID of the left node and the second is left-ID of the * right node in a connection. */ class InhibitConnectionPlugin extends EditConnectionCostPlugin { List<List<Integer>> inhibitedPairs; @Override
public void setUp(Grammar grammar) {
WorksApplications/Sudachi
src/main/java/com/worksap/nlp/sudachi/InputText.java
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // }
import java.util.Set; import com.worksap.nlp.sudachi.dictionary.CategoryType;
/* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; /** * An immutable sequence of characters. This class has the original input text * and the modified text each character of which is mapped to the original one. * In the methods of this class the index is not one of characters or code * points. The meaning of the index is implementation dependent, but users do * not have to worry about it. */ public interface InputText { /** * Returns the modified text. This text is used in the tokenizing. * * @return the modified text */ public String getText(); /** * Returns the original input text before all of the replacements in * {@link InputTextBuilder#replace}. * * @return the original input text. */ public String getOriginalText(); /** * Returns the substring of the modified text. The substring begins at the * specified {@code begin} and extends to the character at index * {@code end - 1}. * * @param begin * the beginning index * @param end * the ending index * @return the new string * @throws IndexOutOfBoundsException * if {@code begin} or {@code end} are negative, greater than the * length of the sequence, or {@code begin} is greater than * {@code end} */ public String getSubstring(int begin, int end); /** * Returns the structure of substring. The substring begins at the specified * {@code begin} and extends to the character at index {@code end - 1}. * * @param begin * the beginning index * @param end * the ending index * @return the new string * @throws IndexOutOfBoundsException * if {@code begin} or {@code end} are negative, greater than the * length of the sequence, or {@code begin} is greater than * {@code end} */ public InputText slice(int begin, int end); /** * Returns the index of the original text mapped to the character at the * specified {@code index} in the modified text. * * @param index * the index of the modified text * @return the index of original text * @throws IndexOutOfBoundsException * if {@code index} are negative, greater than the length of the * sequence */ public int getOriginalIndex(int index); /** * Returns the set of category types of the character at the specified * {@code index} in the modified text. * * @param index * the index of the modified text * @return the set of the character category types * @throws IndexOutOfBoundsException * if {@code index} are negative, greater than the length of the * sequence */
// Path: src/main/java/com/worksap/nlp/sudachi/dictionary/CategoryType.java // public enum CategoryType { // /** The fall back category. */ // DEFAULT(1), // /** White spaces. */ // SPACE(1 << 1), // /** CJKV ideographic characters. */ // KANJI(1 << 2), // /** Symbols. */ // SYMBOL(1 << 3), // /** Numerical characters. */ // NUMERIC(1 << 4), // /** Latin alphabets. */ // ALPHA(1 << 5), // /** Hiragana characters. */ // HIRAGANA(1 << 6), // /** Katakana characters. */ // KATAKANA(1 << 7), // /** Kanji numeric characters. */ // KANJINUMERIC(1 << 8), // /** Greek alphabets. */ // GREEK(1 << 9), // /** Cyrillic alphabets. */ // CYRILLIC(1 << 10), // /** User defined category. */ // USER1(1 << 11), // /** User defined category. */ // USER2(1 << 12), // /** User defined category. */ // USER3(1 << 13), // /** User defined category. */ // USER4(1 << 14), // /** Characters that cannot be the beginning of word */ // NOOOVBOW(1 << 15); // // private final int id; // // private CategoryType(int id) { // this.id = id; // } // // /** // * Returns the integer ID number of the category. // * // * @return the ID number of the category // */ // public int getId() { // return id; // } // // /** // * Returns the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // * // * @param id // * the ID number of category // * @return the category to which the specified ID is mapped, or {@code null} if // * there is no associated category. // */ // public static CategoryType getType(int id) { // for (CategoryType type : CategoryType.values()) { // if (type.getId() == id) { // return type; // } // } // return null; // } // } // Path: src/main/java/com/worksap/nlp/sudachi/InputText.java import java.util.Set; import com.worksap.nlp.sudachi.dictionary.CategoryType; /* * Copyright (c) 2021 Works Applications Co., 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.worksap.nlp.sudachi; /** * An immutable sequence of characters. This class has the original input text * and the modified text each character of which is mapped to the original one. * In the methods of this class the index is not one of characters or code * points. The meaning of the index is implementation dependent, but users do * not have to worry about it. */ public interface InputText { /** * Returns the modified text. This text is used in the tokenizing. * * @return the modified text */ public String getText(); /** * Returns the original input text before all of the replacements in * {@link InputTextBuilder#replace}. * * @return the original input text. */ public String getOriginalText(); /** * Returns the substring of the modified text. The substring begins at the * specified {@code begin} and extends to the character at index * {@code end - 1}. * * @param begin * the beginning index * @param end * the ending index * @return the new string * @throws IndexOutOfBoundsException * if {@code begin} or {@code end} are negative, greater than the * length of the sequence, or {@code begin} is greater than * {@code end} */ public String getSubstring(int begin, int end); /** * Returns the structure of substring. The substring begins at the specified * {@code begin} and extends to the character at index {@code end - 1}. * * @param begin * the beginning index * @param end * the ending index * @return the new string * @throws IndexOutOfBoundsException * if {@code begin} or {@code end} are negative, greater than the * length of the sequence, or {@code begin} is greater than * {@code end} */ public InputText slice(int begin, int end); /** * Returns the index of the original text mapped to the character at the * specified {@code index} in the modified text. * * @param index * the index of the modified text * @return the index of original text * @throws IndexOutOfBoundsException * if {@code index} are negative, greater than the length of the * sequence */ public int getOriginalIndex(int index); /** * Returns the set of category types of the character at the specified * {@code index} in the modified text. * * @param index * the index of the modified text * @return the set of the character category types * @throws IndexOutOfBoundsException * if {@code index} are negative, greater than the length of the * sequence */
public Set<CategoryType> getCharCategoryTypes(int index);
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Results/ResultsPanel.java
// Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisListener.java // public interface AnalysisListener { // // public void analysisStarted(SequenceFile file); // public void analysisUpdated(SequenceFile file, int sequencesProcessed, int percentComplete); // public void analysisComplete(SequenceFile file, QCModule [] results); // public void analysisExceptionReceived(SequenceFile file, Exception e); // } // // Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // }
import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import uk.ac.bbsrc.babraham.FastQC.Analysis.AnalysisListener; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel;
/** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Results; public class ResultsPanel extends JPanel implements ListSelectionListener, AnalysisListener{ private static final ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/error.png")); private static final ImageIcon WARNING_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/warning.png")); private static final ImageIcon OK_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/tick.png"));
// Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisListener.java // public interface AnalysisListener { // // public void analysisStarted(SequenceFile file); // public void analysisUpdated(SequenceFile file, int sequencesProcessed, int percentComplete); // public void analysisComplete(SequenceFile file, QCModule [] results); // public void analysisExceptionReceived(SequenceFile file, Exception e); // } // // Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // Path: uk/ac/bbsrc/babraham/FastQC/Results/ResultsPanel.java import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import uk.ac.bbsrc.babraham.FastQC.Analysis.AnalysisListener; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; /** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Results; public class ResultsPanel extends JPanel implements ListSelectionListener, AnalysisListener{ private static final ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/error.png")); private static final ImageIcon WARNING_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/warning.png")); private static final ImageIcon OK_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/tick.png"));
private QCModule [] modules;
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Results/ResultsPanel.java
// Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisListener.java // public interface AnalysisListener { // // public void analysisStarted(SequenceFile file); // public void analysisUpdated(SequenceFile file, int sequencesProcessed, int percentComplete); // public void analysisComplete(SequenceFile file, QCModule [] results); // public void analysisExceptionReceived(SequenceFile file, Exception e); // } // // Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // }
import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import uk.ac.bbsrc.babraham.FastQC.Analysis.AnalysisListener; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel;
/** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Results; public class ResultsPanel extends JPanel implements ListSelectionListener, AnalysisListener{ private static final ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/error.png")); private static final ImageIcon WARNING_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/warning.png")); private static final ImageIcon OK_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/tick.png")); private QCModule [] modules; private JList moduleList; private JPanel [] panels; private JPanel currentPanel = null; private JLabel progressLabel;
// Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisListener.java // public interface AnalysisListener { // // public void analysisStarted(SequenceFile file); // public void analysisUpdated(SequenceFile file, int sequencesProcessed, int percentComplete); // public void analysisComplete(SequenceFile file, QCModule [] results); // public void analysisExceptionReceived(SequenceFile file, Exception e); // } // // Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // Path: uk/ac/bbsrc/babraham/FastQC/Results/ResultsPanel.java import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import uk.ac.bbsrc.babraham.FastQC.Analysis.AnalysisListener; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; /** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Results; public class ResultsPanel extends JPanel implements ListSelectionListener, AnalysisListener{ private static final ImageIcon ERROR_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/error.png")); private static final ImageIcon WARNING_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/warning.png")); private static final ImageIcon OK_ICON = new ImageIcon(ClassLoader.getSystemResource("uk/ac/bbsrc/babraham/FastQC/Resources/tick.png")); private QCModule [] modules; private JList moduleList; private JPanel [] panels; private JPanel currentPanel = null; private JLabel progressLabel;
private SequenceFile sequenceFile;
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisQueue.java
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // }
import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.util.LinkedList; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule;
} Thread t = new Thread(this); t.start(); } public void addToQueue (AnalysisRunner runner) { queue.add(runner); } public void run() { while (true) { // System.err.println("Status available="+availableSlots+" used="+usedSlots+" queue="+queue.size()); if (availableSlots > usedSlots && queue.size() > 0) { ++usedSlots; AnalysisRunner currentRun = queue.getFirst(); queue.removeFirst(); currentRun.addAnalysisListener(this); Thread t = new Thread(currentRun); t.start(); } try { Thread.sleep(500); } catch (InterruptedException e) {} } }
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisQueue.java import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.util.LinkedList; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; } Thread t = new Thread(this); t.start(); } public void addToQueue (AnalysisRunner runner) { queue.add(runner); } public void run() { while (true) { // System.err.println("Status available="+availableSlots+" used="+usedSlots+" queue="+queue.size()); if (availableSlots > usedSlots && queue.size() > 0) { ++usedSlots; AnalysisRunner currentRun = queue.getFirst(); queue.removeFirst(); currentRun.addAnalysisListener(this); Thread t = new Thread(currentRun); t.start(); } try { Thread.sleep(500); } catch (InterruptedException e) {} } }
public void analysisComplete(SequenceFile file, QCModule[] results) {
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisQueue.java
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // }
import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.util.LinkedList; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule;
} Thread t = new Thread(this); t.start(); } public void addToQueue (AnalysisRunner runner) { queue.add(runner); } public void run() { while (true) { // System.err.println("Status available="+availableSlots+" used="+usedSlots+" queue="+queue.size()); if (availableSlots > usedSlots && queue.size() > 0) { ++usedSlots; AnalysisRunner currentRun = queue.getFirst(); queue.removeFirst(); currentRun.addAnalysisListener(this); Thread t = new Thread(currentRun); t.start(); } try { Thread.sleep(500); } catch (InterruptedException e) {} } }
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisQueue.java import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import java.util.LinkedList; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; } Thread t = new Thread(this); t.start(); } public void addToQueue (AnalysisRunner runner) { queue.add(runner); } public void run() { while (true) { // System.err.println("Status available="+availableSlots+" used="+usedSlots+" queue="+queue.size()); if (availableSlots > usedSlots && queue.size() > 0) { ++usedSlots; AnalysisRunner currentRun = queue.getFirst(); queue.removeFirst(); currentRun.addAnalysisListener(this); Thread t = new Thread(currentRun); t.start(); } try { Thread.sleep(500); } catch (InterruptedException e) {} } }
public void analysisComplete(SequenceFile file, QCModule[] results) {
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/FastQCMenuBar.java
// Path: uk/ac/bbsrc/babraham/FastQC/Dialogs/AboutDialog.java // public class AboutDialog extends JDialog { // // /** // * Instantiates a new about dialog. // * // * @param a The SeqMonk application. // */ // public AboutDialog (FastQCApplication a) { // super(a); // setTitle("About FastQC..."); // Container cont = getContentPane(); // cont.setLayout(new BorderLayout()); // // add(new FastQCTitlePanel(),BorderLayout.CENTER); // // JPanel buttonPanel = new JPanel(); // // JButton closeButton = new JButton("Close"); // getRootPane().setDefaultButton(closeButton); // closeButton.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent arg0) { // setVisible(false); // dispose(); // } // }); // buttonPanel.add(closeButton); // // cont.add(buttonPanel,BorderLayout.SOUTH); // // setSize(650,200); // setLocationRelativeTo(a); // setResizable(false); // setVisible(true); // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Help/HelpDialog.java // public class HelpDialog extends JDialog implements TreeSelectionListener { // // /** The tree. */ // private JTree tree; // // /** The current page. */ // private HelpPageDisplay currentPage = null; // // /** The main split. */ // private JSplitPane mainSplit; // // // /** // * Instantiates a new help dialog. // * // * @param parent the parent // * @param startingLocation the starting location // */ // public HelpDialog (JFrame parent, File startingLocation) { // super(parent,"Help Contents"); // // HelpIndexRoot root = new HelpIndexRoot(startingLocation); // // mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // setContentPane(mainSplit); // // tree = new JTree(new DefaultTreeModel(root)); // // JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // leftSplit.setTopComponent(new JScrollPane(tree)); // leftSplit.setBottomComponent(new HelpSearchPanel(root,this)); // // mainSplit.setLeftComponent(leftSplit); // currentPage = new HelpPageDisplay(null); // mainSplit.setRightComponent(currentPage); // // tree.addTreeSelectionListener(this); // // // setSize(800,500); // setLocationRelativeTo(parent); // setVisible(true); // // leftSplit.setDividerLocation(0.7); // mainSplit.setDividerLocation(0.3); // findStartingPage(); // } // // /** // * Find starting page. // */ // private void findStartingPage () { // DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)tree.getModel().getRoot(); // // DisplayPage((HelpPage)currentNode.getFirstLeaf()); // } // // /** // * Display page. // * // * @param page the page // */ // public void DisplayPage(HelpPage page) { // if (currentPage != null) { // int d = mainSplit.getDividerLocation(); // mainSplit.remove(currentPage); // currentPage = new HelpPageDisplay(page); // mainSplit.setRightComponent(currentPage); // mainSplit.setDividerLocation(d); // } // } // // /* (non-Javadoc) // * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) // */ // public void valueChanged(TreeSelectionEvent tse) { // // if (tse.getNewLeadSelectionPath() == null) return; // // Object o = tse.getNewLeadSelectionPath().getLastPathComponent(); // if (o instanceof HelpPage && ((HelpPage)o).isLeaf()) { // DisplayPage((HelpPage)o); // } // } // // }
import uk.ac.bbsrc.babraham.FastQC.Dialogs.AboutDialog; import uk.ac.bbsrc.babraham.FastQC.Help.HelpDialog; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke;
helpAbout.setMnemonic(KeyEvent.VK_A); helpAbout.setActionCommand("about"); helpAbout.addActionListener(this); helpMenu.add(helpAbout); add(helpMenu); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("exit")) { System.exit(0); } else if (command.equals("open")) { application.openFile(); } else if (command.equals("save")) { application.saveReport(); } else if (command.equals("close")) { application.close(); } else if (command.equals("close_all")) { application.closeAll(); } else if (command.equals("help_contents")) {
// Path: uk/ac/bbsrc/babraham/FastQC/Dialogs/AboutDialog.java // public class AboutDialog extends JDialog { // // /** // * Instantiates a new about dialog. // * // * @param a The SeqMonk application. // */ // public AboutDialog (FastQCApplication a) { // super(a); // setTitle("About FastQC..."); // Container cont = getContentPane(); // cont.setLayout(new BorderLayout()); // // add(new FastQCTitlePanel(),BorderLayout.CENTER); // // JPanel buttonPanel = new JPanel(); // // JButton closeButton = new JButton("Close"); // getRootPane().setDefaultButton(closeButton); // closeButton.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent arg0) { // setVisible(false); // dispose(); // } // }); // buttonPanel.add(closeButton); // // cont.add(buttonPanel,BorderLayout.SOUTH); // // setSize(650,200); // setLocationRelativeTo(a); // setResizable(false); // setVisible(true); // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Help/HelpDialog.java // public class HelpDialog extends JDialog implements TreeSelectionListener { // // /** The tree. */ // private JTree tree; // // /** The current page. */ // private HelpPageDisplay currentPage = null; // // /** The main split. */ // private JSplitPane mainSplit; // // // /** // * Instantiates a new help dialog. // * // * @param parent the parent // * @param startingLocation the starting location // */ // public HelpDialog (JFrame parent, File startingLocation) { // super(parent,"Help Contents"); // // HelpIndexRoot root = new HelpIndexRoot(startingLocation); // // mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // setContentPane(mainSplit); // // tree = new JTree(new DefaultTreeModel(root)); // // JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // leftSplit.setTopComponent(new JScrollPane(tree)); // leftSplit.setBottomComponent(new HelpSearchPanel(root,this)); // // mainSplit.setLeftComponent(leftSplit); // currentPage = new HelpPageDisplay(null); // mainSplit.setRightComponent(currentPage); // // tree.addTreeSelectionListener(this); // // // setSize(800,500); // setLocationRelativeTo(parent); // setVisible(true); // // leftSplit.setDividerLocation(0.7); // mainSplit.setDividerLocation(0.3); // findStartingPage(); // } // // /** // * Find starting page. // */ // private void findStartingPage () { // DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)tree.getModel().getRoot(); // // DisplayPage((HelpPage)currentNode.getFirstLeaf()); // } // // /** // * Display page. // * // * @param page the page // */ // public void DisplayPage(HelpPage page) { // if (currentPage != null) { // int d = mainSplit.getDividerLocation(); // mainSplit.remove(currentPage); // currentPage = new HelpPageDisplay(page); // mainSplit.setRightComponent(currentPage); // mainSplit.setDividerLocation(d); // } // } // // /* (non-Javadoc) // * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) // */ // public void valueChanged(TreeSelectionEvent tse) { // // if (tse.getNewLeadSelectionPath() == null) return; // // Object o = tse.getNewLeadSelectionPath().getLastPathComponent(); // if (o instanceof HelpPage && ((HelpPage)o).isLeaf()) { // DisplayPage((HelpPage)o); // } // } // // } // Path: uk/ac/bbsrc/babraham/FastQC/FastQCMenuBar.java import uk.ac.bbsrc.babraham.FastQC.Dialogs.AboutDialog; import uk.ac.bbsrc.babraham.FastQC.Help.HelpDialog; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; helpAbout.setMnemonic(KeyEvent.VK_A); helpAbout.setActionCommand("about"); helpAbout.addActionListener(this); helpMenu.add(helpAbout); add(helpMenu); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("exit")) { System.exit(0); } else if (command.equals("open")) { application.openFile(); } else if (command.equals("save")) { application.saveReport(); } else if (command.equals("close")) { application.close(); } else if (command.equals("close_all")) { application.closeAll(); } else if (command.equals("help_contents")) {
new HelpDialog(application,new File(ClassLoader.getSystemResource("Help").getFile().replaceAll("%20", " ")));
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/FastQCMenuBar.java
// Path: uk/ac/bbsrc/babraham/FastQC/Dialogs/AboutDialog.java // public class AboutDialog extends JDialog { // // /** // * Instantiates a new about dialog. // * // * @param a The SeqMonk application. // */ // public AboutDialog (FastQCApplication a) { // super(a); // setTitle("About FastQC..."); // Container cont = getContentPane(); // cont.setLayout(new BorderLayout()); // // add(new FastQCTitlePanel(),BorderLayout.CENTER); // // JPanel buttonPanel = new JPanel(); // // JButton closeButton = new JButton("Close"); // getRootPane().setDefaultButton(closeButton); // closeButton.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent arg0) { // setVisible(false); // dispose(); // } // }); // buttonPanel.add(closeButton); // // cont.add(buttonPanel,BorderLayout.SOUTH); // // setSize(650,200); // setLocationRelativeTo(a); // setResizable(false); // setVisible(true); // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Help/HelpDialog.java // public class HelpDialog extends JDialog implements TreeSelectionListener { // // /** The tree. */ // private JTree tree; // // /** The current page. */ // private HelpPageDisplay currentPage = null; // // /** The main split. */ // private JSplitPane mainSplit; // // // /** // * Instantiates a new help dialog. // * // * @param parent the parent // * @param startingLocation the starting location // */ // public HelpDialog (JFrame parent, File startingLocation) { // super(parent,"Help Contents"); // // HelpIndexRoot root = new HelpIndexRoot(startingLocation); // // mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // setContentPane(mainSplit); // // tree = new JTree(new DefaultTreeModel(root)); // // JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // leftSplit.setTopComponent(new JScrollPane(tree)); // leftSplit.setBottomComponent(new HelpSearchPanel(root,this)); // // mainSplit.setLeftComponent(leftSplit); // currentPage = new HelpPageDisplay(null); // mainSplit.setRightComponent(currentPage); // // tree.addTreeSelectionListener(this); // // // setSize(800,500); // setLocationRelativeTo(parent); // setVisible(true); // // leftSplit.setDividerLocation(0.7); // mainSplit.setDividerLocation(0.3); // findStartingPage(); // } // // /** // * Find starting page. // */ // private void findStartingPage () { // DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)tree.getModel().getRoot(); // // DisplayPage((HelpPage)currentNode.getFirstLeaf()); // } // // /** // * Display page. // * // * @param page the page // */ // public void DisplayPage(HelpPage page) { // if (currentPage != null) { // int d = mainSplit.getDividerLocation(); // mainSplit.remove(currentPage); // currentPage = new HelpPageDisplay(page); // mainSplit.setRightComponent(currentPage); // mainSplit.setDividerLocation(d); // } // } // // /* (non-Javadoc) // * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) // */ // public void valueChanged(TreeSelectionEvent tse) { // // if (tse.getNewLeadSelectionPath() == null) return; // // Object o = tse.getNewLeadSelectionPath().getLastPathComponent(); // if (o instanceof HelpPage && ((HelpPage)o).isLeaf()) { // DisplayPage((HelpPage)o); // } // } // // }
import uk.ac.bbsrc.babraham.FastQC.Dialogs.AboutDialog; import uk.ac.bbsrc.babraham.FastQC.Help.HelpDialog; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke;
helpMenu.add(helpAbout); add(helpMenu); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("exit")) { System.exit(0); } else if (command.equals("open")) { application.openFile(); } else if (command.equals("save")) { application.saveReport(); } else if (command.equals("close")) { application.close(); } else if (command.equals("close_all")) { application.closeAll(); } else if (command.equals("help_contents")) { new HelpDialog(application,new File(ClassLoader.getSystemResource("Help").getFile().replaceAll("%20", " "))); } else if (command.equals("about")) {
// Path: uk/ac/bbsrc/babraham/FastQC/Dialogs/AboutDialog.java // public class AboutDialog extends JDialog { // // /** // * Instantiates a new about dialog. // * // * @param a The SeqMonk application. // */ // public AboutDialog (FastQCApplication a) { // super(a); // setTitle("About FastQC..."); // Container cont = getContentPane(); // cont.setLayout(new BorderLayout()); // // add(new FastQCTitlePanel(),BorderLayout.CENTER); // // JPanel buttonPanel = new JPanel(); // // JButton closeButton = new JButton("Close"); // getRootPane().setDefaultButton(closeButton); // closeButton.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent arg0) { // setVisible(false); // dispose(); // } // }); // buttonPanel.add(closeButton); // // cont.add(buttonPanel,BorderLayout.SOUTH); // // setSize(650,200); // setLocationRelativeTo(a); // setResizable(false); // setVisible(true); // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Help/HelpDialog.java // public class HelpDialog extends JDialog implements TreeSelectionListener { // // /** The tree. */ // private JTree tree; // // /** The current page. */ // private HelpPageDisplay currentPage = null; // // /** The main split. */ // private JSplitPane mainSplit; // // // /** // * Instantiates a new help dialog. // * // * @param parent the parent // * @param startingLocation the starting location // */ // public HelpDialog (JFrame parent, File startingLocation) { // super(parent,"Help Contents"); // // HelpIndexRoot root = new HelpIndexRoot(startingLocation); // // mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // setContentPane(mainSplit); // // tree = new JTree(new DefaultTreeModel(root)); // // JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // leftSplit.setTopComponent(new JScrollPane(tree)); // leftSplit.setBottomComponent(new HelpSearchPanel(root,this)); // // mainSplit.setLeftComponent(leftSplit); // currentPage = new HelpPageDisplay(null); // mainSplit.setRightComponent(currentPage); // // tree.addTreeSelectionListener(this); // // // setSize(800,500); // setLocationRelativeTo(parent); // setVisible(true); // // leftSplit.setDividerLocation(0.7); // mainSplit.setDividerLocation(0.3); // findStartingPage(); // } // // /** // * Find starting page. // */ // private void findStartingPage () { // DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)tree.getModel().getRoot(); // // DisplayPage((HelpPage)currentNode.getFirstLeaf()); // } // // /** // * Display page. // * // * @param page the page // */ // public void DisplayPage(HelpPage page) { // if (currentPage != null) { // int d = mainSplit.getDividerLocation(); // mainSplit.remove(currentPage); // currentPage = new HelpPageDisplay(page); // mainSplit.setRightComponent(currentPage); // mainSplit.setDividerLocation(d); // } // } // // /* (non-Javadoc) // * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent) // */ // public void valueChanged(TreeSelectionEvent tse) { // // if (tse.getNewLeadSelectionPath() == null) return; // // Object o = tse.getNewLeadSelectionPath().getLastPathComponent(); // if (o instanceof HelpPage && ((HelpPage)o).isLeaf()) { // DisplayPage((HelpPage)o); // } // } // // } // Path: uk/ac/bbsrc/babraham/FastQC/FastQCMenuBar.java import uk.ac.bbsrc.babraham.FastQC.Dialogs.AboutDialog; import uk.ac.bbsrc.babraham.FastQC.Help.HelpDialog; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.KeyStroke; helpMenu.add(helpAbout); add(helpMenu); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("exit")) { System.exit(0); } else if (command.equals("open")) { application.openFile(); } else if (command.equals("save")) { application.saveReport(); } else if (command.equals("close")) { application.close(); } else if (command.equals("close_all")) { application.closeAll(); } else if (command.equals("help_contents")) { new HelpDialog(application,new File(ClassLoader.getSystemResource("Help").getFile().replaceAll("%20", " "))); } else if (command.equals("about")) {
new AboutDialog(application);
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisRunner.java
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/Sequence.java // public class Sequence { // // private String sequence; // private String quality; // private String id; // private SequenceFile file; // private String colorspace; // private boolean isFiltered; // // public Sequence (SequenceFile file,String sequence, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence.toUpperCase(); // this.quality = quality; // this.colorspace = null; // this.isFiltered = false; // } // // public Sequence (SequenceFile file,String sequence, String colorspace, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence; // this.quality = quality; // this.colorspace = colorspace; // } // // public void setIsFiltered (boolean isFiltered) { // this.isFiltered = isFiltered; // } // // public boolean isFiltered () { // return isFiltered; // } // // public SequenceFile file () { // return file; // } // // public String getSequence () { // return sequence; // } // // public String getColorspace () { // return colorspace; // } // // public String getQualityString () { // return quality; // } // // public String getID () { // return id; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFormatException.java // public class SequenceFormatException extends Exception { // // public SequenceFormatException (String message) { // super(message); // } // // }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.Sequence; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFormatException;
/** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Analysis; public class AnalysisRunner implements Runnable { private SequenceFile file;
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/Sequence.java // public class Sequence { // // private String sequence; // private String quality; // private String id; // private SequenceFile file; // private String colorspace; // private boolean isFiltered; // // public Sequence (SequenceFile file,String sequence, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence.toUpperCase(); // this.quality = quality; // this.colorspace = null; // this.isFiltered = false; // } // // public Sequence (SequenceFile file,String sequence, String colorspace, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence; // this.quality = quality; // this.colorspace = colorspace; // } // // public void setIsFiltered (boolean isFiltered) { // this.isFiltered = isFiltered; // } // // public boolean isFiltered () { // return isFiltered; // } // // public SequenceFile file () { // return file; // } // // public String getSequence () { // return sequence; // } // // public String getColorspace () { // return colorspace; // } // // public String getQualityString () { // return quality; // } // // public String getID () { // return id; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFormatException.java // public class SequenceFormatException extends Exception { // // public SequenceFormatException (String message) { // super(message); // } // // } // Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisRunner.java import java.util.ArrayList; import java.util.Iterator; import java.util.List; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.Sequence; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFormatException; /** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Analysis; public class AnalysisRunner implements Runnable { private SequenceFile file;
private QCModule [] modules;
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisRunner.java
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/Sequence.java // public class Sequence { // // private String sequence; // private String quality; // private String id; // private SequenceFile file; // private String colorspace; // private boolean isFiltered; // // public Sequence (SequenceFile file,String sequence, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence.toUpperCase(); // this.quality = quality; // this.colorspace = null; // this.isFiltered = false; // } // // public Sequence (SequenceFile file,String sequence, String colorspace, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence; // this.quality = quality; // this.colorspace = colorspace; // } // // public void setIsFiltered (boolean isFiltered) { // this.isFiltered = isFiltered; // } // // public boolean isFiltered () { // return isFiltered; // } // // public SequenceFile file () { // return file; // } // // public String getSequence () { // return sequence; // } // // public String getColorspace () { // return colorspace; // } // // public String getQualityString () { // return quality; // } // // public String getID () { // return id; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFormatException.java // public class SequenceFormatException extends Exception { // // public SequenceFormatException (String message) { // super(message); // } // // }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.Sequence; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFormatException;
listeners.add(l); } } public void removeAnalysisListener (AnalysisListener l) { if (l != null && listeners.contains(l)) { listeners.remove(l); } } public void startAnalysis (QCModule [] modules) { this.modules = modules; for (int i=0;i<modules.length;i++) { modules[i].reset(); } AnalysisQueue.getInstance().addToQueue(this); } public void run() { Iterator<AnalysisListener> i = listeners.iterator(); while (i.hasNext()) { i.next().analysisStarted(file); } int seqCount = 0; while (file.hasNext()) { ++seqCount;
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/Sequence.java // public class Sequence { // // private String sequence; // private String quality; // private String id; // private SequenceFile file; // private String colorspace; // private boolean isFiltered; // // public Sequence (SequenceFile file,String sequence, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence.toUpperCase(); // this.quality = quality; // this.colorspace = null; // this.isFiltered = false; // } // // public Sequence (SequenceFile file,String sequence, String colorspace, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence; // this.quality = quality; // this.colorspace = colorspace; // } // // public void setIsFiltered (boolean isFiltered) { // this.isFiltered = isFiltered; // } // // public boolean isFiltered () { // return isFiltered; // } // // public SequenceFile file () { // return file; // } // // public String getSequence () { // return sequence; // } // // public String getColorspace () { // return colorspace; // } // // public String getQualityString () { // return quality; // } // // public String getID () { // return id; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFormatException.java // public class SequenceFormatException extends Exception { // // public SequenceFormatException (String message) { // super(message); // } // // } // Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisRunner.java import java.util.ArrayList; import java.util.Iterator; import java.util.List; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.Sequence; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFormatException; listeners.add(l); } } public void removeAnalysisListener (AnalysisListener l) { if (l != null && listeners.contains(l)) { listeners.remove(l); } } public void startAnalysis (QCModule [] modules) { this.modules = modules; for (int i=0;i<modules.length;i++) { modules[i].reset(); } AnalysisQueue.getInstance().addToQueue(this); } public void run() { Iterator<AnalysisListener> i = listeners.iterator(); while (i.hasNext()) { i.next().analysisStarted(file); } int seqCount = 0; while (file.hasNext()) { ++seqCount;
Sequence seq;
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisRunner.java
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/Sequence.java // public class Sequence { // // private String sequence; // private String quality; // private String id; // private SequenceFile file; // private String colorspace; // private boolean isFiltered; // // public Sequence (SequenceFile file,String sequence, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence.toUpperCase(); // this.quality = quality; // this.colorspace = null; // this.isFiltered = false; // } // // public Sequence (SequenceFile file,String sequence, String colorspace, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence; // this.quality = quality; // this.colorspace = colorspace; // } // // public void setIsFiltered (boolean isFiltered) { // this.isFiltered = isFiltered; // } // // public boolean isFiltered () { // return isFiltered; // } // // public SequenceFile file () { // return file; // } // // public String getSequence () { // return sequence; // } // // public String getColorspace () { // return colorspace; // } // // public String getQualityString () { // return quality; // } // // public String getID () { // return id; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFormatException.java // public class SequenceFormatException extends Exception { // // public SequenceFormatException (String message) { // super(message); // } // // }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.Sequence; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFormatException;
public void removeAnalysisListener (AnalysisListener l) { if (l != null && listeners.contains(l)) { listeners.remove(l); } } public void startAnalysis (QCModule [] modules) { this.modules = modules; for (int i=0;i<modules.length;i++) { modules[i].reset(); } AnalysisQueue.getInstance().addToQueue(this); } public void run() { Iterator<AnalysisListener> i = listeners.iterator(); while (i.hasNext()) { i.next().analysisStarted(file); } int seqCount = 0; while (file.hasNext()) { ++seqCount; Sequence seq; try { seq = file.next(); }
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/Sequence.java // public class Sequence { // // private String sequence; // private String quality; // private String id; // private SequenceFile file; // private String colorspace; // private boolean isFiltered; // // public Sequence (SequenceFile file,String sequence, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence.toUpperCase(); // this.quality = quality; // this.colorspace = null; // this.isFiltered = false; // } // // public Sequence (SequenceFile file,String sequence, String colorspace, String quality, String id) { // this.id = id; // this.file = file; // this.sequence = sequence; // this.quality = quality; // this.colorspace = colorspace; // } // // public void setIsFiltered (boolean isFiltered) { // this.isFiltered = isFiltered; // } // // public boolean isFiltered () { // return isFiltered; // } // // public SequenceFile file () { // return file; // } // // public String getSequence () { // return sequence; // } // // public String getColorspace () { // return colorspace; // } // // public String getQualityString () { // return quality; // } // // public String getID () { // return id; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFormatException.java // public class SequenceFormatException extends Exception { // // public SequenceFormatException (String message) { // super(message); // } // // } // Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisRunner.java import java.util.ArrayList; import java.util.Iterator; import java.util.List; import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.Sequence; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFormatException; public void removeAnalysisListener (AnalysisListener l) { if (l != null && listeners.contains(l)) { listeners.remove(l); } } public void startAnalysis (QCModule [] modules) { this.modules = modules; for (int i=0;i<modules.length;i++) { modules[i].reset(); } AnalysisQueue.getInstance().addToQueue(this); } public void run() { Iterator<AnalysisListener> i = listeners.iterator(); while (i.hasNext()) { i.next().analysisStarted(file); } int seqCount = 0; while (file.hasNext()) { ++seqCount; Sequence seq; try { seq = file.next(); }
catch (SequenceFormatException e) {
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFileGroup.java
// Path: uk/ac/bbsrc/babraham/FastQC/Utilities/CasavaBasename.java // public class CasavaBasename { // // /** // * This method finds the core name from a CASAVA 1.8 fastq file. It strips off the // * part which indicates that this file is one of a set and returns the base name with // * this part removed. // * // * If the filename does not conform to standard CASAVA naming then a NameFormatException // * is thrown. // * // * @param originalName // * @return // * @throws NameFormatException // */ // // public static String getCasavaBasename (String originalName) throws NameFormatException { // // // Find the base name. We need to remove the 123 numbers from // // files of the form: // // // // anyold_text_123.fastq.gz // // // // where the base name will be // // // // anyoldtext.fastq.gz // // // The file must end with .fastq.gz // // // if (originalName.endsWith(".fastq.gz")) { // // // They must have an _ 13 chars before the end // if (originalName.substring(originalName.length()-13, originalName.length()-12).equals("_")) { // // // They must have numbers for the 3 positions before .fastq // try { // Integer.parseInt(originalName.substring(originalName.length()-12, originalName.length()-9)); // // // If we get here then everything is OK to use the base name from this file // String baseName = originalName.substring(0,originalName.length()-13)+".fastq.gz"; // return baseName; // } // catch (NumberFormatException nfe) {} // } // } // // throw new NameFormatException(); // } // // public static File [][] getCasavaGroups (File [] files) { // Hashtable<String, Vector<File>> fileBases = new Hashtable<String, Vector<File>>(); // // for (int f=0;f<files.length;f++) { // // // If a file forms part of a CASAVA group then put it into that // // group. // try { // String baseName = CasavaBasename.getCasavaBasename(files[f].getName()); // if (! fileBases.containsKey(baseName)) { // fileBases.put(baseName,new Vector<File>()); // } // fileBases.get(baseName).add(files[f]); // // } // // // If the file name doesn't appear to be part of a CASAVA group // // then add it as a singleton // catch (NameFormatException nfe) { // // System.err.println("File '"+files[f].getName()+"' didn't look like part of a CASAVA group"); // Vector<File> newVector = new Vector<File>(); // newVector.add(files[f]); // fileBases.put(files[f].getName(), newVector); // } // // } // // String [] baseNames = fileBases.keySet().toArray(new String [0]); // // File [][] fileGroups = new File[baseNames.length][]; // // for (int i=0;i<baseNames.length;i++) { // fileGroups[i] = fileBases.get(baseNames[i]).toArray(new File[0]); // } // // return fileGroups; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Utilities/NameFormatException.java // public class NameFormatException extends Exception { // // }
import java.io.File; import uk.ac.bbsrc.babraham.FastQC.Utilities.CasavaBasename; import uk.ac.bbsrc.babraham.FastQC.Utilities.NameFormatException;
package uk.ac.bbsrc.babraham.FastQC.Sequence; public class SequenceFileGroup implements SequenceFile { private SequenceFile [] files; private File groupFile; private int currentIndex = 0; public SequenceFileGroup (SequenceFile [] files) { this.files = files; try {
// Path: uk/ac/bbsrc/babraham/FastQC/Utilities/CasavaBasename.java // public class CasavaBasename { // // /** // * This method finds the core name from a CASAVA 1.8 fastq file. It strips off the // * part which indicates that this file is one of a set and returns the base name with // * this part removed. // * // * If the filename does not conform to standard CASAVA naming then a NameFormatException // * is thrown. // * // * @param originalName // * @return // * @throws NameFormatException // */ // // public static String getCasavaBasename (String originalName) throws NameFormatException { // // // Find the base name. We need to remove the 123 numbers from // // files of the form: // // // // anyold_text_123.fastq.gz // // // // where the base name will be // // // // anyoldtext.fastq.gz // // // The file must end with .fastq.gz // // // if (originalName.endsWith(".fastq.gz")) { // // // They must have an _ 13 chars before the end // if (originalName.substring(originalName.length()-13, originalName.length()-12).equals("_")) { // // // They must have numbers for the 3 positions before .fastq // try { // Integer.parseInt(originalName.substring(originalName.length()-12, originalName.length()-9)); // // // If we get here then everything is OK to use the base name from this file // String baseName = originalName.substring(0,originalName.length()-13)+".fastq.gz"; // return baseName; // } // catch (NumberFormatException nfe) {} // } // } // // throw new NameFormatException(); // } // // public static File [][] getCasavaGroups (File [] files) { // Hashtable<String, Vector<File>> fileBases = new Hashtable<String, Vector<File>>(); // // for (int f=0;f<files.length;f++) { // // // If a file forms part of a CASAVA group then put it into that // // group. // try { // String baseName = CasavaBasename.getCasavaBasename(files[f].getName()); // if (! fileBases.containsKey(baseName)) { // fileBases.put(baseName,new Vector<File>()); // } // fileBases.get(baseName).add(files[f]); // // } // // // If the file name doesn't appear to be part of a CASAVA group // // then add it as a singleton // catch (NameFormatException nfe) { // // System.err.println("File '"+files[f].getName()+"' didn't look like part of a CASAVA group"); // Vector<File> newVector = new Vector<File>(); // newVector.add(files[f]); // fileBases.put(files[f].getName(), newVector); // } // // } // // String [] baseNames = fileBases.keySet().toArray(new String [0]); // // File [][] fileGroups = new File[baseNames.length][]; // // for (int i=0;i<baseNames.length;i++) { // fileGroups[i] = fileBases.get(baseNames[i]).toArray(new File[0]); // } // // return fileGroups; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Utilities/NameFormatException.java // public class NameFormatException extends Exception { // // } // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFileGroup.java import java.io.File; import uk.ac.bbsrc.babraham.FastQC.Utilities.CasavaBasename; import uk.ac.bbsrc.babraham.FastQC.Utilities.NameFormatException; package uk.ac.bbsrc.babraham.FastQC.Sequence; public class SequenceFileGroup implements SequenceFile { private SequenceFile [] files; private File groupFile; private int currentIndex = 0; public SequenceFileGroup (SequenceFile [] files) { this.files = files; try {
String baseName = CasavaBasename.getCasavaBasename(files[0].name());
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFileGroup.java
// Path: uk/ac/bbsrc/babraham/FastQC/Utilities/CasavaBasename.java // public class CasavaBasename { // // /** // * This method finds the core name from a CASAVA 1.8 fastq file. It strips off the // * part which indicates that this file is one of a set and returns the base name with // * this part removed. // * // * If the filename does not conform to standard CASAVA naming then a NameFormatException // * is thrown. // * // * @param originalName // * @return // * @throws NameFormatException // */ // // public static String getCasavaBasename (String originalName) throws NameFormatException { // // // Find the base name. We need to remove the 123 numbers from // // files of the form: // // // // anyold_text_123.fastq.gz // // // // where the base name will be // // // // anyoldtext.fastq.gz // // // The file must end with .fastq.gz // // // if (originalName.endsWith(".fastq.gz")) { // // // They must have an _ 13 chars before the end // if (originalName.substring(originalName.length()-13, originalName.length()-12).equals("_")) { // // // They must have numbers for the 3 positions before .fastq // try { // Integer.parseInt(originalName.substring(originalName.length()-12, originalName.length()-9)); // // // If we get here then everything is OK to use the base name from this file // String baseName = originalName.substring(0,originalName.length()-13)+".fastq.gz"; // return baseName; // } // catch (NumberFormatException nfe) {} // } // } // // throw new NameFormatException(); // } // // public static File [][] getCasavaGroups (File [] files) { // Hashtable<String, Vector<File>> fileBases = new Hashtable<String, Vector<File>>(); // // for (int f=0;f<files.length;f++) { // // // If a file forms part of a CASAVA group then put it into that // // group. // try { // String baseName = CasavaBasename.getCasavaBasename(files[f].getName()); // if (! fileBases.containsKey(baseName)) { // fileBases.put(baseName,new Vector<File>()); // } // fileBases.get(baseName).add(files[f]); // // } // // // If the file name doesn't appear to be part of a CASAVA group // // then add it as a singleton // catch (NameFormatException nfe) { // // System.err.println("File '"+files[f].getName()+"' didn't look like part of a CASAVA group"); // Vector<File> newVector = new Vector<File>(); // newVector.add(files[f]); // fileBases.put(files[f].getName(), newVector); // } // // } // // String [] baseNames = fileBases.keySet().toArray(new String [0]); // // File [][] fileGroups = new File[baseNames.length][]; // // for (int i=0;i<baseNames.length;i++) { // fileGroups[i] = fileBases.get(baseNames[i]).toArray(new File[0]); // } // // return fileGroups; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Utilities/NameFormatException.java // public class NameFormatException extends Exception { // // }
import java.io.File; import uk.ac.bbsrc.babraham.FastQC.Utilities.CasavaBasename; import uk.ac.bbsrc.babraham.FastQC.Utilities.NameFormatException;
package uk.ac.bbsrc.babraham.FastQC.Sequence; public class SequenceFileGroup implements SequenceFile { private SequenceFile [] files; private File groupFile; private int currentIndex = 0; public SequenceFileGroup (SequenceFile [] files) { this.files = files; try { String baseName = CasavaBasename.getCasavaBasename(files[0].name()); if (files[0].getFile().getParent() == null) { groupFile = new File(baseName); } else { groupFile = new File(files[0].getFile().getParent()+"/"+baseName); } }
// Path: uk/ac/bbsrc/babraham/FastQC/Utilities/CasavaBasename.java // public class CasavaBasename { // // /** // * This method finds the core name from a CASAVA 1.8 fastq file. It strips off the // * part which indicates that this file is one of a set and returns the base name with // * this part removed. // * // * If the filename does not conform to standard CASAVA naming then a NameFormatException // * is thrown. // * // * @param originalName // * @return // * @throws NameFormatException // */ // // public static String getCasavaBasename (String originalName) throws NameFormatException { // // // Find the base name. We need to remove the 123 numbers from // // files of the form: // // // // anyold_text_123.fastq.gz // // // // where the base name will be // // // // anyoldtext.fastq.gz // // // The file must end with .fastq.gz // // // if (originalName.endsWith(".fastq.gz")) { // // // They must have an _ 13 chars before the end // if (originalName.substring(originalName.length()-13, originalName.length()-12).equals("_")) { // // // They must have numbers for the 3 positions before .fastq // try { // Integer.parseInt(originalName.substring(originalName.length()-12, originalName.length()-9)); // // // If we get here then everything is OK to use the base name from this file // String baseName = originalName.substring(0,originalName.length()-13)+".fastq.gz"; // return baseName; // } // catch (NumberFormatException nfe) {} // } // } // // throw new NameFormatException(); // } // // public static File [][] getCasavaGroups (File [] files) { // Hashtable<String, Vector<File>> fileBases = new Hashtable<String, Vector<File>>(); // // for (int f=0;f<files.length;f++) { // // // If a file forms part of a CASAVA group then put it into that // // group. // try { // String baseName = CasavaBasename.getCasavaBasename(files[f].getName()); // if (! fileBases.containsKey(baseName)) { // fileBases.put(baseName,new Vector<File>()); // } // fileBases.get(baseName).add(files[f]); // // } // // // If the file name doesn't appear to be part of a CASAVA group // // then add it as a singleton // catch (NameFormatException nfe) { // // System.err.println("File '"+files[f].getName()+"' didn't look like part of a CASAVA group"); // Vector<File> newVector = new Vector<File>(); // newVector.add(files[f]); // fileBases.put(files[f].getName(), newVector); // } // // } // // String [] baseNames = fileBases.keySet().toArray(new String [0]); // // File [][] fileGroups = new File[baseNames.length][]; // // for (int i=0;i<baseNames.length;i++) { // fileGroups[i] = fileBases.get(baseNames[i]).toArray(new File[0]); // } // // return fileGroups; // } // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Utilities/NameFormatException.java // public class NameFormatException extends Exception { // // } // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFileGroup.java import java.io.File; import uk.ac.bbsrc.babraham.FastQC.Utilities.CasavaBasename; import uk.ac.bbsrc.babraham.FastQC.Utilities.NameFormatException; package uk.ac.bbsrc.babraham.FastQC.Sequence; public class SequenceFileGroup implements SequenceFile { private SequenceFile [] files; private File groupFile; private int currentIndex = 0; public SequenceFileGroup (SequenceFile [] files) { this.files = files; try { String baseName = CasavaBasename.getCasavaBasename(files[0].name()); if (files[0].getFile().getParent() == null) { groupFile = new File(baseName); } else { groupFile = new File(files[0].getFile().getParent()+"/"+baseName); } }
catch (NameFormatException nfe) {
csf-ngs/fastqc
uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisListener.java
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // }
import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile;
/** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Analysis; public interface AnalysisListener { public void analysisStarted(SequenceFile file); public void analysisUpdated(SequenceFile file, int sequencesProcessed, int percentComplete);
// Path: uk/ac/bbsrc/babraham/FastQC/Modules/QCModule.java // public interface QCModule { // // public void processSequence(Sequence sequence); // // public JPanel getResultsPanel(); // // public String name (); // // public String description (); // // public void reset (); // // public boolean raisesError(); // // public boolean raisesWarning(); // // public boolean ignoreFilteredSequences(); // // public void makeReport(HTMLReportArchive report) throws IOException; // // // } // // Path: uk/ac/bbsrc/babraham/FastQC/Sequence/SequenceFile.java // public interface SequenceFile { // // public boolean hasNext(); // public Sequence next() throws SequenceFormatException; // public boolean isColorspace(); // public String name(); // public int getPercentComplete(); // public File getFile(); // // } // Path: uk/ac/bbsrc/babraham/FastQC/Analysis/AnalysisListener.java import uk.ac.bbsrc.babraham.FastQC.Modules.QCModule; import uk.ac.bbsrc.babraham.FastQC.Sequence.SequenceFile; /** * Copyright Copyright 2010-11 Simon Andrews * * This file is part of FastQC. * * FastQC 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. * * FastQC 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 FastQC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.bbsrc.babraham.FastQC.Analysis; public interface AnalysisListener { public void analysisStarted(SequenceFile file); public void analysisUpdated(SequenceFile file, int sequencesProcessed, int percentComplete);
public void analysisComplete(SequenceFile file, QCModule [] results);
bbilger/jrestless-examples
aws/service/aws-service-usage-example-client/src/main/java/com/jrestless/aws/examples/BackendService.java
// Path: aws/gateway/aws-gateway-showcase/src/main/java/com/jrestless/aws/examples/SampleResource.java // public static class PojoDto { // private final String value; // @JsonCreator // public PojoDto(@JsonProperty("value") String value) { // this.value = value; // } // public String getValue() { // return value; // } // }
import com.jrestless.aws.examples.SampleResource.PojoDto; import feign.Headers; import feign.Param; import feign.RequestLine;
package com.jrestless.aws.examples; @Headers({ "Accept: application/json", "Content-Type: application/json" }) public interface BackendService { @RequestLine("GET /api/info")
// Path: aws/gateway/aws-gateway-showcase/src/main/java/com/jrestless/aws/examples/SampleResource.java // public static class PojoDto { // private final String value; // @JsonCreator // public PojoDto(@JsonProperty("value") String value) { // this.value = value; // } // public String getValue() { // return value; // } // } // Path: aws/service/aws-service-usage-example-client/src/main/java/com/jrestless/aws/examples/BackendService.java import com.jrestless.aws.examples.SampleResource.PojoDto; import feign.Headers; import feign.Param; import feign.RequestLine; package com.jrestless.aws.examples; @Headers({ "Accept: application/json", "Content-Type: application/json" }) public interface BackendService { @RequestLine("GET /api/info")
PojoDto getInfo();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/presenter/AddFriendsPresenter.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // }
import android.widget.TextView; import com.idisfkj.hightcopywx.dao.RegisterDataHelper;
package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public interface AddFriendsPresenter { void switchView(CharSequence text);
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/presenter/AddFriendsPresenter.java import android.widget.TextView; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public interface AddFriendsPresenter { void switchView(CharSequence text);
void switchActicity(TextView searchContent, RegisterDataHelper helper);
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/presenter/AddFriendsPresenterImp.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/view/AddFriendsView.java // public interface AddFriendsView { // void showSearch(); // // void goneSearch(); // // void jumpSearchResult(String text); // // void changeText(CharSequence text); // // void showToast(String text); // }
import android.database.Cursor; import android.widget.TextView; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; import com.idisfkj.hightcopywx.main.view.AddFriendsView;
package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public class AddFriendsPresenterImp implements AddFriendsPresenter { private AddFriendsView mAddFriendsView; public AddFriendsPresenterImp(AddFriendsView addFriendsView) { mAddFriendsView = addFriendsView; } @Override public void switchView(CharSequence text) { if (!"".equals(text.toString())) { mAddFriendsView.showSearch(); } else { mAddFriendsView.goneSearch(); } mAddFriendsView.changeText(text); } @Override
// Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java // public class RegisterDataHelper extends BaseDataHelper { // // public RegisterDataHelper(Context mContext) { // super(mContext); // } // // @Override // public Uri getContentUri() { // return DataProvider.REGISTERS_CONTENT_URI; // } // // private ContentValues getContentValues(RegisterInfo info) { // ContentValues values = new ContentValues(); // values.put(RegisterDataInfo.USER_NAME, info.getUserName()); // values.put(RegisterDataInfo.NUMBER, info.getNumber()); // values.put(RegisterDataInfo.REGID, info.getRegId()); // return values; // } // // public static final class RegisterDataInfo implements BaseColumns { // // public RegisterDataInfo() { // } // // public static final String TABLE_NAME = "register"; // public static final String USER_NAME = "userName"; // public static final String REGID = "regId"; // public static final String NUMBER = "number"; // public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME) // .addColumn(USER_NAME, Column.DataType.TEXT) // .addColumn(NUMBER, Column.DataType.TEXT) // .addColumn(REGID, Column.DataType.TEXT); // } // // public Cursor query(String number, String regId) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID + "=?" // , new String[]{number, regId}, null); // return cursor; // } // // public Cursor query(String number) { // Cursor cursor = query(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, null); // return cursor; // } // // public void insert(RegisterInfo info) { // ContentValues values = getContentValues(info); // insert(values); // } // // public int update(RegisterInfo info, String number, String regId) { // ContentValues values = getContentValues(info); // int row = update(values, RegisterDataInfo.NUMBER + "=?" + " AND " + RegisterDataInfo.REGID // , new String[]{number}); // return row; // } // // public CursorLoader getCursorLoader(String number) { // return getCursorLoader(null, RegisterDataInfo.NUMBER + "=?", new String[]{number}, RegisterDataInfo._ID + " ASC"); // } // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/view/AddFriendsView.java // public interface AddFriendsView { // void showSearch(); // // void goneSearch(); // // void jumpSearchResult(String text); // // void changeText(CharSequence text); // // void showToast(String text); // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/presenter/AddFriendsPresenterImp.java import android.database.Cursor; import android.widget.TextView; import com.idisfkj.hightcopywx.dao.RegisterDataHelper; import com.idisfkj.hightcopywx.main.view.AddFriendsView; package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/5/7. * Email : [email protected]. */ public class AddFriendsPresenterImp implements AddFriendsPresenter { private AddFriendsView mAddFriendsView; public AddFriendsPresenterImp(AddFriendsView addFriendsView) { mAddFriendsView = addFriendsView; } @Override public void switchView(CharSequence text) { if (!"".equals(text.toString())) { mAddFriendsView.showSearch(); } else { mAddFriendsView.goneSearch(); } mAddFriendsView.changeText(text); } @Override
public void switchActicity(TextView searchContent, RegisterDataHelper helper) {
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/presenter/MainPresenterImp.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModel.java // public interface MainModel { // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModelImp.java // public class MainModelImp implements MainModel { // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/view/MainView.java // public interface MainView { // void switchWX(); // // void switchAddressBook(); // // void switchFind(); // // void switchMe(); // // void switchAlpha(int id); // // void jumpChatActivity(); // // void createBadgeView(); // }
import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.model.MainModel; import com.idisfkj.hightcopywx.main.model.MainModelImp; import com.idisfkj.hightcopywx.main.view.MainView;
package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class MainPresenterImp implements MainPresenter { private MainView mMianViw;
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModel.java // public interface MainModel { // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModelImp.java // public class MainModelImp implements MainModel { // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/view/MainView.java // public interface MainView { // void switchWX(); // // void switchAddressBook(); // // void switchFind(); // // void switchMe(); // // void switchAlpha(int id); // // void jumpChatActivity(); // // void createBadgeView(); // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/presenter/MainPresenterImp.java import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.model.MainModel; import com.idisfkj.hightcopywx.main.model.MainModelImp; import com.idisfkj.hightcopywx.main.view.MainView; package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class MainPresenterImp implements MainPresenter { private MainView mMianViw;
private MainModel mMainModel;
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/presenter/MainPresenterImp.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModel.java // public interface MainModel { // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModelImp.java // public class MainModelImp implements MainModel { // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/view/MainView.java // public interface MainView { // void switchWX(); // // void switchAddressBook(); // // void switchFind(); // // void switchMe(); // // void switchAlpha(int id); // // void jumpChatActivity(); // // void createBadgeView(); // }
import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.model.MainModel; import com.idisfkj.hightcopywx.main.model.MainModelImp; import com.idisfkj.hightcopywx.main.view.MainView;
package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class MainPresenterImp implements MainPresenter { private MainView mMianViw; private MainModel mMainModel; public MainPresenterImp(MainView mainView) { mMianViw = mainView;
// Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModel.java // public interface MainModel { // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/model/MainModelImp.java // public class MainModelImp implements MainModel { // // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/main/view/MainView.java // public interface MainView { // void switchWX(); // // void switchAddressBook(); // // void switchFind(); // // void switchMe(); // // void switchAlpha(int id); // // void jumpChatActivity(); // // void createBadgeView(); // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/presenter/MainPresenterImp.java import com.idisfkj.hightcopywx.R; import com.idisfkj.hightcopywx.main.model.MainModel; import com.idisfkj.hightcopywx.main.model.MainModelImp; import com.idisfkj.hightcopywx.main.view.MainView; package com.idisfkj.hightcopywx.main.presenter; /** * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class MainPresenterImp implements MainPresenter { private MainView mMianViw; private MainModel mMainModel; public MainPresenterImp(MainView mainView) { mMianViw = mainView;
mMainModel = new MainModelImp();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/util/SPUtils.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // }
import android.content.SharedPreferences; import com.idisfkj.hightcopywx.App;
package com.idisfkj.hightcopywx.util; /** SharedPreferences 工具类 * Created by idisfkj on 16/4/28. * Email : [email protected]. */ public class SPUtils { public SPUtils() { } public static SharedPreferences.Editor putString(String key, String value){
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/util/SPUtils.java import android.content.SharedPreferences; import com.idisfkj.hightcopywx.App; package com.idisfkj.hightcopywx.util; /** SharedPreferences 工具类 * Created by idisfkj on 16/4/28. * Email : [email protected]. */ public class SPUtils { public SPUtils() { } public static SharedPreferences.Editor putString(String key, String value){
App.editor = App.sp.edit();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/dao/DataProvider.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // }
import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.support.annotation.Nullable; import android.util.Log; import com.idisfkj.hightcopywx.App;
package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class DataProvider extends ContentProvider { public final String TAG = DataProvider.class.getSimpleName(); public static final Object DBLock = new Object(); private static final String AUTHORITY = "com.idisfkj.hightcopywx.provider"; private static final String SCHEME = "content://"; private static final String PATH_REGISTERS = "/registers"; private static final String PATH_WXS = "/wxs"; private static final String PATH_CHAT_MESSAGES = "/chats"; public static final Uri REGISTERS_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_REGISTERS); public static final Uri WXS_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_WXS); public static final Uri CHAT_MESSAGES_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_CHAT_MESSAGES); private static final int REGISTERS = 0; private static final int WXS = 1; private static final int CHAT_MESSAGES = 2; private static final String REGISTERS_CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.idisfkj.hightcopywx.register"; private static final String WXS_CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.idisfkj.hightcopywx.wx"; private static final String CHAT_MESSAGES_CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.idisfkj.hightcopywx.chat"; private static final UriMatcher sUriMatcher; private static DBHelper mDBHelper; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, "registers", REGISTERS); sUriMatcher.addURI(AUTHORITY, "wxs", WXS); sUriMatcher.addURI(AUTHORITY, "chats", CHAT_MESSAGES); } public static DBHelper getDBHelper() { if (mDBHelper == null) {
// Path: app/src/main/java/com/idisfkj/hightcopywx/App.java // public class App extends Application{ // private static Context mContext; // public static final String APP_ID = "2882303761517464903"; // public static final String APP_KEY = "5631746467903"; // public static final String APP_SECRET_KEY = "HxMA7STSUQMLEiDX+zo+5A=="; // public static final String TAG = "com.idisfkj.hightcopywx"; // public static final String DEVELOPER_ID = "/f6ukNwIPpdSmkrgsmklcMbW6WefG01XkxdILDNEUVw="; // public static final String DEVELOPER_NUMBER = "666666"; // public static final String DEVELOPER_NAME = "idisfkj"; // public static final String DEVELOPER_MESSAGE = "欢迎注册高仿微信App,我是该App的开发者,你可以使用添加朋友自行互动测试!如有问题可以在此留言与我。"; // public static final String HELLO_MESSAGE = "你已添加了%s,现在可以开始聊天了"; // public static final String UNREADNUM = "unReadNum"; // public static String mNumber = "-1"; // public static String mRegId = "-1"; // public static SharedPreferences sp; // public static SharedPreferences.Editor editor; // // // @Override // public void onCreate() { // super.onCreate(); // mContext = getApplicationContext(); // sp = getSharedPreferences("userInfo",Context.MODE_PRIVATE); // // //初始化push推送服务 // if(shouldInit()) { // MiPushClient.registerPush(this, APP_ID, APP_KEY); // } // // //小米推送调试日记 // LoggerInterface newLogger = new LoggerInterface() { // @Override // public void setTag(String tag) { // // ignore // } // @Override // public void log(String content, Throwable t) { // Log.d(TAG, content, t); // } // @Override // public void log(String content) { // Log.d(TAG, content); // } // }; // Logger.setLogger(this, newLogger); // // } // // private boolean shouldInit() { // ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)); // List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses(); // String mainProcessName = getPackageName(); // int myPid = android.os.Process.myPid(); // for (ActivityManager.RunningAppProcessInfo info : processInfos) { // if (info.pid == myPid && mainProcessName.equals(info.processName)) { // return true; // } // } // return false; // } // // public static Context getAppContext(){ // return mContext; // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/DataProvider.java import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.support.annotation.Nullable; import android.util.Log; import com.idisfkj.hightcopywx.App; package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class DataProvider extends ContentProvider { public final String TAG = DataProvider.class.getSimpleName(); public static final Object DBLock = new Object(); private static final String AUTHORITY = "com.idisfkj.hightcopywx.provider"; private static final String SCHEME = "content://"; private static final String PATH_REGISTERS = "/registers"; private static final String PATH_WXS = "/wxs"; private static final String PATH_CHAT_MESSAGES = "/chats"; public static final Uri REGISTERS_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_REGISTERS); public static final Uri WXS_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_WXS); public static final Uri CHAT_MESSAGES_CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_CHAT_MESSAGES); private static final int REGISTERS = 0; private static final int WXS = 1; private static final int CHAT_MESSAGES = 2; private static final String REGISTERS_CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.idisfkj.hightcopywx.register"; private static final String WXS_CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.idisfkj.hightcopywx.wx"; private static final String CHAT_MESSAGES_CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.idisfkj.hightcopywx.chat"; private static final UriMatcher sUriMatcher; private static DBHelper mDBHelper; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, "registers", REGISTERS); sUriMatcher.addURI(AUTHORITY, "wxs", WXS); sUriMatcher.addURI(AUTHORITY, "chats", CHAT_MESSAGES); } public static DBHelper getDBHelper() { if (mDBHelper == null) {
mDBHelper = new DBHelper(App.getAppContext());
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/RegisterInfo.java // public class RegisterInfo { // private String userName; // // private String number; // // private String regId; // // private String pictureUrl; // // public RegisterInfo(String userName, String number, String regId) { // this.userName = userName; // this.number = number; // this.regId = regId; // } // // public String getPictureUrl() { // return pictureUrl; // } // // public void setPictureUrl(String pictureUrl) { // this.pictureUrl = pictureUrl; // } // // public RegisterInfo() { // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getNumber() { // return number; // } // // public void setNumber(String number) { // this.number = number; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // }
import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.RegisterInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable;
package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class RegisterDataHelper extends BaseDataHelper { public RegisterDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.REGISTERS_CONTENT_URI; }
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/RegisterInfo.java // public class RegisterInfo { // private String userName; // // private String number; // // private String regId; // // private String pictureUrl; // // public RegisterInfo(String userName, String number, String regId) { // this.userName = userName; // this.number = number; // this.regId = regId; // } // // public String getPictureUrl() { // return pictureUrl; // } // // public void setPictureUrl(String pictureUrl) { // this.pictureUrl = pictureUrl; // } // // public RegisterInfo() { // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getNumber() { // return number; // } // // public void setNumber(String number) { // this.number = number; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // } // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.RegisterInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable; package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class RegisterDataHelper extends BaseDataHelper { public RegisterDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.REGISTERS_CONTENT_URI; }
private ContentValues getContentValues(RegisterInfo info) {
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/RegisterInfo.java // public class RegisterInfo { // private String userName; // // private String number; // // private String regId; // // private String pictureUrl; // // public RegisterInfo(String userName, String number, String regId) { // this.userName = userName; // this.number = number; // this.regId = regId; // } // // public String getPictureUrl() { // return pictureUrl; // } // // public void setPictureUrl(String pictureUrl) { // this.pictureUrl = pictureUrl; // } // // public RegisterInfo() { // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getNumber() { // return number; // } // // public void setNumber(String number) { // this.number = number; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // }
import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.RegisterInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable;
package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class RegisterDataHelper extends BaseDataHelper { public RegisterDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.REGISTERS_CONTENT_URI; } private ContentValues getContentValues(RegisterInfo info) { ContentValues values = new ContentValues(); values.put(RegisterDataInfo.USER_NAME, info.getUserName()); values.put(RegisterDataInfo.NUMBER, info.getNumber()); values.put(RegisterDataInfo.REGID, info.getRegId()); return values; } public static final class RegisterDataInfo implements BaseColumns { public RegisterDataInfo() { } public static final String TABLE_NAME = "register"; public static final String USER_NAME = "userName"; public static final String REGID = "regId"; public static final String NUMBER = "number";
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/RegisterInfo.java // public class RegisterInfo { // private String userName; // // private String number; // // private String regId; // // private String pictureUrl; // // public RegisterInfo(String userName, String number, String regId) { // this.userName = userName; // this.number = number; // this.regId = regId; // } // // public String getPictureUrl() { // return pictureUrl; // } // // public void setPictureUrl(String pictureUrl) { // this.pictureUrl = pictureUrl; // } // // public RegisterInfo() { // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getNumber() { // return number; // } // // public void setNumber(String number) { // this.number = number; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // } // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.RegisterInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable; package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class RegisterDataHelper extends BaseDataHelper { public RegisterDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.REGISTERS_CONTENT_URI; } private ContentValues getContentValues(RegisterInfo info) { ContentValues values = new ContentValues(); values.put(RegisterDataInfo.USER_NAME, info.getUserName()); values.put(RegisterDataInfo.NUMBER, info.getNumber()); values.put(RegisterDataInfo.REGID, info.getRegId()); return values; } public static final class RegisterDataInfo implements BaseColumns { public RegisterDataInfo() { } public static final String TABLE_NAME = "register"; public static final String USER_NAME = "userName"; public static final String REGID = "regId"; public static final String NUMBER = "number";
public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME)
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/RegisterInfo.java // public class RegisterInfo { // private String userName; // // private String number; // // private String regId; // // private String pictureUrl; // // public RegisterInfo(String userName, String number, String regId) { // this.userName = userName; // this.number = number; // this.regId = regId; // } // // public String getPictureUrl() { // return pictureUrl; // } // // public void setPictureUrl(String pictureUrl) { // this.pictureUrl = pictureUrl; // } // // public RegisterInfo() { // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getNumber() { // return number; // } // // public void setNumber(String number) { // this.number = number; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // }
import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.RegisterInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable;
package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class RegisterDataHelper extends BaseDataHelper { public RegisterDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.REGISTERS_CONTENT_URI; } private ContentValues getContentValues(RegisterInfo info) { ContentValues values = new ContentValues(); values.put(RegisterDataInfo.USER_NAME, info.getUserName()); values.put(RegisterDataInfo.NUMBER, info.getNumber()); values.put(RegisterDataInfo.REGID, info.getRegId()); return values; } public static final class RegisterDataInfo implements BaseColumns { public RegisterDataInfo() { } public static final String TABLE_NAME = "register"; public static final String USER_NAME = "userName"; public static final String REGID = "regId"; public static final String NUMBER = "number"; public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME)
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/RegisterInfo.java // public class RegisterInfo { // private String userName; // // private String number; // // private String regId; // // private String pictureUrl; // // public RegisterInfo(String userName, String number, String regId) { // this.userName = userName; // this.number = number; // this.regId = regId; // } // // public String getPictureUrl() { // return pictureUrl; // } // // public void setPictureUrl(String pictureUrl) { // this.pictureUrl = pictureUrl; // } // // public RegisterInfo() { // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getNumber() { // return number; // } // // public void setNumber(String number) { // this.number = number; // } // // public String getUserName() { // return userName; // } // // public void setUserName(String userName) { // this.userName = userName; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // } // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/RegisterDataHelper.java import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.RegisterInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable; package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/29. * Email : [email protected]. */ public class RegisterDataHelper extends BaseDataHelper { public RegisterDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.REGISTERS_CONTENT_URI; } private ContentValues getContentValues(RegisterInfo info) { ContentValues values = new ContentValues(); values.put(RegisterDataInfo.USER_NAME, info.getUserName()); values.put(RegisterDataInfo.NUMBER, info.getNumber()); values.put(RegisterDataInfo.REGID, info.getRegId()); return values; } public static final class RegisterDataInfo implements BaseColumns { public RegisterDataInfo() { } public static final String TABLE_NAME = "register"; public static final String USER_NAME = "userName"; public static final String REGID = "regId"; public static final String NUMBER = "number"; public static final SQLiteTable TABLE = new SQLiteTable(TABLE_NAME)
.addColumn(USER_NAME, Column.DataType.TEXT)
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/dao/ChatMessageDataHelper.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/ChatMessageInfo.java // public class ChatMessageInfo implements Serializable { // private String message; // /** // * 接收与发送的标识 // */ // private int flag; // private String time; // /** // * 接收该信息的账号 // */ // private String receiverNumber; // private String regId; // /** // * 发送者的账号 // */ // private String sendNumber; // // public ChatMessageInfo() { // } // // public ChatMessageInfo(String message, int flag, String time, String receiverNumber, String regId, String sendNumber) { // this.message = message; // this.flag = flag; // this.time = time; // this.receiverNumber = receiverNumber; // this.regId = regId; // this.sendNumber = sendNumber; // } // // public String getReceiverNumber() { // return receiverNumber; // } // // public void setReceiverNumber(String receiverNumber) { // this.receiverNumber = receiverNumber; // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getSendNumber() { // return sendNumber; // } // // public void setSendNumber(String sendNumber) { // this.sendNumber = sendNumber; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public int getFlag() { // return flag; // } // // public void setFlag(int flag) { // this.flag = flag; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // }
import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.ChatMessageInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable; import java.util.ArrayList;
package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/30. * Email : [email protected]. */ public class ChatMessageDataHelper extends BaseDataHelper { public ChatMessageDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.CHAT_MESSAGES_CONTENT_URI; }
// Path: app/src/main/java/com/idisfkj/hightcopywx/beans/ChatMessageInfo.java // public class ChatMessageInfo implements Serializable { // private String message; // /** // * 接收与发送的标识 // */ // private int flag; // private String time; // /** // * 接收该信息的账号 // */ // private String receiverNumber; // private String regId; // /** // * 发送者的账号 // */ // private String sendNumber; // // public ChatMessageInfo() { // } // // public ChatMessageInfo(String message, int flag, String time, String receiverNumber, String regId, String sendNumber) { // this.message = message; // this.flag = flag; // this.time = time; // this.receiverNumber = receiverNumber; // this.regId = regId; // this.sendNumber = sendNumber; // } // // public String getReceiverNumber() { // return receiverNumber; // } // // public void setReceiverNumber(String receiverNumber) { // this.receiverNumber = receiverNumber; // } // // public String getRegId() { // return regId; // } // // public void setRegId(String regId) { // this.regId = regId; // } // // public String getSendNumber() { // return sendNumber; // } // // public void setSendNumber(String sendNumber) { // this.sendNumber = sendNumber; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // public int getFlag() { // return flag; // } // // public void setFlag(int flag) { // this.flag = flag; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/Column.java // public class Column { // private Constraint mConstraint; // private DataType mDataType; // private String mColumnName; // // public Column(String columnName, Constraint constraint, DataType dataType) { // mColumnName = columnName; // mConstraint = constraint; // mDataType = dataType; // } // // public String getColumnName() { // return mColumnName; // } // // public Constraint getConstraint() { // return mConstraint; // } // // public DataType getDataType() { // return mDataType; // } // // public static enum Constraint { // // NUll("NULL"), UNIQUE("UNIQUE"), PRIMARY_KEY("PRIMARY KEY"), NOT("NOT"), FOREIGN_KEY("FOREIGN KEY"), CHECK("CHECK"); // private String mValue; // // Constraint(String value) { // mValue = value; // } // // @Override // public String toString() { // return mValue; // } // } // // public static enum DataType { // NULL, REAL, INTEGER, TEXT, BLOB; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/util/database/SQLiteTable.java // public class SQLiteTable { // private String mTableName; // private List<Column> mColumns = new ArrayList<>(); // // /** // * default add main key // * // * @param mTableName // */ // public SQLiteTable(String mTableName) { // this.mTableName = mTableName; // mColumns.add(new Column(BaseColumns._ID, Column.Constraint.PRIMARY_KEY, Column.DataType.INTEGER)); // } // // public SQLiteTable addColumn(Column column) { // mColumns.add(column); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.DataType dataType) { // mColumns.add(new Column(columnName, null, dataType)); // return this; // } // // public SQLiteTable addColumn(String columnName, Column.Constraint constraint, Column.DataType dataType) { // mColumns.add(new Column(columnName, constraint, dataType)); // return this; // } // // public void create(SQLiteDatabase db) { // String format = " %s"; // int index = 0; // StringBuilder builder = new StringBuilder(); // builder.append("CREATE TABLE IF NOT EXISTS "); // builder.append(mTableName); // builder.append("("); // int count = mColumns.size(); // for (Column column : mColumns) { // builder.append(column.getColumnName()); // builder.append(String.format(format, column.getDataType().name())); // Column.Constraint constraint = column.getConstraint(); // if (constraint != null) { // builder.append(String.format(format, constraint.toString())); // } // if (index < count - 1) { // builder.append(","); // } // index++; // } // builder.append(");"); // db.execSQL(builder.toString()); // } // // public void delete(SQLiteDatabase db) { // db.execSQL("DROP TABLE IF EXISTS " + mTableName); // } // // } // Path: app/src/main/java/com/idisfkj/hightcopywx/dao/ChatMessageDataHelper.java import android.content.ContentValues; import android.content.Context; import android.content.CursorLoader; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import com.idisfkj.hightcopywx.beans.ChatMessageInfo; import com.idisfkj.hightcopywx.util.database.Column; import com.idisfkj.hightcopywx.util.database.SQLiteTable; import java.util.ArrayList; package com.idisfkj.hightcopywx.dao; /** * Created by idisfkj on 16/4/30. * Email : [email protected]. */ public class ChatMessageDataHelper extends BaseDataHelper { public ChatMessageDataHelper(Context mContext) { super(mContext); } @Override public Uri getContentUri() { return DataProvider.CHAT_MESSAGES_CONTENT_URI; }
public ContentValues getContentValues(ChatMessageInfo info) {
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // }
import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment;
package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0:
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment; package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0:
mFragment = new WXFragment();
idisfkj/HightCopyWX
app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // }
import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment;
package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0: mFragment = new WXFragment(); break; case 1:
// Path: app/src/main/java/com/idisfkj/hightcopywx/contact/ContactFragment.java // public class ContactFragment extends Fragment { // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.contact_layout, null); // return view; // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/find/FindFragment.java // public class FindFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.find_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/me/MeFragment.java // public class MeFragment extends Fragment{ // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.me_layout,null); // return view; // } // } // // Path: app/src/main/java/com/idisfkj/hightcopywx/wx/widget/WXFragment.java // public class WXFragment extends Fragment implements WXView, LoaderManager.LoaderCallbacks<Cursor> { // @InjectView(R.id.wx_recyclerView) // RecyclerView wxRecyclerView; // private WXAdapter wxAdapter; // private WXPresent mWXPresent; // private WXDataHelper mHelper; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = LayoutInflater.from(getContext()).inflate(R.layout.wx_layout, null); // ButterKnife.inject(this, view); // init(); // return view; // } // // public void init() { // wxAdapter = new WXAdapter(getContext()); // mWXPresent = new WXPresentImp(this); // wxRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); // wxRecyclerView.addItemDecoration(new WXItemDecoration(getContext())); // wxRecyclerView.setAdapter(wxAdapter); // wxRecyclerView.addOnItemTouchListener(new OnItemTouchListener(wxRecyclerView) { // @Override // public void onItemListener(RecyclerView.ViewHolder vh) { // Intent intent = new Intent(getActivity(), ChatActivity.class); // Bundle bundle = new Bundle(); // bundle.putInt("_id", vh.getLayoutPosition()+1); // intent.putExtras(bundle); // startActivity(intent); // } // }); // mHelper = new WXDataHelper(getContext()); // getLoaderManager().initLoader(0, null, this); // } // // @Override // public void onDestroyView() { // super.onDestroyView(); // ButterKnife.reset(this); // } // // @Override // public Loader<Cursor> onCreateLoader(int id, Bundle args) { // return mHelper.getCursorLoader(SPUtils.getString("userPhone")); // } // // @Override // public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // if (loader != null && data.getCount() <= 0) { // mWXPresent.initData(mHelper); // } // wxAdapter.changeCursor(data); // } // // @Override // public void onLoaderReset(Loader<Cursor> loader) { // wxAdapter.changeCursor(null); // } // } // Path: app/src/main/java/com/idisfkj/hightcopywx/main/FragmentFactory.java import android.support.v4.app.Fragment; import com.idisfkj.hightcopywx.contact.ContactFragment; import com.idisfkj.hightcopywx.find.FindFragment; import com.idisfkj.hightcopywx.me.MeFragment; import com.idisfkj.hightcopywx.wx.widget.WXFragment; package com.idisfkj.hightcopywx.main; /** * Fragment工厂 * Created by idisfkj on 16/4/19. * Email : [email protected]. */ public class FragmentFactory { private Fragment mFragment; private int mSize; public FragmentFactory(int size) { mSize = size; } public int getSize(){ return mSize; } public Fragment createFragment(int position){ switch (position){ case 0: mFragment = new WXFragment(); break; case 1:
mFragment = new ContactFragment();