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
|
---|---|---|---|---|---|---|
bmatthews68/inmemdb-maven-plugin | src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestDatabaseFactory.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/derby/DerbyDatabaseFactory.java
// public final class DerbyDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code derby}.
// */
// @Override
// public String getServerName() {
// return "derby";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link DerbyDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new DerbyDatabase();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2DatabaseFactory.java
// public final class H2DatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code h2}.
// */
// @Override
// public String getServerName() {
// return "h2";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link H2Database} instance.
// */
// @Override
// public Server createServer() {
// return new H2Database();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabaseFactory.java
// public final class HSQLDBDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code hsqldb}.
// */
// @Override
// public String getServerName() {
// return "hsqldb";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link HSQLDBDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new HSQLDBDatabase();
// }
// }
| import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.MockitoAnnotations.initMocks;
import com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.h2.H2DatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabaseFactory;
import com.btmatthews.utils.monitor.Logger;
import com.btmatthews.utils.monitor.ServerFactory;
import com.btmatthews.utils.monitor.ServerFactoryLocator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock; | /*
* Copyright 2011-2012 Brian Matthews
*
* 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.btmatthews.maven.plugins.inmemdb.test;
/**
* Unit test the server factory configuration.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @version 1.0.0
*/
public final class TestDatabaseFactory {
/**
* Mock for the logger.
*/
@Mock
private Logger logger;
/**
* Used to locate the {@link ServerFactory} for the database server.
*/
private ServerFactoryLocator locator;
/**
* Create the server locator factory test fixture.
*/
@Before
public void setUp() {
initMocks(this);
locator = ServerFactoryLocator.getInstance(logger);
}
/**
* Verify that the server factory locator returns {@code null} when {@code null} is passed as the
* database type.
*/
@Test
public void testNullType() {
final ServerFactory factory = locator.getFactory(null);
assertNull(factory);
}
/**
* Verify that the server factory locator returns a {@link DerbyDatabaseFactory} when
* "derby" is passed as the database type.
*/
@Test
public void testDerbyType() {
final ServerFactory factory = locator.getFactory("derby");
assertNotNull(factory);
assertTrue(factory instanceof DerbyDatabaseFactory);
}
/**
* Verify that the server factory locator returns a {@link H2DatabaseFactory} when
* "h2" is passed as the database type.
*/
@Test
public void testH2Type() {
final ServerFactory factory = locator.getFactory("h2");
assertNotNull(factory); | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/derby/DerbyDatabaseFactory.java
// public final class DerbyDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code derby}.
// */
// @Override
// public String getServerName() {
// return "derby";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link DerbyDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new DerbyDatabase();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2DatabaseFactory.java
// public final class H2DatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code h2}.
// */
// @Override
// public String getServerName() {
// return "h2";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link H2Database} instance.
// */
// @Override
// public Server createServer() {
// return new H2Database();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabaseFactory.java
// public final class HSQLDBDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code hsqldb}.
// */
// @Override
// public String getServerName() {
// return "hsqldb";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link HSQLDBDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new HSQLDBDatabase();
// }
// }
// Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestDatabaseFactory.java
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.MockitoAnnotations.initMocks;
import com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.h2.H2DatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabaseFactory;
import com.btmatthews.utils.monitor.Logger;
import com.btmatthews.utils.monitor.ServerFactory;
import com.btmatthews.utils.monitor.ServerFactoryLocator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
/*
* Copyright 2011-2012 Brian Matthews
*
* 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.btmatthews.maven.plugins.inmemdb.test;
/**
* Unit test the server factory configuration.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @version 1.0.0
*/
public final class TestDatabaseFactory {
/**
* Mock for the logger.
*/
@Mock
private Logger logger;
/**
* Used to locate the {@link ServerFactory} for the database server.
*/
private ServerFactoryLocator locator;
/**
* Create the server locator factory test fixture.
*/
@Before
public void setUp() {
initMocks(this);
locator = ServerFactoryLocator.getInstance(logger);
}
/**
* Verify that the server factory locator returns {@code null} when {@code null} is passed as the
* database type.
*/
@Test
public void testNullType() {
final ServerFactory factory = locator.getFactory(null);
assertNull(factory);
}
/**
* Verify that the server factory locator returns a {@link DerbyDatabaseFactory} when
* "derby" is passed as the database type.
*/
@Test
public void testDerbyType() {
final ServerFactory factory = locator.getFactory("derby");
assertNotNull(factory);
assertTrue(factory instanceof DerbyDatabaseFactory);
}
/**
* Verify that the server factory locator returns a {@link H2DatabaseFactory} when
* "h2" is passed as the database type.
*/
@Test
public void testH2Type() {
final ServerFactory factory = locator.getFactory("h2");
assertNotNull(factory); | assertTrue(factory instanceof H2DatabaseFactory); |
bmatthews68/inmemdb-maven-plugin | src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestDatabaseFactory.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/derby/DerbyDatabaseFactory.java
// public final class DerbyDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code derby}.
// */
// @Override
// public String getServerName() {
// return "derby";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link DerbyDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new DerbyDatabase();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2DatabaseFactory.java
// public final class H2DatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code h2}.
// */
// @Override
// public String getServerName() {
// return "h2";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link H2Database} instance.
// */
// @Override
// public Server createServer() {
// return new H2Database();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabaseFactory.java
// public final class HSQLDBDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code hsqldb}.
// */
// @Override
// public String getServerName() {
// return "hsqldb";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link HSQLDBDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new HSQLDBDatabase();
// }
// }
| import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.MockitoAnnotations.initMocks;
import com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.h2.H2DatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabaseFactory;
import com.btmatthews.utils.monitor.Logger;
import com.btmatthews.utils.monitor.ServerFactory;
import com.btmatthews.utils.monitor.ServerFactoryLocator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock; | /**
* Verify that the server factory locator returns a {@link DerbyDatabaseFactory} when
* "derby" is passed as the database type.
*/
@Test
public void testDerbyType() {
final ServerFactory factory = locator.getFactory("derby");
assertNotNull(factory);
assertTrue(factory instanceof DerbyDatabaseFactory);
}
/**
* Verify that the server factory locator returns a {@link H2DatabaseFactory} when
* "h2" is passed as the database type.
*/
@Test
public void testH2Type() {
final ServerFactory factory = locator.getFactory("h2");
assertNotNull(factory);
assertTrue(factory instanceof H2DatabaseFactory);
}
/**
* Verify that the server factory locator returns a {@link HSQLDBDatabaseFactory} when
* "hsqldb" is passed as the database type.
*/
@Test
public void testHSQLDBType() {
final ServerFactory factory = locator.getFactory("hsqldb");
assertNotNull(factory); | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/derby/DerbyDatabaseFactory.java
// public final class DerbyDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code derby}.
// */
// @Override
// public String getServerName() {
// return "derby";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link DerbyDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new DerbyDatabase();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/h2/H2DatabaseFactory.java
// public final class H2DatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code h2}.
// */
// @Override
// public String getServerName() {
// return "h2";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link H2Database} instance.
// */
// @Override
// public Server createServer() {
// return new H2Database();
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabaseFactory.java
// public final class HSQLDBDatabaseFactory implements ServerFactory {
//
// /**
// * Get the name of the server created by this server factory.
// *
// * @return Always returns {@code hsqldb}.
// */
// @Override
// public String getServerName() {
// return "hsqldb";
// }
//
// /**
// * Create the server instance.
// *
// * @return A {@link HSQLDBDatabase} instance.
// */
// @Override
// public Server createServer() {
// return new HSQLDBDatabase();
// }
// }
// Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestDatabaseFactory.java
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.MockitoAnnotations.initMocks;
import com.btmatthews.maven.plugins.inmemdb.db.derby.DerbyDatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.h2.H2DatabaseFactory;
import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabaseFactory;
import com.btmatthews.utils.monitor.Logger;
import com.btmatthews.utils.monitor.ServerFactory;
import com.btmatthews.utils.monitor.ServerFactoryLocator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
/**
* Verify that the server factory locator returns a {@link DerbyDatabaseFactory} when
* "derby" is passed as the database type.
*/
@Test
public void testDerbyType() {
final ServerFactory factory = locator.getFactory("derby");
assertNotNull(factory);
assertTrue(factory instanceof DerbyDatabaseFactory);
}
/**
* Verify that the server factory locator returns a {@link H2DatabaseFactory} when
* "h2" is passed as the database type.
*/
@Test
public void testH2Type() {
final ServerFactory factory = locator.getFactory("h2");
assertNotNull(factory);
assertTrue(factory instanceof H2DatabaseFactory);
}
/**
* Verify that the server factory locator returns a {@link HSQLDBDatabaseFactory} when
* "hsqldb" is passed as the database type.
*/
@Test
public void testHSQLDBType() {
final ServerFactory factory = locator.getFactory("hsqldb");
assertNotNull(factory); | assertTrue(factory instanceof HSQLDBDatabaseFactory); |
bmatthews68/inmemdb-maven-plugin | src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitXMLLoader.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
| import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.btmatthews.maven.plugins.inmemdb.Source;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet; | /*
* Copyright 2011-2012 Brian Matthews
*
* 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.btmatthews.maven.plugins.inmemdb.ldr.dbunit;
/**
* Loader that loads data from a DBUnit XML data set.
*
* @author <a href="[email protected]">Brian Matthews</a>
* @version 1.0.0
*/
public final class DBUnitXMLLoader extends AbstractDBUnitLoader {
/**
* The file extension for DBUnit XML data set files.
*/
private static final String EXT = ".dbunit.xml";
/**
* Get the file extension for DBUnit XML data set files.
*
* @return {@link #EXT}
*/
@Override
protected String getExtension() {
return EXT;
}
/**
* Load a DBUnit XML data set.
*
* @param source The source file containing the DBUnit XML data set.
* @return The DBUnit XML data set.
* @throws DataSetException If there was an error loading the DBUnit XML data set.
* @throws IOException If there was an error reading the DBUnit XML data set from
* the file.
*/
@Override | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/ldr/dbunit/DBUnitXMLLoader.java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import com.btmatthews.maven.plugins.inmemdb.Source;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.XmlDataSet;
/*
* Copyright 2011-2012 Brian Matthews
*
* 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.btmatthews.maven.plugins.inmemdb.ldr.dbunit;
/**
* Loader that loads data from a DBUnit XML data set.
*
* @author <a href="[email protected]">Brian Matthews</a>
* @version 1.0.0
*/
public final class DBUnitXMLLoader extends AbstractDBUnitLoader {
/**
* The file extension for DBUnit XML data set files.
*/
private static final String EXT = ".dbunit.xml";
/**
* Get the file extension for DBUnit XML data set files.
*
* @return {@link #EXT}
*/
@Override
protected String getExtension() {
return EXT;
}
/**
* Load a DBUnit XML data set.
*
* @param source The source file containing the DBUnit XML data set.
* @return The DBUnit XML data set.
* @throws DataSetException If there was an error loading the DBUnit XML data set.
* @throws IOException If there was an error reading the DBUnit XML data set from
* the file.
*/
@Override | protected IDataSet loadDataSet(final Source source) |
bmatthews68/inmemdb-maven-plugin | src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestHSQLDBDatabase.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabase.java
// public final class HSQLDBDatabase extends AbstractSQLDatabase {
//
// /**
// * The connection protocol for in-memory HSQLDB databases.
// */
// private static final String PROTOCOL = "hsqldb:hsql://localhost:{0,number,#}/";
// /**
// * Default port HSQLDB listens on, can be altered via setting port property
// */
// private static final int DEFAULT_PORT = ServerConstants.SC_DEFAULT_HSQL_SERVER_PORT;
// private static final int PING_RETRIES = 10;
// private static final int PING_DELAY = 100;
// /**
// * The loaders that are supported for loading data or executing scripts.
// */
// private static final Loader[] LOADERS = new Loader[]{
// new DBUnitXMLLoader(), new DBUnitFlatXMLLoader(),
// new DBUnitCSVLoader(), new DBUnitXLSLoader(), new SQLLoader()};
// /**
// * The HSQLDB server.
// */
// private Server server;
//
// /**
// * The default constructor initializes the default database port.
// */
// public HSQLDBDatabase() {
// super(DEFAULT_PORT);
// }
//
// /**
// * Get the database connection protocol.
// *
// * @return Always returns {@link HSQLDBDatabase#PROTOCOL}.
// */
// @Override
// protected String getUrlProtocol() {
// return MessageFormat.format(PROTOCOL, getPort());
// }
//
// /**
// * Get the data source that describes the connection to the in-memory HSQLDB
// * database.
// *
// * @return Returns {@code dataSource} which was initialised by the
// * constructor.
// */
// @Override
// public DataSource getDataSource() {
// final JDBCDataSource dataSource = new JDBCDataSource();
// dataSource.setUrl(getUrl());
// dataSource.setUser(getUsername());
// dataSource.setPassword(getPassword());
// return dataSource;
// }
//
// /**
// * Get the loaders that are supported for loading data or executing scripts.
// *
// * @return Returns {@link #LOADERS}.
// */
// @Override
// public Loader[] getLoaders() {
// return LOADERS;
// }
//
// /**
// * Start the in-memory HSQLDB server.
// *
// * @param logger Used to report errors and raise exceptions.
// */
// @Override
// public void start(final Logger logger) {
//
// logger.logInfo("Starting embedded HSQLDB database");
//
// server = new Server();
// server.setDatabasePath(0, DatabaseURL.S_MEM + getDatabaseName());
// server.setDatabaseName(0, getDatabaseName());
// server.setDaemon(true);
// server.setAddress(ServerConstants.SC_DEFAULT_ADDRESS);
// server.setPort(getPort());
// server.setErrWriter(null);
// server.setLogWriter(null);
// server.setTls(false);
// server.setTrace(false);
// server.setSilent(true);
// server.setNoSystemExit(true);
// server.setRestartOnShutdown(false);
// server.start();
//
// logger.logInfo("Started embedded HSQLDB database");
// }
//
// /**
// * Shutdown the in-memory HSQLDB database by sending it a SHUTDOWN command.
// *
// * @param logger Used to report errors and raise exceptions.
// */
// @Override
// public void stop(final Logger logger) {
//
// logger.logInfo("Stopping embedded HSQLDB database");
//
// if (server != null) {
// server.stop();
// server.shutdown();
// }
//
// logger.logInfo("Stopping embedded HSQLDB database");
// }
//
// @Override
// public boolean isStarted(final Logger logger) {
// if (server != null) {
// try {
// server.checkRunning(true);
// return true;
// } catch (final RuntimeException e) {
// return false;
// }
// }
// return false;
// }
//
// @Override
// public boolean isStopped(final Logger logger) {
// try {
// server.checkRunning(false);
// return true;
// } catch (final RuntimeException e) {
// return false;
// }
// }
// }
| import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabase;
import com.btmatthews.utils.monitor.Server; | /*
* Copyright 2011-2012 Brian Matthews
*
* 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.btmatthews.maven.plugins.inmemdb.test;
/**
* Unit test the HSQLDB database server.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @since 1.2.0
*/
public class TestHSQLDBDatabase extends AbstractTestDatabase {
/**
* Create the {@link HSQLDBDatabase} server test fixture.
*
* @return The {@link HSQLDBDatabase} server test fixture.
*/
@Override
protected Server createDatabaseServer() { | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/hsqldb/HSQLDBDatabase.java
// public final class HSQLDBDatabase extends AbstractSQLDatabase {
//
// /**
// * The connection protocol for in-memory HSQLDB databases.
// */
// private static final String PROTOCOL = "hsqldb:hsql://localhost:{0,number,#}/";
// /**
// * Default port HSQLDB listens on, can be altered via setting port property
// */
// private static final int DEFAULT_PORT = ServerConstants.SC_DEFAULT_HSQL_SERVER_PORT;
// private static final int PING_RETRIES = 10;
// private static final int PING_DELAY = 100;
// /**
// * The loaders that are supported for loading data or executing scripts.
// */
// private static final Loader[] LOADERS = new Loader[]{
// new DBUnitXMLLoader(), new DBUnitFlatXMLLoader(),
// new DBUnitCSVLoader(), new DBUnitXLSLoader(), new SQLLoader()};
// /**
// * The HSQLDB server.
// */
// private Server server;
//
// /**
// * The default constructor initializes the default database port.
// */
// public HSQLDBDatabase() {
// super(DEFAULT_PORT);
// }
//
// /**
// * Get the database connection protocol.
// *
// * @return Always returns {@link HSQLDBDatabase#PROTOCOL}.
// */
// @Override
// protected String getUrlProtocol() {
// return MessageFormat.format(PROTOCOL, getPort());
// }
//
// /**
// * Get the data source that describes the connection to the in-memory HSQLDB
// * database.
// *
// * @return Returns {@code dataSource} which was initialised by the
// * constructor.
// */
// @Override
// public DataSource getDataSource() {
// final JDBCDataSource dataSource = new JDBCDataSource();
// dataSource.setUrl(getUrl());
// dataSource.setUser(getUsername());
// dataSource.setPassword(getPassword());
// return dataSource;
// }
//
// /**
// * Get the loaders that are supported for loading data or executing scripts.
// *
// * @return Returns {@link #LOADERS}.
// */
// @Override
// public Loader[] getLoaders() {
// return LOADERS;
// }
//
// /**
// * Start the in-memory HSQLDB server.
// *
// * @param logger Used to report errors and raise exceptions.
// */
// @Override
// public void start(final Logger logger) {
//
// logger.logInfo("Starting embedded HSQLDB database");
//
// server = new Server();
// server.setDatabasePath(0, DatabaseURL.S_MEM + getDatabaseName());
// server.setDatabaseName(0, getDatabaseName());
// server.setDaemon(true);
// server.setAddress(ServerConstants.SC_DEFAULT_ADDRESS);
// server.setPort(getPort());
// server.setErrWriter(null);
// server.setLogWriter(null);
// server.setTls(false);
// server.setTrace(false);
// server.setSilent(true);
// server.setNoSystemExit(true);
// server.setRestartOnShutdown(false);
// server.start();
//
// logger.logInfo("Started embedded HSQLDB database");
// }
//
// /**
// * Shutdown the in-memory HSQLDB database by sending it a SHUTDOWN command.
// *
// * @param logger Used to report errors and raise exceptions.
// */
// @Override
// public void stop(final Logger logger) {
//
// logger.logInfo("Stopping embedded HSQLDB database");
//
// if (server != null) {
// server.stop();
// server.shutdown();
// }
//
// logger.logInfo("Stopping embedded HSQLDB database");
// }
//
// @Override
// public boolean isStarted(final Logger logger) {
// if (server != null) {
// try {
// server.checkRunning(true);
// return true;
// } catch (final RuntimeException e) {
// return false;
// }
// }
// return false;
// }
//
// @Override
// public boolean isStopped(final Logger logger) {
// try {
// server.checkRunning(false);
// return true;
// } catch (final RuntimeException e) {
// return false;
// }
// }
// }
// Path: src/test/java/com/btmatthews/maven/plugins/inmemdb/test/TestHSQLDBDatabase.java
import com.btmatthews.maven.plugins.inmemdb.db.hsqldb.HSQLDBDatabase;
import com.btmatthews.utils.monitor.Server;
/*
* Copyright 2011-2012 Brian Matthews
*
* 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.btmatthews.maven.plugins.inmemdb.test;
/**
* Unit test the HSQLDB database server.
*
* @author <a href="mailto:[email protected]">Brian Matthews</a>
* @since 1.2.0
*/
public class TestHSQLDBDatabase extends AbstractTestDatabase {
/**
* Create the {@link HSQLDBDatabase} server test fixture.
*
* @return The {@link HSQLDBDatabase} server test fixture.
*/
@Override
protected Server createDatabaseServer() { | return new HSQLDBDatabase(); |
bmatthews68/inmemdb-maven-plugin | src/main/java/com/btmatthews/maven/plugins/inmemdb/db/AbstractDatabase.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java
// public interface Database {
//
// /**
// * Find the loader that supports the source file and use it to load the data
// * into or execute the script against the database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing data or script.
// */
// void load(Logger logger, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java
// public interface Loader {
//
// /**
// * The message key for the error reported when a source file cannot be read.
// */
// String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file";
//
// /**
// * The message key for the error reported when a source file cannot be processed.
// */
// String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file";
//
// /**
// * Determine whether or not the data or script can be loaded or executed.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing the data or script.
// * @return <ul>
// * <li><code>true</code> if the data or script can be loaded or executed.</li>
// * <li><code>false</code>if the data or script cannot be loaded or executed.</li>
// * </ul>
// */
// boolean isSupported(Logger logger, Source source);
//
// /**
// * Load data into or execute a script against the in-memory database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param database The in-memory database.
// * @param source The source file containing the data or script.
// */
// void load(Logger logger, Database database, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/MessageUtil.java
// public final class MessageUtil {
//
// /**
// * The base name of the message resource bundle.
// */
// private static final String BUNDLE_NAME = "com.btmatthews.maven.plugins.inmemdb.messages";
//
// /**
// * The message resource bundle.
// */
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// /**
// * Make the constructor private because this class only offers static utility methods.
// */
// private MessageUtil() {
// }
//
// /**
// * Retrieve the message pattern for a given message key from the resource
// * bundle and format the message replacing the place holders with the
// * message arguments.
// *
// * @param messageKey The key of the message in the resource bundle.
// * @param arguments The message arguments.
// * @return The expanded message string.
// */
// public static String getMessage(final String messageKey,
// final Object... arguments) {
// final String messagePattern = RESOURCE_BUNDLE.getString(messageKey);
// return MessageFormat.format(messagePattern, arguments);
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
| import java.util.HashMap;
import java.util.Map;
import com.btmatthews.maven.plugins.inmemdb.Database;
import com.btmatthews.maven.plugins.inmemdb.Loader;
import com.btmatthews.maven.plugins.inmemdb.MessageUtil;
import com.btmatthews.maven.plugins.inmemdb.Source;
import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger; | if (databasePassword == null) {
return "";
} else {
return databasePassword;
}
}
/**
* Get the port number used in the database connection URL
*
* @return database port number
*/
public int getPort() {
return port;
}
/**
* Get the attributes used to connect to database
* @return attributes
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* Get the loaders that are supported for loading data or executing scripts.
*
* @return Returns an array of loaders.
*/ | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java
// public interface Database {
//
// /**
// * Find the loader that supports the source file and use it to load the data
// * into or execute the script against the database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing data or script.
// */
// void load(Logger logger, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java
// public interface Loader {
//
// /**
// * The message key for the error reported when a source file cannot be read.
// */
// String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file";
//
// /**
// * The message key for the error reported when a source file cannot be processed.
// */
// String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file";
//
// /**
// * Determine whether or not the data or script can be loaded or executed.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing the data or script.
// * @return <ul>
// * <li><code>true</code> if the data or script can be loaded or executed.</li>
// * <li><code>false</code>if the data or script cannot be loaded or executed.</li>
// * </ul>
// */
// boolean isSupported(Logger logger, Source source);
//
// /**
// * Load data into or execute a script against the in-memory database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param database The in-memory database.
// * @param source The source file containing the data or script.
// */
// void load(Logger logger, Database database, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/MessageUtil.java
// public final class MessageUtil {
//
// /**
// * The base name of the message resource bundle.
// */
// private static final String BUNDLE_NAME = "com.btmatthews.maven.plugins.inmemdb.messages";
//
// /**
// * The message resource bundle.
// */
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// /**
// * Make the constructor private because this class only offers static utility methods.
// */
// private MessageUtil() {
// }
//
// /**
// * Retrieve the message pattern for a given message key from the resource
// * bundle and format the message replacing the place holders with the
// * message arguments.
// *
// * @param messageKey The key of the message in the resource bundle.
// * @param arguments The message arguments.
// * @return The expanded message string.
// */
// public static String getMessage(final String messageKey,
// final Object... arguments) {
// final String messagePattern = RESOURCE_BUNDLE.getString(messageKey);
// return MessageFormat.format(messagePattern, arguments);
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/AbstractDatabase.java
import java.util.HashMap;
import java.util.Map;
import com.btmatthews.maven.plugins.inmemdb.Database;
import com.btmatthews.maven.plugins.inmemdb.Loader;
import com.btmatthews.maven.plugins.inmemdb.MessageUtil;
import com.btmatthews.maven.plugins.inmemdb.Source;
import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger;
if (databasePassword == null) {
return "";
} else {
return databasePassword;
}
}
/**
* Get the port number used in the database connection URL
*
* @return database port number
*/
public int getPort() {
return port;
}
/**
* Get the attributes used to connect to database
* @return attributes
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* Get the loaders that are supported for loading data or executing scripts.
*
* @return Returns an array of loaders.
*/ | protected abstract Loader[] getLoaders(); |
bmatthews68/inmemdb-maven-plugin | src/main/java/com/btmatthews/maven/plugins/inmemdb/db/AbstractDatabase.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java
// public interface Database {
//
// /**
// * Find the loader that supports the source file and use it to load the data
// * into or execute the script against the database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing data or script.
// */
// void load(Logger logger, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java
// public interface Loader {
//
// /**
// * The message key for the error reported when a source file cannot be read.
// */
// String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file";
//
// /**
// * The message key for the error reported when a source file cannot be processed.
// */
// String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file";
//
// /**
// * Determine whether or not the data or script can be loaded or executed.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing the data or script.
// * @return <ul>
// * <li><code>true</code> if the data or script can be loaded or executed.</li>
// * <li><code>false</code>if the data or script cannot be loaded or executed.</li>
// * </ul>
// */
// boolean isSupported(Logger logger, Source source);
//
// /**
// * Load data into or execute a script against the in-memory database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param database The in-memory database.
// * @param source The source file containing the data or script.
// */
// void load(Logger logger, Database database, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/MessageUtil.java
// public final class MessageUtil {
//
// /**
// * The base name of the message resource bundle.
// */
// private static final String BUNDLE_NAME = "com.btmatthews.maven.plugins.inmemdb.messages";
//
// /**
// * The message resource bundle.
// */
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// /**
// * Make the constructor private because this class only offers static utility methods.
// */
// private MessageUtil() {
// }
//
// /**
// * Retrieve the message pattern for a given message key from the resource
// * bundle and format the message replacing the place holders with the
// * message arguments.
// *
// * @param messageKey The key of the message in the resource bundle.
// * @param arguments The message arguments.
// * @return The expanded message string.
// */
// public static String getMessage(final String messageKey,
// final Object... arguments) {
// final String messagePattern = RESOURCE_BUNDLE.getString(messageKey);
// return MessageFormat.format(messagePattern, arguments);
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
| import java.util.HashMap;
import java.util.Map;
import com.btmatthews.maven.plugins.inmemdb.Database;
import com.btmatthews.maven.plugins.inmemdb.Loader;
import com.btmatthews.maven.plugins.inmemdb.MessageUtil;
import com.btmatthews.maven.plugins.inmemdb.Source;
import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger; | * @return database port number
*/
public int getPort() {
return port;
}
/**
* Get the attributes used to connect to database
* @return attributes
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* Get the loaders that are supported for loading data or executing scripts.
*
* @return Returns an array of loaders.
*/
protected abstract Loader[] getLoaders();
/**
* Find the loader that supports the source file and use it to load the data
* into or execute the script against the database.
*
* @param logger Used to report errors and raise exceptions.
* @param source The source file containing data or script.
*/
@Override | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java
// public interface Database {
//
// /**
// * Find the loader that supports the source file and use it to load the data
// * into or execute the script against the database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing data or script.
// */
// void load(Logger logger, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java
// public interface Loader {
//
// /**
// * The message key for the error reported when a source file cannot be read.
// */
// String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file";
//
// /**
// * The message key for the error reported when a source file cannot be processed.
// */
// String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file";
//
// /**
// * Determine whether or not the data or script can be loaded or executed.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing the data or script.
// * @return <ul>
// * <li><code>true</code> if the data or script can be loaded or executed.</li>
// * <li><code>false</code>if the data or script cannot be loaded or executed.</li>
// * </ul>
// */
// boolean isSupported(Logger logger, Source source);
//
// /**
// * Load data into or execute a script against the in-memory database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param database The in-memory database.
// * @param source The source file containing the data or script.
// */
// void load(Logger logger, Database database, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/MessageUtil.java
// public final class MessageUtil {
//
// /**
// * The base name of the message resource bundle.
// */
// private static final String BUNDLE_NAME = "com.btmatthews.maven.plugins.inmemdb.messages";
//
// /**
// * The message resource bundle.
// */
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// /**
// * Make the constructor private because this class only offers static utility methods.
// */
// private MessageUtil() {
// }
//
// /**
// * Retrieve the message pattern for a given message key from the resource
// * bundle and format the message replacing the place holders with the
// * message arguments.
// *
// * @param messageKey The key of the message in the resource bundle.
// * @param arguments The message arguments.
// * @return The expanded message string.
// */
// public static String getMessage(final String messageKey,
// final Object... arguments) {
// final String messagePattern = RESOURCE_BUNDLE.getString(messageKey);
// return MessageFormat.format(messagePattern, arguments);
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/AbstractDatabase.java
import java.util.HashMap;
import java.util.Map;
import com.btmatthews.maven.plugins.inmemdb.Database;
import com.btmatthews.maven.plugins.inmemdb.Loader;
import com.btmatthews.maven.plugins.inmemdb.MessageUtil;
import com.btmatthews.maven.plugins.inmemdb.Source;
import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger;
* @return database port number
*/
public int getPort() {
return port;
}
/**
* Get the attributes used to connect to database
* @return attributes
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* Get the loaders that are supported for loading data or executing scripts.
*
* @return Returns an array of loaders.
*/
protected abstract Loader[] getLoaders();
/**
* Find the loader that supports the source file and use it to load the data
* into or execute the script against the database.
*
* @param logger Used to report errors and raise exceptions.
* @param source The source file containing data or script.
*/
@Override | public final void load(final Logger logger, final Source source) { |
bmatthews68/inmemdb-maven-plugin | src/main/java/com/btmatthews/maven/plugins/inmemdb/db/AbstractDatabase.java | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java
// public interface Database {
//
// /**
// * Find the loader that supports the source file and use it to load the data
// * into or execute the script against the database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing data or script.
// */
// void load(Logger logger, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java
// public interface Loader {
//
// /**
// * The message key for the error reported when a source file cannot be read.
// */
// String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file";
//
// /**
// * The message key for the error reported when a source file cannot be processed.
// */
// String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file";
//
// /**
// * Determine whether or not the data or script can be loaded or executed.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing the data or script.
// * @return <ul>
// * <li><code>true</code> if the data or script can be loaded or executed.</li>
// * <li><code>false</code>if the data or script cannot be loaded or executed.</li>
// * </ul>
// */
// boolean isSupported(Logger logger, Source source);
//
// /**
// * Load data into or execute a script against the in-memory database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param database The in-memory database.
// * @param source The source file containing the data or script.
// */
// void load(Logger logger, Database database, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/MessageUtil.java
// public final class MessageUtil {
//
// /**
// * The base name of the message resource bundle.
// */
// private static final String BUNDLE_NAME = "com.btmatthews.maven.plugins.inmemdb.messages";
//
// /**
// * The message resource bundle.
// */
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// /**
// * Make the constructor private because this class only offers static utility methods.
// */
// private MessageUtil() {
// }
//
// /**
// * Retrieve the message pattern for a given message key from the resource
// * bundle and format the message replacing the place holders with the
// * message arguments.
// *
// * @param messageKey The key of the message in the resource bundle.
// * @param arguments The message arguments.
// * @return The expanded message string.
// */
// public static String getMessage(final String messageKey,
// final Object... arguments) {
// final String messagePattern = RESOURCE_BUNDLE.getString(messageKey);
// return MessageFormat.format(messagePattern, arguments);
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
| import java.util.HashMap;
import java.util.Map;
import com.btmatthews.maven.plugins.inmemdb.Database;
import com.btmatthews.maven.plugins.inmemdb.Loader;
import com.btmatthews.maven.plugins.inmemdb.MessageUtil;
import com.btmatthews.maven.plugins.inmemdb.Source;
import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger; | public int getPort() {
return port;
}
/**
* Get the attributes used to connect to database
* @return attributes
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* Get the loaders that are supported for loading data or executing scripts.
*
* @return Returns an array of loaders.
*/
protected abstract Loader[] getLoaders();
/**
* Find the loader that supports the source file and use it to load the data
* into or execute the script against the database.
*
* @param logger Used to report errors and raise exceptions.
* @param source The source file containing data or script.
*/
@Override
public final void load(final Logger logger, final Source source) {
if (source == null) { | // Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Database.java
// public interface Database {
//
// /**
// * Find the loader that supports the source file and use it to load the data
// * into or execute the script against the database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing data or script.
// */
// void load(Logger logger, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Loader.java
// public interface Loader {
//
// /**
// * The message key for the error reported when a source file cannot be read.
// */
// String CANNOT_READ_SOURCE_FILE = "cannot_read_source_file";
//
// /**
// * The message key for the error reported when a source file cannot be processed.
// */
// String ERROR_PROCESSING_SOURCE_FILE = "error_processing_source_file";
//
// /**
// * Determine whether or not the data or script can be loaded or executed.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param source The source file containing the data or script.
// * @return <ul>
// * <li><code>true</code> if the data or script can be loaded or executed.</li>
// * <li><code>false</code>if the data or script cannot be loaded or executed.</li>
// * </ul>
// */
// boolean isSupported(Logger logger, Source source);
//
// /**
// * Load data into or execute a script against the in-memory database.
// *
// * @param logger Used to report errors and raise exceptions.
// * @param database The in-memory database.
// * @param source The source file containing the data or script.
// */
// void load(Logger logger, Database database, Source source);
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/MessageUtil.java
// public final class MessageUtil {
//
// /**
// * The base name of the message resource bundle.
// */
// private static final String BUNDLE_NAME = "com.btmatthews.maven.plugins.inmemdb.messages";
//
// /**
// * The message resource bundle.
// */
// private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
//
// /**
// * Make the constructor private because this class only offers static utility methods.
// */
// private MessageUtil() {
// }
//
// /**
// * Retrieve the message pattern for a given message key from the resource
// * bundle and format the message replacing the place holders with the
// * message arguments.
// *
// * @param messageKey The key of the message in the resource bundle.
// * @param arguments The message arguments.
// * @return The expanded message string.
// */
// public static String getMessage(final String messageKey,
// final Object... arguments) {
// final String messagePattern = RESOURCE_BUNDLE.getString(messageKey);
// return MessageFormat.format(messagePattern, arguments);
// }
// }
//
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/Source.java
// public interface Source {
//
// /**
// * Get the source file that contains the DDL/DML script or DBUnit data set.
// *
// * @return The source file.
// */
// String getSourceFile();
//
// /**
// * Determine if the table names in the source file are fully qualified.
// *
// * @return <ul>
// * <li>{@link Boolean#TRUE} if the table names are fully qualified.</li>
// * <li>{@link Boolean#FALSE} if the table names are not fully qualified.</li>
// * </ul>
// */
// Boolean getQualifiedTableNames();
// }
// Path: src/main/java/com/btmatthews/maven/plugins/inmemdb/db/AbstractDatabase.java
import java.util.HashMap;
import java.util.Map;
import com.btmatthews.maven.plugins.inmemdb.Database;
import com.btmatthews.maven.plugins.inmemdb.Loader;
import com.btmatthews.maven.plugins.inmemdb.MessageUtil;
import com.btmatthews.maven.plugins.inmemdb.Source;
import com.btmatthews.utils.monitor.AbstractServer;
import com.btmatthews.utils.monitor.Logger;
public int getPort() {
return port;
}
/**
* Get the attributes used to connect to database
* @return attributes
*/
public Map<String, String> getAttributes() {
return attributes;
}
/**
* Get the loaders that are supported for loading data or executing scripts.
*
* @return Returns an array of loaders.
*/
protected abstract Loader[] getLoaders();
/**
* Find the loader that supports the source file and use it to load the data
* into or execute the script against the database.
*
* @param logger Used to report errors and raise exceptions.
* @param source The source file containing data or script.
*/
@Override
public final void load(final Logger logger, final Source source) {
if (source == null) { | final String message = MessageUtil.getMessage(UNSUPPORTED_FILE_TYPE, "null"); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
| import br.ufpe.cin.groundhog.GroundhogException; | package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Factory class that creates a specific {@link Format}
*
* @author ghlp
* @since 0.0.1
*/
public class FormaterFactory {
/**
* Factory method to create a {@link Formater} object
* @param formater
* @return
*/
public static Formater get(Class<? extends Formater> formater) {
try {
return formater.newInstance();
} catch (Exception e) {
String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName()); | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
import br.ufpe.cin.groundhog.GroundhogException;
package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Factory class that creates a specific {@link Format}
*
* @author ghlp
* @since 0.0.1
*/
public class FormaterFactory {
/**
* Factory method to create a {@link Formater} object
* @param formater
* @return
*/
public static Formater get(Class<? extends Formater> formater) {
try {
return formater.newInstance();
} catch (Exception e) {
String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName()); | throw new GroundhogException(msg, e); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/Commit.java | // Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.util.Date;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.gson.annotations.SerializedName;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
import org.mongodb.morphia.annotations.Reference; | */
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* Informs the project to which the commit belongs
* @return a {@link Project} object
*/
public Project getProject() {
return this.project;
}
public void setProject(Project project) {
this.project = project;
}
/**
* Informs the date when the commit was done
* @return a {@link Date} object
*/
public Date getCommitDate() {
return this.commitDate;
}
public void setCommitDate(String date) { | // Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/Commit.java
import java.util.Date;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.gson.annotations.SerializedName;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
import org.mongodb.morphia.annotations.Reference;
*/
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* Informs the project to which the commit belongs
* @return a {@link Project} object
*/
public Project getProject() {
return this.project;
}
public void setProject(Project project) {
this.project = project;
}
/**
* Informs the date when the commit was done
* @return a {@link Date} object
*/
public Date getCommitDate() {
return this.commitDate;
}
public void setCommitDate(String date) { | Date createAtDate = new Dates("yyyy-MM-dd HH:mm:ss").format(date.replaceAll("T", " ").replace("Z", "")); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/CmdOptions.java | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
| import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import br.ufpe.cin.groundhog.GroundhogException;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException; |
public JsonInputFile getInputFile() {
return input;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getGitHubOauthAcessToken() {
return gitHubOauthAcessToken;
}
public void setGitHubOauthAcessToken(String gitHubOauthAcessToken) {
this.gitHubOauthAcessToken = gitHubOauthAcessToken;
}
@Option(name = "-in", usage = "all inputs together in one json file")
public void setInputFile(File inputFile) {
try {
List<String> lines = Files.readLines(inputFile,
Charset.defaultCharset());
String json = Joiner.on(" ").join(lines);
JsonInputFile args = new Gson().fromJson(json, JsonInputFile.class);
this.input = args;
} catch (JsonSyntaxException e) { | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/CmdOptions.java
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import br.ufpe.cin.groundhog.GroundhogException;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public JsonInputFile getInputFile() {
return input;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getGitHubOauthAcessToken() {
return gitHubOauthAcessToken;
}
public void setGitHubOauthAcessToken(String gitHubOauthAcessToken) {
this.gitHubOauthAcessToken = gitHubOauthAcessToken;
}
@Option(name = "-in", usage = "all inputs together in one json file")
public void setInputFile(File inputFile) {
try {
List<String> lines = Files.readLines(inputFile,
Charset.defaultCharset());
String json = Joiner.on(" ").join(lines);
JsonInputFile args = new Gson().fromJson(json, JsonInputFile.class);
this.input = args;
} catch (JsonSyntaxException e) { | throw new GroundhogException( |
spgroup/groundhog | src/java/test/br/ufpe/cin/groundhog/search/UrlBuilderTest.java | // Path: src/java/main/br/ufpe/cin/groundhog/search/UrlBuilder.java
// enum GithubAPI {
// LEGACY_V2 {
// @Override
// public String baseForm() {
// return String.format("%slegacy/repos/search/", ROOT.baseForm());
// }
// },
// ROOT {
// @Override
// public String baseForm() {
// return "https://api.github.com/";
// }
// },
// REPOSITORIES {
// @Override
// public String baseForm() {
// return String.format("%srepositories", ROOT.baseForm());
// }
// },
// USERS {
// @Override
// public String baseForm() {
// return "https://api.github.com/users/";
// }
// };
//
// public abstract String baseForm();
// }
| import org.junit.Assert;
import org.junit.Test;
import br.ufpe.cin.groundhog.search.UrlBuilder.GithubAPI; | package br.ufpe.cin.groundhog.search;
public class UrlBuilderTest {
private UrlBuilder builder = new UrlBuilder("fake");
@Test
public void getProjectUrlV2() { | // Path: src/java/main/br/ufpe/cin/groundhog/search/UrlBuilder.java
// enum GithubAPI {
// LEGACY_V2 {
// @Override
// public String baseForm() {
// return String.format("%slegacy/repos/search/", ROOT.baseForm());
// }
// },
// ROOT {
// @Override
// public String baseForm() {
// return "https://api.github.com/";
// }
// },
// REPOSITORIES {
// @Override
// public String baseForm() {
// return String.format("%srepositories", ROOT.baseForm());
// }
// },
// USERS {
// @Override
// public String baseForm() {
// return "https://api.github.com/users/";
// }
// };
//
// public abstract String baseForm();
// }
// Path: src/java/test/br/ufpe/cin/groundhog/search/UrlBuilderTest.java
import org.junit.Assert;
import org.junit.Test;
import br.ufpe.cin.groundhog.search.UrlBuilder.GithubAPI;
package br.ufpe.cin.groundhog.search;
public class UrlBuilderTest {
private UrlBuilder builder = new UrlBuilder("fake");
@Test
public void getProjectUrlV2() { | String searchUrl = builder.uses(GithubAPI.LEGACY_V2) |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java | // Path: src/java/main/br/ufpe/cin/groundhog/parser/ParserException.java
// public class ParserException extends GroundhogException {
//
// /**
// *
// */
// private static final long serialVersionUID = 2115582632203381099L;
//
// public ParserException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public ParserException() {
// super();
// }
//
// public ParserException(String msg) {
// super(msg);
// }
//
// public ParserException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/MutableInt.java
// public class MutableInt {
// int value;
//
// public MutableInt() {
// value = 1;
// }
//
// public MutableInt(int value) {
// this.value = value;
// }
//
// public void increment() {
// ++value;
// }
//
// public int get() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.valueOf(value);
// }
// }
| import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import au.com.bytecode.opencsv.CSVWriter;
import br.ufpe.cin.groundhog.parser.ParserException;
import br.ufpe.cin.groundhog.parser.java.MutableInt; | package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Creates the CSV representation of the extracted metrics The output file
* groups data associated with each metric. Each metric has a set of entry value
* that are printed one per line
*
* @author drn2
* @since 0.0.1
*/
public class CSVFormater extends Formater {
@Override | // Path: src/java/main/br/ufpe/cin/groundhog/parser/ParserException.java
// public class ParserException extends GroundhogException {
//
// /**
// *
// */
// private static final long serialVersionUID = 2115582632203381099L;
//
// public ParserException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public ParserException() {
// super();
// }
//
// public ParserException(String msg) {
// super(msg);
// }
//
// public ParserException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/MutableInt.java
// public class MutableInt {
// int value;
//
// public MutableInt() {
// value = 1;
// }
//
// public MutableInt(int value) {
// this.value = value;
// }
//
// public void increment() {
// ++value;
// }
//
// public int get() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.valueOf(value);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import au.com.bytecode.opencsv.CSVWriter;
import br.ufpe.cin.groundhog.parser.ParserException;
import br.ufpe.cin.groundhog.parser.java.MutableInt;
package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Creates the CSV representation of the extracted metrics The output file
* groups data associated with each metric. Each metric has a set of entry value
* that are printed one per line
*
* @author drn2
* @since 0.0.1
*/
public class CSVFormater extends Formater {
@Override | public String format(HashMap<String, HashMap<String, MutableInt>> object) { |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java | // Path: src/java/main/br/ufpe/cin/groundhog/parser/ParserException.java
// public class ParserException extends GroundhogException {
//
// /**
// *
// */
// private static final long serialVersionUID = 2115582632203381099L;
//
// public ParserException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public ParserException() {
// super();
// }
//
// public ParserException(String msg) {
// super(msg);
// }
//
// public ParserException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/MutableInt.java
// public class MutableInt {
// int value;
//
// public MutableInt() {
// value = 1;
// }
//
// public MutableInt(int value) {
// this.value = value;
// }
//
// public void increment() {
// ++value;
// }
//
// public int get() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.valueOf(value);
// }
// }
| import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import au.com.bytecode.opencsv.CSVWriter;
import br.ufpe.cin.groundhog.parser.ParserException;
import br.ufpe.cin.groundhog.parser.java.MutableInt; | package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Creates the CSV representation of the extracted metrics The output file
* groups data associated with each metric. Each metric has a set of entry value
* that are printed one per line
*
* @author drn2
* @since 0.0.1
*/
public class CSVFormater extends Formater {
@Override
public String format(HashMap<String, HashMap<String, MutableInt>> object) {
StringWriter result = new StringWriter();
try {
CSVWriter writer = new CSVWriter(result, ';');
writer.writeNext(new String[] { "Metric", "Entry", "Value" });
for (String metric : object.keySet()) {
HashMap<String, MutableInt> counter = object.get(metric);
for (Entry<String, MutableInt> entry : counter.entrySet()) {
writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
}
}
writer.flush();
writer.close();
return result.toString();
} catch (IOException e) {
e.printStackTrace(); | // Path: src/java/main/br/ufpe/cin/groundhog/parser/ParserException.java
// public class ParserException extends GroundhogException {
//
// /**
// *
// */
// private static final long serialVersionUID = 2115582632203381099L;
//
// public ParserException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public ParserException() {
// super();
// }
//
// public ParserException(String msg) {
// super(msg);
// }
//
// public ParserException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/MutableInt.java
// public class MutableInt {
// int value;
//
// public MutableInt() {
// value = 1;
// }
//
// public MutableInt(int value) {
// this.value = value;
// }
//
// public void increment() {
// ++value;
// }
//
// public int get() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.valueOf(value);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import au.com.bytecode.opencsv.CSVWriter;
import br.ufpe.cin.groundhog.parser.ParserException;
import br.ufpe.cin.groundhog.parser.java.MutableInt;
package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Creates the CSV representation of the extracted metrics The output file
* groups data associated with each metric. Each metric has a set of entry value
* that are printed one per line
*
* @author drn2
* @since 0.0.1
*/
public class CSVFormater extends Formater {
@Override
public String format(HashMap<String, HashMap<String, MutableInt>> object) {
StringWriter result = new StringWriter();
try {
CSVWriter writer = new CSVWriter(result, ';');
writer.writeNext(new String[] { "Metric", "Entry", "Value" });
for (String metric : object.keySet()) {
HashMap<String, MutableInt> counter = object.get(metric);
for (Entry<String, MutableInt> entry : counter.entrySet()) {
writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
}
}
writer.flush();
writer.close();
return result.toString();
} catch (IOException e) {
e.printStackTrace(); | throw new ParserException(); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/scmclient/GitClient.java | // Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.CheckoutConflictException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.errors.StopWalkException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.gitective.core.CommitFinder;
import org.gitective.core.filter.commit.AllCommitFilter;
import org.gitective.core.filter.commit.AndCommitFilter;
import org.gitective.core.filter.commit.CommitCountFilter;
import org.gitective.core.filter.commit.CommitFilter;
import org.gitective.core.filter.commit.CommitterDateFilter;
import br.ufpe.cin.groundhog.util.Dates; | * @throws EmptyProjectAtDateException
*/
public void checkout(File repositoryFolder, Date date) throws IOException,
RefAlreadyExistsException, InvalidRefNameException,
CheckoutConflictException, GitAPIException,
EmptyProjectAtDateException {
Git git = Git.open(repositoryFolder);
Repository rep = git.getRepository();
CommitFinder finder = new CommitFinder(rep);
final List<RevCommit> commits = new ArrayList<RevCommit>();
finder.setFilter(new CommitterDateFilter(date).negate());
AllCommitFilter filter = new AllCommitFilter() {
@Override
public boolean include(RevWalk walker, RevCommit commit)
throws IOException {
boolean include = super.include(walker, commit);
if (include) {
commits.add(commit);
}
return include;
}
};
finder.setMatcher(filter);
finder.find();
if (commits.size() == 0) {
rep.close();
throw new EmptyProjectAtDateException( | // Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/scmclient/GitClient.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.CheckoutConflictException;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.errors.StopWalkException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.revwalk.filter.RevFilter;
import org.gitective.core.CommitFinder;
import org.gitective.core.filter.commit.AllCommitFilter;
import org.gitective.core.filter.commit.AndCommitFilter;
import org.gitective.core.filter.commit.CommitCountFilter;
import org.gitective.core.filter.commit.CommitFilter;
import org.gitective.core.filter.commit.CommitterDateFilter;
import br.ufpe.cin.groundhog.util.Dates;
* @throws EmptyProjectAtDateException
*/
public void checkout(File repositoryFolder, Date date) throws IOException,
RefAlreadyExistsException, InvalidRefNameException,
CheckoutConflictException, GitAPIException,
EmptyProjectAtDateException {
Git git = Git.open(repositoryFolder);
Repository rep = git.getRepository();
CommitFinder finder = new CommitFinder(rep);
final List<RevCommit> commits = new ArrayList<RevCommit>();
finder.setFilter(new CommitterDateFilter(date).negate());
AllCommitFilter filter = new AllCommitFilter() {
@Override
public boolean include(RevWalk walker, RevCommit commit)
throws IOException {
boolean include = super.include(walker, commit);
if (include) {
commits.add(commit);
}
return include;
}
};
finder.setMatcher(filter);
finder.find();
if (commits.size() == 0) {
rep.close();
throw new EmptyProjectAtDateException( | new Dates("yyyy-MM-dd").format(date)); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/database/GroundhogDB.java | // Path: src/java/main/br/ufpe/cin/groundhog/GitHubEntity.java
// public abstract class GitHubEntity {
//
// /**
// * Returns the Entity's API URL
// * @return a String
// */
// public abstract String getURL();
// }
| import java.net.UnknownHostException;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import br.ufpe.cin.groundhog.GitHubEntity;
import com.mongodb.MongoClient; | package br.ufpe.cin.groundhog.database;
/**
* This class represents the database interface for Groundhog data persistence via MongoDB
* Read more at https://github.com/spgroup/groundhog#database-support
*
* @author Rodrigo Alves
*
*/
public class GroundhogDB {
private final String dbName;
private final MongoClient mongo;
private final Datastore datastore;
public GroundhogDB(String host, String dbName) throws UnknownHostException {
this.dbName = dbName;
this.mongo = new MongoClient(host);
this.datastore = new Morphia().createDatastore(this.mongo, dbName);
}
public GroundhogDB(MongoClient mongo, String dbName) throws UnknownHostException {
this.dbName = dbName;
this.mongo = null;
this.datastore = new Morphia().createDatastore(mongo, dbName);
}
| // Path: src/java/main/br/ufpe/cin/groundhog/GitHubEntity.java
// public abstract class GitHubEntity {
//
// /**
// * Returns the Entity's API URL
// * @return a String
// */
// public abstract String getURL();
// }
// Path: src/java/main/br/ufpe/cin/groundhog/database/GroundhogDB.java
import java.net.UnknownHostException;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import br.ufpe.cin.groundhog.GitHubEntity;
import com.mongodb.MongoClient;
package br.ufpe.cin.groundhog.database;
/**
* This class represents the database interface for Groundhog data persistence via MongoDB
* Read more at https://github.com/spgroup/groundhog#database-support
*
* @author Rodrigo Alves
*
*/
public class GroundhogDB {
private final String dbName;
private final MongoClient mongo;
private final Datastore datastore;
public GroundhogDB(String host, String dbName) throws UnknownHostException {
this.dbName = dbName;
this.mongo = new MongoClient(host);
this.datastore = new Morphia().createDatastore(this.mongo, dbName);
}
public GroundhogDB(MongoClient mongo, String dbName) throws UnknownHostException {
this.dbName = dbName;
this.mongo = null;
this.datastore = new Morphia().createDatastore(mongo, dbName);
}
| public static void query(GitHubEntity entity, String params) { |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/parser/java/JavaParser.java | // Path: src/java/main/br/ufpe/cin/groundhog/parser/Parser.java
// public interface Parser<T> {
//
// public T parser();
//
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/ParserException.java
// public class ParserException extends GroundhogException {
//
// /**
// *
// */
// private static final long serialVersionUID = 2115582632203381099L;
//
// public ParserException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public ParserException() {
// super();
// }
//
// public ParserException(String msg) {
// super(msg);
// }
//
// public ParserException(Throwable cause) {
// super(cause);
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import br.ufpe.cin.groundhog.parser.Parser;
import br.ufpe.cin.groundhog.parser.ParserException; | StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
List<String> options = new ArrayList<String>();
options.add("-g:none"); // Do not generate any debugging information
options.add("-nowarn"); // Disable warning messages
options.add("-implicit:none"); // Suppress class file generation
options.add("-proc:only"); // Only annotation processing is done, without any subsequent compilation
CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
CodeAnalyzerProcessor processor = new CodeAnalyzerProcessor();
task.setProcessors(Arrays.asList(processor));
task.call();
fileManager.close();
return processor.getCounters();
}
/**
* Parses all Java source files inside this.folder and returns extracted
* metrics.
*
* @return a map of metrics to another map of metric value and count.
*/
public HashMap<String, HashMap<String, MutableInt>> parser() {
logger.info("Running java parser..");
searchForJavaFiles(folder);
try {
return invokeProcessor();
} catch (IOException e) { | // Path: src/java/main/br/ufpe/cin/groundhog/parser/Parser.java
// public interface Parser<T> {
//
// public T parser();
//
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/ParserException.java
// public class ParserException extends GroundhogException {
//
// /**
// *
// */
// private static final long serialVersionUID = 2115582632203381099L;
//
// public ParserException(String msg, Throwable cause) {
// super(msg, cause);
// }
//
// public ParserException() {
// super();
// }
//
// public ParserException(String msg) {
// super(msg);
// }
//
// public ParserException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/JavaParser.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import br.ufpe.cin.groundhog.parser.Parser;
import br.ufpe.cin.groundhog.parser.ParserException;
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(filesList);
List<String> options = new ArrayList<String>();
options.add("-g:none"); // Do not generate any debugging information
options.add("-nowarn"); // Disable warning messages
options.add("-implicit:none"); // Suppress class file generation
options.add("-proc:only"); // Only annotation processing is done, without any subsequent compilation
CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
CodeAnalyzerProcessor processor = new CodeAnalyzerProcessor();
task.setProcessors(Arrays.asList(processor));
task.call();
fileManager.close();
return processor.getCounters();
}
/**
* Parses all Java source files inside this.folder and returns extracted
* metrics.
*
* @return a map of metrics to another map of metric value and count.
*/
public HashMap<String, HashMap<String, MutableInt>> parser() {
logger.info("Running java parser..");
searchForJavaFiles(folder);
try {
return invokeProcessor();
} catch (IOException e) { | throw new ParserException(e.getMessage()); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/extractor/DefaultUncompressor.java | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import lzma.sdk.lzma.Decoder;
import lzma.streams.LzmaInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import br.ufpe.cin.groundhog.GroundhogException; | package br.ufpe.cin.groundhog.extractor;
/**
* The default file uncompressor in Groundhog
* @author fjsj
* @deprecated
*/
public class DefaultUncompressor {
private static DefaultUncompressor instance;
public static DefaultUncompressor getInstance() {
if (instance == null) {
instance = new DefaultUncompressor();
}
return instance;
}
private DefaultUncompressor() {
}
/**
* The compressed file extractor method that takes a compressed file and a destination folder
* and extracts the given file according to its compression format. The supported formats are declared
* in the formats class.
* @param file the compressed file to be extracted
* @param destinationFolder the folder to which the extracted file will be moved to
*/
public void uncompress(File file, File destinationFolder) {
String name = file.getName();
try {
if (name.endsWith(".zip")) {
ZipUncompressor.extract(file, destinationFolder);
} else if (name.endsWith(".tar.gz") || name.endsWith(".tgz")) {
TarUncompressor.extract(file, new GZIPInputStream(new FileInputStream(file)), destinationFolder);
} else if (name.endsWith(".tar.bz2") || name.endsWith(".tar.bzip2") || name.endsWith(".tbz2")) {
TarUncompressor.extract(file, new BZip2CompressorInputStream(new FileInputStream(file)), destinationFolder);
} else if (name.endsWith(".tar.lzma") || name.endsWith(".tlzma")) {
TarUncompressor.extract(file, new LzmaInputStream(new FileInputStream(file), new Decoder()), destinationFolder);
} else if (name.endsWith(".rar")) {
RarUncompressor.extract(file, destinationFolder);
} else if (name.endsWith(".tar")) {
TarUncompressor.extract(file, new FileInputStream(file), destinationFolder);
}
} catch (IOException e) {
e.printStackTrace(); | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/extractor/DefaultUncompressor.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import lzma.sdk.lzma.Decoder;
import lzma.streams.LzmaInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import br.ufpe.cin.groundhog.GroundhogException;
package br.ufpe.cin.groundhog.extractor;
/**
* The default file uncompressor in Groundhog
* @author fjsj
* @deprecated
*/
public class DefaultUncompressor {
private static DefaultUncompressor instance;
public static DefaultUncompressor getInstance() {
if (instance == null) {
instance = new DefaultUncompressor();
}
return instance;
}
private DefaultUncompressor() {
}
/**
* The compressed file extractor method that takes a compressed file and a destination folder
* and extracts the given file according to its compression format. The supported formats are declared
* in the formats class.
* @param file the compressed file to be extracted
* @param destinationFolder the folder to which the extracted file will be moved to
*/
public void uncompress(File file, File destinationFolder) {
String name = file.getName();
try {
if (name.endsWith(".zip")) {
ZipUncompressor.extract(file, destinationFolder);
} else if (name.endsWith(".tar.gz") || name.endsWith(".tgz")) {
TarUncompressor.extract(file, new GZIPInputStream(new FileInputStream(file)), destinationFolder);
} else if (name.endsWith(".tar.bz2") || name.endsWith(".tar.bzip2") || name.endsWith(".tbz2")) {
TarUncompressor.extract(file, new BZip2CompressorInputStream(new FileInputStream(file)), destinationFolder);
} else if (name.endsWith(".tar.lzma") || name.endsWith(".tlzma")) {
TarUncompressor.extract(file, new LzmaInputStream(new FileInputStream(file), new Decoder()), destinationFolder);
} else if (name.endsWith(".rar")) {
RarUncompressor.extract(file, destinationFolder);
} else if (name.endsWith(".tar")) {
TarUncompressor.extract(file, new FileInputStream(file), destinationFolder);
}
} catch (IOException e) {
e.printStackTrace(); | throw new GroundhogException("Error when trying to extract the source code", e); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/util/FileUtil.java | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import br.ufpe.cin.groundhog.GroundhogException;
import com.google.common.io.Files; | package br.ufpe.cin.groundhog.util;
/**
* General utilities class for file operations
*
* @author fjsj, gustavopinto, Rodrigo Alves
*/
public class FileUtil {
private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
private static FileUtil instance;
private List<File> createdTempDirs;
public static FileUtil getInstance() {
if (instance == null) {
instance = new FileUtil();
}
return instance;
}
private FileUtil() {
this.createdTempDirs = new ArrayList<File>();
}
/**
*
* @return A File object representing the created temporary directory
*/
public synchronized File createTempDir() {
try {
File tempDir = Files.createTempDir();
this.createdTempDirs.add(tempDir);
return tempDir;
} catch (Exception e) {
e.printStackTrace();
String error = "Unable to create temporary directory. Are you running groundhog with admin privileges?";
logger.error(error); | // Path: src/java/main/br/ufpe/cin/groundhog/GroundhogException.java
// public class GroundhogException extends RuntimeException {
// private static final long serialVersionUID = -3563928567447310893L;
//
// public GroundhogException() {
// super();
// }
//
// public GroundhogException(String msg) {
// super(msg);
// }
//
// public GroundhogException(Throwable cause) {
// super(cause);
// }
//
// public GroundhogException(String msg, Throwable cause) {
// super(msg, cause);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/util/FileUtil.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import br.ufpe.cin.groundhog.GroundhogException;
import com.google.common.io.Files;
package br.ufpe.cin.groundhog.util;
/**
* General utilities class for file operations
*
* @author fjsj, gustavopinto, Rodrigo Alves
*/
public class FileUtil {
private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
private static FileUtil instance;
private List<File> createdTempDirs;
public static FileUtil getInstance() {
if (instance == null) {
instance = new FileUtil();
}
return instance;
}
private FileUtil() {
this.createdTempDirs = new ArrayList<File>();
}
/**
*
* @return A File object representing the created temporary directory
*/
public synchronized File createTempDir() {
try {
File tempDir = Files.createTempDir();
this.createdTempDirs.add(tempDir);
return tempDir;
} catch (Exception e) {
e.printStackTrace();
String error = "Unable to create temporary directory. Are you running groundhog with admin privileges?";
logger.error(error); | throw new GroundhogException(error); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists; | package br.ufpe.cin.groundhog.main;
/**
* This class represents the parameters passed via command line.
* @author gustavopinto
*/
public final class JsonInputFile {
private String forge;
private String dest;
private String out;
private String datetime;
private String nprojects;
private String outputformat;
private Search search;
private String gitHubOauthAcessToken;
public JsonInputFile(CmdOptions opt) {
super();
this.forge = opt.getForge().name();
this.dest = opt.getDestinationFolder() != null ? opt.getDestinationFolder().getAbsolutePath() : null;
this.out = opt.getMetricsFolder().getAbsolutePath();
this.datetime = opt.getDatetime();
this.nprojects = opt.getnProjects();
this.outputformat = opt.getMetricsFormat();
this.search = new Search(opt.getArguments(), opt.getUsername());
this.gitHubOauthAcessToken = opt.getGitHubOauthAcessToken();
}
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
} | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java
import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
package br.ufpe.cin.groundhog.main;
/**
* This class represents the parameters passed via command line.
* @author gustavopinto
*/
public final class JsonInputFile {
private String forge;
private String dest;
private String out;
private String datetime;
private String nprojects;
private String outputformat;
private Search search;
private String gitHubOauthAcessToken;
public JsonInputFile(CmdOptions opt) {
super();
this.forge = opt.getForge().name();
this.dest = opt.getDestinationFolder() != null ? opt.getDestinationFolder().getAbsolutePath() : null;
this.out = opt.getMetricsFolder().getAbsolutePath();
this.datetime = opt.getDatetime();
this.nprojects = opt.getnProjects();
this.outputformat = opt.getMetricsFormat();
this.search = new Search(opt.getArguments(), opt.getUsername());
this.gitHubOauthAcessToken = opt.getGitHubOauthAcessToken();
}
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
} | throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists; | this.dest = opt.getDestinationFolder() != null ? opt.getDestinationFolder().getAbsolutePath() : null;
this.out = opt.getMetricsFolder().getAbsolutePath();
this.datetime = opt.getDatetime();
this.nprojects = opt.getnProjects();
this.outputformat = opt.getMetricsFormat();
this.search = new Search(opt.getArguments(), opt.getUsername());
this.gitHubOauthAcessToken = opt.getGitHubOauthAcessToken();
}
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() { | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java
import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
this.dest = opt.getDestinationFolder() != null ? opt.getDestinationFolder().getAbsolutePath() : null;
this.out = opt.getMetricsFolder().getAbsolutePath();
this.datetime = opt.getDatetime();
this.nprojects = opt.getnProjects();
this.outputformat = opt.getMetricsFormat();
this.search = new Search(opt.getArguments(), opt.getUsername());
this.gitHubOauthAcessToken = opt.getGitHubOauthAcessToken();
}
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() { | return new Dates("yyyy-MM-dd HH:mm").format(this.datetime); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists; | }
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
| // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java
import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
}
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
| public Formater getOutputformat() { |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists; | //TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
public Formater getOutputformat() {
if(this.outputformat.equals("json")) { | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java
import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
public Formater getOutputformat() {
if(this.outputformat.equals("json")) { | return FormaterFactory.get(JSONFormater.class); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists; | //TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
public Formater getOutputformat() {
if(this.outputformat.equals("json")) { | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java
import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
//TODO: this should be discovered dynamically
public SupportedForge getForge() {
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
public Formater getOutputformat() {
if(this.outputformat.equals("json")) { | return FormaterFactory.get(JSONFormater.class); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists; | if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
public Formater getOutputformat() {
if(this.outputformat.equals("json")) {
return FormaterFactory.get(JSONFormater.class);
} | // Path: src/java/main/br/ufpe/cin/groundhog/codehistory/UnsupportedForgeException.java
// public class UnsupportedForgeException extends GroundhogException {
// private static final long serialVersionUID = 1L;
//
// public UnsupportedForgeException(String msg) {
// super(msg);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/CSVFormater.java
// public class CSVFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// StringWriter result = new StringWriter();
// try {
// CSVWriter writer = new CSVWriter(result, ';');
// writer.writeNext(new String[] { "Metric", "Entry", "Value" });
// for (String metric : object.keySet()) {
// HashMap<String, MutableInt> counter = object.get(metric);
// for (Entry<String, MutableInt> entry : counter.entrySet()) {
// writer.writeNext(new String[] { metric, entry.getKey(), entry.getValue().toString() });
// }
// }
// writer.flush();
// writer.close();
// return result.toString();
// } catch (IOException e) {
// e.printStackTrace();
// throw new ParserException();
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/Formater.java
// public abstract class Formater {
//
// /**
// * Formats the metric object into a file representation. It could be
// * CSV or JSON
// *
// * @param object
// * @return
// */
// public abstract String format(HashMap<String, HashMap<String, MutableInt>> object);
//
// public String toString() {
// return getClass().getSimpleName().toLowerCase().replaceAll("formater", "");
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/FormaterFactory.java
// public class FormaterFactory {
//
// /**
// * Factory method to create a {@link Formater} object
// * @param formater
// * @return
// */
// public static Formater get(Class<? extends Formater> formater) {
// try {
// return formater.newInstance();
// } catch (Exception e) {
// String msg = String.format("I did not reconginze this output format (%s) :( I can only format in CSV or JSON", formater.getSimpleName());
// throw new GroundhogException(msg, e);
// }
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
// public class JSONFormater extends Formater {
//
// @Override
// public String format(HashMap<String, HashMap<String, MutableInt>> object) {
// Gson gson = new GsonBuilder().serializeNulls().create();
// return gson.toJson(object);
// }
// }
//
// Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/main/JsonInputFile.java
import java.io.File;
import java.util.Date;
import java.util.List;
import br.ufpe.cin.groundhog.codehistory.UnsupportedForgeException;
import br.ufpe.cin.groundhog.parser.java.formater.CSVFormater;
import br.ufpe.cin.groundhog.parser.java.formater.Formater;
import br.ufpe.cin.groundhog.parser.java.formater.FormaterFactory;
import br.ufpe.cin.groundhog.parser.java.formater.JSONFormater;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
if (forge.toLowerCase().equals("github")) {
return SupportedForge.GITHUB;
} else if (forge.equals("googlecode")) {
return SupportedForge.GOOGLECODE;
} else if (forge.equals("googlecode")) {
return SupportedForge.SOURCEFORGE;
}
throw new UnsupportedForgeException("Sorry, currently Groundhog only supports Github, Sourceforge and GoogleCode. We do not support: " + forge);
}
public File getDest() {
return new File(this.dest);
}
public File getOut() {
return new File(this.out);
}
public Date getDatetime() {
return new Dates("yyyy-MM-dd HH:mm").format(this.datetime);
}
public int getNprojects() {
return Integer.parseInt(this.nprojects);
}
public Formater getOutputformat() {
if(this.outputformat.equals("json")) {
return FormaterFactory.get(JSONFormater.class);
} | return FormaterFactory.get(CSVFormater.class); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java | // Path: src/java/main/br/ufpe/cin/groundhog/parser/java/MutableInt.java
// public class MutableInt {
// int value;
//
// public MutableInt() {
// value = 1;
// }
//
// public MutableInt(int value) {
// this.value = value;
// }
//
// public void increment() {
// ++value;
// }
//
// public int get() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.valueOf(value);
// }
// }
| import java.util.HashMap;
import br.ufpe.cin.groundhog.parser.java.MutableInt;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder; | package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Creates an object that represents the JSON result of the metrics.
*
* @return JSONObject that embodies the result
* @since 0.0.1
*/
public class JSONFormater extends Formater {
@Override | // Path: src/java/main/br/ufpe/cin/groundhog/parser/java/MutableInt.java
// public class MutableInt {
// int value;
//
// public MutableInt() {
// value = 1;
// }
//
// public MutableInt(int value) {
// this.value = value;
// }
//
// public void increment() {
// ++value;
// }
//
// public int get() {
// return value;
// }
//
// @Override
// public String toString() {
// return String.valueOf(value);
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/parser/java/formater/JSONFormater.java
import java.util.HashMap;
import br.ufpe.cin.groundhog.parser.java.MutableInt;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
package br.ufpe.cin.groundhog.parser.java.formater;
/**
* Creates an object that represents the JSON result of the metrics.
*
* @return JSONObject that embodies the result
* @since 0.0.1
*/
public class JSONFormater extends Formater {
@Override | public String format(HashMap<String, HashMap<String, MutableInt>> object) { |
spgroup/groundhog | src/java/test/br/ufpe/cin/groundhog/util/FileUtilTest.java | // Path: src/java/main/br/ufpe/cin/groundhog/util/FileUtil.java
// public class FileUtil {
//
// private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
//
//
// private static FileUtil instance;
// private List<File> createdTempDirs;
//
// public static FileUtil getInstance() {
// if (instance == null) {
// instance = new FileUtil();
// }
// return instance;
// }
//
// private FileUtil() {
// this.createdTempDirs = new ArrayList<File>();
// }
//
// /**
// *
// * @return A File object representing the created temporary directory
// */
// public synchronized File createTempDir() {
// try {
// File tempDir = Files.createTempDir();
// this.createdTempDirs.add(tempDir);
// return tempDir;
// } catch (Exception e) {
// e.printStackTrace();
// String error = "Unable to create temporary directory. Are you running groundhog with admin privileges?";
// logger.error(error);
// throw new GroundhogException(error);
// }
// }
//
// /**
// * Deletes the temporary directories used to store the downloaded the
// * projects.
// *
// * @throws IOException
// */
// public synchronized void deleteTempDirs() throws IOException {
// for (File tempDir : this.createdTempDirs) {
// if (tempDir.exists()) {
// FileUtils.deleteDirectory(tempDir);
// }
// }
// }
//
// /**
// *
// * @param file
// * the file to which the string will be written to
// * @param data
// * the string to be written to the file
// * @throws IOException
// */
// public void writeStringToFile(File file, String data) throws IOException {
// FileUtils.writeStringToFile(file, data);
// }
//
// /**
// * Takes a directory and moves it to another directory
// *
// * @param srcDir
// * the directory to be moved
// * @param destDir
// * the destination directory
// * @throws IOException
// */
// public void copyDirectory(File srcDir, File destDir) throws IOException {
// FileUtils.copyDirectory(srcDir, destDir);
// // TODO: add tests
// }
//
// public String readAllLines(File file) {
// try {
// StringBuffer buffer = new StringBuffer();
// Scanner scanner = new Scanner(file);
//
// while(scanner.hasNextLine()){
// buffer.append(scanner.nextLine());
// }
//
// scanner.close();
// return buffer.toString();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
//
// String error = String.format("Unable to read the file (%s) content", file.getAbsoluteFile());
// logger.error(error);
// throw new GroundhogException(error);
// }
// }
//
// public boolean isTextFile(final File file) {
//
// if(file.isDirectory()) {
// return false;
// }
//
// final int BUFFER_SIZE = 10 * 1024;
// boolean isText = true;
// byte[] buffer = new byte[BUFFER_SIZE];
//
// RandomAccessFile fis = null;
// try {
// fis = new RandomAccessFile(file, "r");
//
// fis.seek(0);
// final int read = fis.read(buffer);
// int lastByteTranslated = 0;
// for (int i = 0; i < read && isText; i++) {
// final byte b = buffer[i];
// int ub = b & (0xff);
// int utf8value = lastByteTranslated + ub;
// lastByteTranslated = (ub) << 8;
//
// if (ub == 0x09
// || ub == 0x0A
// || ub == 0x0C
// || ub == 0x0D
// || (ub >= 0x20 && ub <= 0x7E)
// || (ub >= 0xA0 && ub <= 0xEE)
// || (utf8value >= 0x2E2E && utf8value <= 0xC3BF)) {
//
// } else {
// isText = false;
// }
// }
// return isText;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// } finally {
// try {
// fis.close();
// } catch (final Throwable th) {
// }
// }
// }
// }
| import java.io.File;
import java.io.IOException;
import org.junit.Test;
import br.ufpe.cin.groundhog.util.FileUtil; | package br.ufpe.cin.groundhog.util;
public class FileUtilTest {
@Test
public void testIsFile() throws IOException {
File files[] = new File(".").listFiles();
for (File file : files) { | // Path: src/java/main/br/ufpe/cin/groundhog/util/FileUtil.java
// public class FileUtil {
//
// private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
//
//
// private static FileUtil instance;
// private List<File> createdTempDirs;
//
// public static FileUtil getInstance() {
// if (instance == null) {
// instance = new FileUtil();
// }
// return instance;
// }
//
// private FileUtil() {
// this.createdTempDirs = new ArrayList<File>();
// }
//
// /**
// *
// * @return A File object representing the created temporary directory
// */
// public synchronized File createTempDir() {
// try {
// File tempDir = Files.createTempDir();
// this.createdTempDirs.add(tempDir);
// return tempDir;
// } catch (Exception e) {
// e.printStackTrace();
// String error = "Unable to create temporary directory. Are you running groundhog with admin privileges?";
// logger.error(error);
// throw new GroundhogException(error);
// }
// }
//
// /**
// * Deletes the temporary directories used to store the downloaded the
// * projects.
// *
// * @throws IOException
// */
// public synchronized void deleteTempDirs() throws IOException {
// for (File tempDir : this.createdTempDirs) {
// if (tempDir.exists()) {
// FileUtils.deleteDirectory(tempDir);
// }
// }
// }
//
// /**
// *
// * @param file
// * the file to which the string will be written to
// * @param data
// * the string to be written to the file
// * @throws IOException
// */
// public void writeStringToFile(File file, String data) throws IOException {
// FileUtils.writeStringToFile(file, data);
// }
//
// /**
// * Takes a directory and moves it to another directory
// *
// * @param srcDir
// * the directory to be moved
// * @param destDir
// * the destination directory
// * @throws IOException
// */
// public void copyDirectory(File srcDir, File destDir) throws IOException {
// FileUtils.copyDirectory(srcDir, destDir);
// // TODO: add tests
// }
//
// public String readAllLines(File file) {
// try {
// StringBuffer buffer = new StringBuffer();
// Scanner scanner = new Scanner(file);
//
// while(scanner.hasNextLine()){
// buffer.append(scanner.nextLine());
// }
//
// scanner.close();
// return buffer.toString();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
//
// String error = String.format("Unable to read the file (%s) content", file.getAbsoluteFile());
// logger.error(error);
// throw new GroundhogException(error);
// }
// }
//
// public boolean isTextFile(final File file) {
//
// if(file.isDirectory()) {
// return false;
// }
//
// final int BUFFER_SIZE = 10 * 1024;
// boolean isText = true;
// byte[] buffer = new byte[BUFFER_SIZE];
//
// RandomAccessFile fis = null;
// try {
// fis = new RandomAccessFile(file, "r");
//
// fis.seek(0);
// final int read = fis.read(buffer);
// int lastByteTranslated = 0;
// for (int i = 0; i < read && isText; i++) {
// final byte b = buffer[i];
// int ub = b & (0xff);
// int utf8value = lastByteTranslated + ub;
// lastByteTranslated = (ub) << 8;
//
// if (ub == 0x09
// || ub == 0x0A
// || ub == 0x0C
// || ub == 0x0D
// || (ub >= 0x20 && ub <= 0x7E)
// || (ub >= 0xA0 && ub <= 0xEE)
// || (utf8value >= 0x2E2E && utf8value <= 0xC3BF)) {
//
// } else {
// isText = false;
// }
// }
// return isText;
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// } finally {
// try {
// fis.close();
// } catch (final Throwable th) {
// }
// }
// }
// }
// Path: src/java/test/br/ufpe/cin/groundhog/util/FileUtilTest.java
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import br.ufpe.cin.groundhog.util.FileUtil;
package br.ufpe.cin.groundhog.util;
public class FileUtilTest {
@Test
public void testIsFile() throws IOException {
File files[] = new File(".").listFiles();
for (File file : files) { | boolean is = FileUtil.getInstance().isTextFile(file); |
spgroup/groundhog | src/java/main/br/ufpe/cin/groundhog/Project.java | // Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import java.util.Date;
import java.util.List;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
import org.mongodb.morphia.annotations.Reference;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.gson.annotations.SerializedName; | this.isFork = value;
}
/**
* Methods that deal with dates are below
* Notice that each setter method is overloaded to support Date and String parameters.
* When the parameter is provided as a String object, the setter method will perform the
* conversion to a date object
*/
/**
* Informs the creation date of the project
* @return a Date object correspondent to the project's creation date
*/
public Date getCreatedAt() {
return this.createdAt;
}
/**
* Sets the creation date of the project
* @param createdAt a Date object for setting the creation date of the project
*/
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* @param createdAtParam the String correspondent to the creation date of the project in question. e.g: 2012-04-28T15:40:35Z
*/
public void setCreatedAt(String createdAtParam) { | // Path: src/java/main/br/ufpe/cin/groundhog/util/Dates.java
// public class Dates {
//
// private SimpleDateFormat simpleDateFormat;
//
// public Dates() {
// simpleDateFormat = new SimpleDateFormat();
// }
//
// public Dates(String pattern) {
// simpleDateFormat = new SimpleDateFormat(pattern);
// }
//
// public String format(Date date) {
// return simpleDateFormat.format(date);
// }
//
// public Date format(String date) {
// try {
// return simpleDateFormat.parse(date);
// } catch (ParseException e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: src/java/main/br/ufpe/cin/groundhog/Project.java
import java.util.Date;
import java.util.List;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import org.mongodb.morphia.annotations.Indexed;
import org.mongodb.morphia.annotations.Reference;
import br.ufpe.cin.groundhog.util.Dates;
import com.google.gson.annotations.SerializedName;
this.isFork = value;
}
/**
* Methods that deal with dates are below
* Notice that each setter method is overloaded to support Date and String parameters.
* When the parameter is provided as a String object, the setter method will perform the
* conversion to a date object
*/
/**
* Informs the creation date of the project
* @return a Date object correspondent to the project's creation date
*/
public Date getCreatedAt() {
return this.createdAt;
}
/**
* Sets the creation date of the project
* @param createdAt a Date object for setting the creation date of the project
*/
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* @param createdAtParam the String correspondent to the creation date of the project in question. e.g: 2012-04-28T15:40:35Z
*/
public void setCreatedAt(String createdAtParam) { | Date createAtDate = new Dates("yyyy-MM-dd HH:mm:ss").format(createdAtParam); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/manager/OnlineUserManager.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/StaticBridge.java
// public class StaticBridge {
// private static Map<String, CoreEngine> coreEngineList = new ConcurrentHashMap<>();
//
// public static void putCoreEngine(String beanName, CoreEngine coreEngine){
// coreEngineList.put(beanName, coreEngine);
// }
//
// public static void removeCoreEngine(String beanName){
// coreEngineList.remove(beanName);
// }
//
// public static CoreEngine queryFirstCoreEngine(){
// return coreEngineList.entrySet().iterator().next().getValue();
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/session/SessionManager.java
// public class SessionManager {
//
// }
| import github.mappingrpc.core.StaticBridge;
import github.mappingrpc.core.session.SessionManager; | package github.mappingrpc.api.serverside.manager;
public class OnlineUserManager {
static SessionManager sessionManager;
//public void callOnlineUser() {}
public static void setupClientSessionToSuccessLogin(Object sessionOpaque){
}
public static void listOnlineUser() { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/StaticBridge.java
// public class StaticBridge {
// private static Map<String, CoreEngine> coreEngineList = new ConcurrentHashMap<>();
//
// public static void putCoreEngine(String beanName, CoreEngine coreEngine){
// coreEngineList.put(beanName, coreEngine);
// }
//
// public static void removeCoreEngine(String beanName){
// coreEngineList.remove(beanName);
// }
//
// public static CoreEngine queryFirstCoreEngine(){
// return coreEngineList.entrySet().iterator().next().getValue();
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/session/SessionManager.java
// public class SessionManager {
//
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/manager/OnlineUserManager.java
import github.mappingrpc.core.StaticBridge;
import github.mappingrpc.core.session.SessionManager;
package github.mappingrpc.api.serverside.manager;
public class OnlineUserManager {
static SessionManager sessionManager;
//public void callOnlineUser() {}
public static void setupClientSessionToSuccessLogin(Object sessionOpaque){
}
public static void listOnlineUser() { | StaticBridge.queryFirstCoreEngine(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/") | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/") | public User registerUser(User user, String password); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/")
public User registerUser(User user, String password);
@RequestMapping("/userService/registerUser/v20140308/") | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/")
public User registerUser(User user, String password);
@RequestMapping("/userService/registerUser/v20140308/") | public User registerUser(User user, String password, RegisterOption option); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/")
public User registerUser(User user, String password);
@RequestMapping("/userService/registerUser/v20140308/")
public User registerUser(User user, String password, RegisterOption option);
@RequestMapping("/userService/loginMobile/v20141013/") | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/")
public User registerUser(User user, String password);
@RequestMapping("/userService/registerUser/v20140308/")
public User registerUser(User user, String password, RegisterOption option);
@RequestMapping("/userService/loginMobile/v20141013/") | public ModelResult<User> login(User user, String password, LoginOption option); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/")
public User registerUser(User user, String password);
@RequestMapping("/userService/registerUser/v20140308/")
public User registerUser(User user, String password, RegisterOption option);
@RequestMapping("/userService/loginMobile/v20141013/") | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
import github.mappingrpc.api.annotation.RequestMapping;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.centerserver.service;
public interface UserService {
@Deprecated
@RequestMapping("/userservice/register/20140305/")
public User registerUser(User user, String password);
@RequestMapping("/userService/registerUser/v20140308/")
public User registerUser(User user, String password, RegisterOption option);
@RequestMapping("/userService/loginMobile/v20141013/") | public ModelResult<User> login(User user, String password, LoginOption option); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/ServiceInvocationHandler.java
// public class ServiceInvocationHandler implements InvocationHandler {
// Logger log = LoggerFactory.getLogger(ServiceInvocationHandler.class);
//
// private MappingPackageClient rpcClient;
// Map<Method, ApiProxyMeta> apiHolder = new HashMap<>();
//
// public ServiceInvocationHandler(MappingPackageClient rpcClient) {
// this.rpcClient = rpcClient;
// }
//
// public Object generateProxy(String serviceInterface) {
// Class<?> clazz;
// try {
// clazz = Class.forName(serviceInterface);// FIXME
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
//
// for (Method method : clazz.getMethods()) {
// RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
// if (requestMapping != null) {
// ApiProxyMeta apiMeta = new ApiProxyMeta();
// apiMeta.setRequestUrl(requestMapping.value());
// apiMeta.setParameterTypes(method.getParameterTypes());
// apiMeta.setReturnType(method.getReturnType());
// apiHolder.put(method, apiMeta);
// }
// }
//
// Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
// return proxy;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// // TODO 过滤掉hashCode()/toString()/equals等本地方法
//
// ApiProxyMeta meta = apiHolder.get(method);
// return rpcClient.sendRpc(meta.getRequestUrl(), args, meta.getReturnType(), 300000);
// }
//
// }
| import github.mappingrpc.core.rpc.CallResultFuture;
import github.mappingrpc.core.rpc.ServiceInvocationHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; | package github.mappingrpc.core.metadata;
public class MetaHolder {
private Map<String, ProviderMeta> providerHolder = new HashMap<>(); | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/ServiceInvocationHandler.java
// public class ServiceInvocationHandler implements InvocationHandler {
// Logger log = LoggerFactory.getLogger(ServiceInvocationHandler.class);
//
// private MappingPackageClient rpcClient;
// Map<Method, ApiProxyMeta> apiHolder = new HashMap<>();
//
// public ServiceInvocationHandler(MappingPackageClient rpcClient) {
// this.rpcClient = rpcClient;
// }
//
// public Object generateProxy(String serviceInterface) {
// Class<?> clazz;
// try {
// clazz = Class.forName(serviceInterface);// FIXME
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
//
// for (Method method : clazz.getMethods()) {
// RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
// if (requestMapping != null) {
// ApiProxyMeta apiMeta = new ApiProxyMeta();
// apiMeta.setRequestUrl(requestMapping.value());
// apiMeta.setParameterTypes(method.getParameterTypes());
// apiMeta.setReturnType(method.getReturnType());
// apiHolder.put(method, apiMeta);
// }
// }
//
// Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
// return proxy;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// // TODO 过滤掉hashCode()/toString()/equals等本地方法
//
// ApiProxyMeta meta = apiHolder.get(method);
// return rpcClient.sendRpc(meta.getRequestUrl(), args, meta.getReturnType(), 300000);
// }
//
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
import github.mappingrpc.core.rpc.CallResultFuture;
import github.mappingrpc.core.rpc.ServiceInvocationHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
package github.mappingrpc.core.metadata;
public class MetaHolder {
private Map<String, ProviderMeta> providerHolder = new HashMap<>(); | private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/ServiceInvocationHandler.java
// public class ServiceInvocationHandler implements InvocationHandler {
// Logger log = LoggerFactory.getLogger(ServiceInvocationHandler.class);
//
// private MappingPackageClient rpcClient;
// Map<Method, ApiProxyMeta> apiHolder = new HashMap<>();
//
// public ServiceInvocationHandler(MappingPackageClient rpcClient) {
// this.rpcClient = rpcClient;
// }
//
// public Object generateProxy(String serviceInterface) {
// Class<?> clazz;
// try {
// clazz = Class.forName(serviceInterface);// FIXME
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
//
// for (Method method : clazz.getMethods()) {
// RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
// if (requestMapping != null) {
// ApiProxyMeta apiMeta = new ApiProxyMeta();
// apiMeta.setRequestUrl(requestMapping.value());
// apiMeta.setParameterTypes(method.getParameterTypes());
// apiMeta.setReturnType(method.getReturnType());
// apiHolder.put(method, apiMeta);
// }
// }
//
// Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
// return proxy;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// // TODO 过滤掉hashCode()/toString()/equals等本地方法
//
// ApiProxyMeta meta = apiHolder.get(method);
// return rpcClient.sendRpc(meta.getRequestUrl(), args, meta.getReturnType(), 300000);
// }
//
// }
| import github.mappingrpc.core.rpc.CallResultFuture;
import github.mappingrpc.core.rpc.ServiceInvocationHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; | package github.mappingrpc.core.metadata;
public class MetaHolder {
private Map<String, ProviderMeta> providerHolder = new HashMap<>();
private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>(); | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/ServiceInvocationHandler.java
// public class ServiceInvocationHandler implements InvocationHandler {
// Logger log = LoggerFactory.getLogger(ServiceInvocationHandler.class);
//
// private MappingPackageClient rpcClient;
// Map<Method, ApiProxyMeta> apiHolder = new HashMap<>();
//
// public ServiceInvocationHandler(MappingPackageClient rpcClient) {
// this.rpcClient = rpcClient;
// }
//
// public Object generateProxy(String serviceInterface) {
// Class<?> clazz;
// try {
// clazz = Class.forName(serviceInterface);// FIXME
// } catch (ClassNotFoundException e) {
// throw new RuntimeException(e);
// }
//
// for (Method method : clazz.getMethods()) {
// RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
// if (requestMapping != null) {
// ApiProxyMeta apiMeta = new ApiProxyMeta();
// apiMeta.setRequestUrl(requestMapping.value());
// apiMeta.setParameterTypes(method.getParameterTypes());
// apiMeta.setReturnType(method.getReturnType());
// apiHolder.put(method, apiMeta);
// }
// }
//
// Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
// return proxy;
// }
//
// @Override
// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// // TODO 过滤掉hashCode()/toString()/equals等本地方法
//
// ApiProxyMeta meta = apiHolder.get(method);
// return rpcClient.sendRpc(meta.getRequestUrl(), args, meta.getReturnType(), 300000);
// }
//
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
import github.mappingrpc.core.rpc.CallResultFuture;
import github.mappingrpc.core.rpc.ServiceInvocationHandler;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
package github.mappingrpc.core.metadata;
public class MetaHolder {
private Map<String, ProviderMeta> providerHolder = new HashMap<>();
private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>(); | private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/fastjson/JsonTest.java | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
| import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.mappingrpc.connector.test.domain.User; | package mappingrpc.test.fastjson;
public class JsonTest {
@Test
public void test_genericsList() { | // Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/fastjson/JsonTest.java
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.mappingrpc.connector.test.domain.User;
package mappingrpc.test.fastjson;
public class JsonTest {
@Test
public void test_genericsList() { | List<User> userList = new ArrayList<>(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/manager/ClientCookieManager.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/domain/Cookie.java
// public class Cookie implements JSONAware {
// private String name;
// private String value;
// private int maxAge = -1;
//
// public Cookie() {
// }
//
// public Cookie(String cookieName, String cookieValue, int maxAge) {
// super();
// this.name = cookieName;
// this.value = cookieValue;
// this.maxAge = maxAge;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String cookieName) {
// this.name = cookieName;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String cookieValue) {
// this.value = cookieValue;
// }
//
// public int getMaxAge() {
// return maxAge;
// }
//
// /**
// *
// * @param maxAge
// * TimeUnit.SECOND
// */
// public void setMaxAge(int maxAge) {
// this.maxAge = maxAge;
// }
//
// public String toString() {
// return JSONObject.toJSONString(this);
// }
//
// @Override
// public String toJSONString() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("name", name);
// map.put("value", value);
// map.put("maxAge", maxAge);
// return JSONObject.toJSONString(map);
// }
// }
| import github.mappingrpc.api.clientside.domain.Cookie;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.api.clientside.manager;
public class ClientCookieManager {
private volatile String cookieCacheForReturnToServer = "[]";
private volatile Calendar cookieCacheExpiredTime;
private volatile boolean needFlushToDisk = false; | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/domain/Cookie.java
// public class Cookie implements JSONAware {
// private String name;
// private String value;
// private int maxAge = -1;
//
// public Cookie() {
// }
//
// public Cookie(String cookieName, String cookieValue, int maxAge) {
// super();
// this.name = cookieName;
// this.value = cookieValue;
// this.maxAge = maxAge;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String cookieName) {
// this.name = cookieName;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String cookieValue) {
// this.value = cookieValue;
// }
//
// public int getMaxAge() {
// return maxAge;
// }
//
// /**
// *
// * @param maxAge
// * TimeUnit.SECOND
// */
// public void setMaxAge(int maxAge) {
// this.maxAge = maxAge;
// }
//
// public String toString() {
// return JSONObject.toJSONString(this);
// }
//
// @Override
// public String toJSONString() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("name", name);
// map.put("value", value);
// map.put("maxAge", maxAge);
// return JSONObject.toJSONString(map);
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/manager/ClientCookieManager.java
import github.mappingrpc.api.clientside.domain.Cookie;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.api.clientside.manager;
public class ClientCookieManager {
private volatile String cookieCacheForReturnToServer = "[]";
private volatile Calendar cookieCacheExpiredTime;
private volatile boolean needFlushToDisk = false; | private Map<String, Cookie> memoryCookieStore = new ConcurrentHashMap<String, Cookie>(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
| import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption; | package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java
import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() { | CallCommand cmd = new CallCommand(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
| import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption; | package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() {
CallCommand cmd = new CallCommand();
cmd.setRequestId(rand.nextLong());
cmd.setProcedureUri("/userService/registerUser/v20140308/"); | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java
import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() {
CallCommand cmd = new CallCommand();
cmd.setRequestId(rand.nextLong());
cmd.setProcedureUri("/userService/registerUser/v20140308/"); | User user = new User(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
| import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption; | package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() {
CallCommand cmd = new CallCommand();
cmd.setRequestId(rand.nextLong());
cmd.setProcedureUri("/userService/registerUser/v20140308/");
User user = new User();
user.setId(6688);
user.setDisplayName("lokki"); | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java
import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() {
CallCommand cmd = new CallCommand();
cmd.setRequestId(rand.nextLong());
cmd.setProcedureUri("/userService/registerUser/v20140308/");
User user = new User();
user.setId(6688);
user.setDisplayName("lokki"); | RegisterOption registerOption = new RegisterOption(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
| import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption; | package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() {
CallCommand cmd = new CallCommand();
cmd.setRequestId(rand.nextLong());
cmd.setProcedureUri("/userService/registerUser/v20140308/");
User user = new User();
user.setId(6688);
user.setDisplayName("lokki");
RegisterOption registerOption = new RegisterOption();
cmd.setArgs(new Object[] { user, "psw", registerOption });
String json = JSONObject.toJSONString(cmd.fieldToArray());
System.out.println(json);
}
@Test
public void test_CallCommand_反序列化_期望成功() {
String jsonText = "[48,4881004229002152578,\"{}\",\"/userService/registerUser/v20140308/\",[{\"displayName\":\"lokki\",\"features\":\"{}\",\"flagBit\":0,\"id\":6688},\"psw\",{}]]";
JSONArray array = JSONObject.parseArray(jsonText);
int i = 0;
int msgType = array.getIntValue(i++);
switch (msgType) { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/RegisterOption.java
// public class RegisterOption {
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CommandJsonTest.java
import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.RegisterOption;
package mappingrpc.test.commandjson;
public class CommandJsonTest {
Random rand = new Random();
@Test
public void test_CallCommand_序列化_期望成功() {
CallCommand cmd = new CallCommand();
cmd.setRequestId(rand.nextLong());
cmd.setProcedureUri("/userService/registerUser/v20140308/");
User user = new User();
user.setId(6688);
user.setDisplayName("lokki");
RegisterOption registerOption = new RegisterOption();
cmd.setArgs(new Object[] { user, "psw", registerOption });
String json = JSONObject.toJSONString(cmd.fieldToArray());
System.out.println(json);
}
@Test
public void test_CallCommand_反序列化_期望成功() {
String jsonText = "[48,4881004229002152578,\"{}\",\"/userService/registerUser/v20140308/\",[{\"displayName\":\"lokki\",\"features\":\"{}\",\"flagBit\":0,\"id\":6688},\"psw\",{}]]";
JSONArray array = JSONObject.parseArray(jsonText);
int i = 0;
int msgType = array.getIntValue(i++);
switch (msgType) { | case MsgTypeConstant.call: |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/commonhandler/DisconnectDetectHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/constant/ClientDaemonThreadEventType.java
// public class ClientDaemonThreadEventType {
// public static final byte noEvent = 0;
//
// @Deprecated
// public static final byte channelConnecting = 1;
//
// @Deprecated
// public static final byte channelConnected = 2;
// public static final byte channelDisconnected = 3;
// public static final byte closeDaemonThread = 4;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/event/ClientDaemonThreadEvent.java
// public class ClientDaemonThreadEvent {
// private byte eventType = ClientDaemonThreadEventType.noEvent;
//
// public ClientDaemonThreadEvent(byte eventType) {
// this.eventType = eventType;
// }
//
// public byte getEventType() {
// return eventType;
// }
//
// public void setEventType(byte eventType) {
// this.eventType = eventType;
// }
// }
| import github.mappingrpc.core.constant.ClientDaemonThreadEventType;
import github.mappingrpc.core.event.ClientDaemonThreadEvent;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import java.util.concurrent.BlockingQueue; | package github.mappingrpc.core.io.commonhandler;
@Sharable
public class DisconnectDetectHandler extends ChannelDuplexHandler { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/constant/ClientDaemonThreadEventType.java
// public class ClientDaemonThreadEventType {
// public static final byte noEvent = 0;
//
// @Deprecated
// public static final byte channelConnecting = 1;
//
// @Deprecated
// public static final byte channelConnected = 2;
// public static final byte channelDisconnected = 3;
// public static final byte closeDaemonThread = 4;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/event/ClientDaemonThreadEvent.java
// public class ClientDaemonThreadEvent {
// private byte eventType = ClientDaemonThreadEventType.noEvent;
//
// public ClientDaemonThreadEvent(byte eventType) {
// this.eventType = eventType;
// }
//
// public byte getEventType() {
// return eventType;
// }
//
// public void setEventType(byte eventType) {
// this.eventType = eventType;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/commonhandler/DisconnectDetectHandler.java
import github.mappingrpc.core.constant.ClientDaemonThreadEventType;
import github.mappingrpc.core.event.ClientDaemonThreadEvent;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import java.util.concurrent.BlockingQueue;
package github.mappingrpc.core.io.commonhandler;
@Sharable
public class DisconnectDetectHandler extends ChannelDuplexHandler { | private BlockingQueue<ClientDaemonThreadEvent> nettyEventToOuter; |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/commonhandler/DisconnectDetectHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/constant/ClientDaemonThreadEventType.java
// public class ClientDaemonThreadEventType {
// public static final byte noEvent = 0;
//
// @Deprecated
// public static final byte channelConnecting = 1;
//
// @Deprecated
// public static final byte channelConnected = 2;
// public static final byte channelDisconnected = 3;
// public static final byte closeDaemonThread = 4;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/event/ClientDaemonThreadEvent.java
// public class ClientDaemonThreadEvent {
// private byte eventType = ClientDaemonThreadEventType.noEvent;
//
// public ClientDaemonThreadEvent(byte eventType) {
// this.eventType = eventType;
// }
//
// public byte getEventType() {
// return eventType;
// }
//
// public void setEventType(byte eventType) {
// this.eventType = eventType;
// }
// }
| import github.mappingrpc.core.constant.ClientDaemonThreadEventType;
import github.mappingrpc.core.event.ClientDaemonThreadEvent;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import java.util.concurrent.BlockingQueue; | package github.mappingrpc.core.io.commonhandler;
@Sharable
public class DisconnectDetectHandler extends ChannelDuplexHandler {
private BlockingQueue<ClientDaemonThreadEvent> nettyEventToOuter;
public DisconnectDetectHandler(BlockingQueue<ClientDaemonThreadEvent> nettyEventToOuter) {
this.nettyEventToOuter = nettyEventToOuter;
}
/*
public void channelActive(ChannelHandlerContext ctx) throws Exception {
nettyEventToOuter.add(new BossThreadEvent(BossThreadEventType.channelConnected));
}*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/constant/ClientDaemonThreadEventType.java
// public class ClientDaemonThreadEventType {
// public static final byte noEvent = 0;
//
// @Deprecated
// public static final byte channelConnecting = 1;
//
// @Deprecated
// public static final byte channelConnected = 2;
// public static final byte channelDisconnected = 3;
// public static final byte closeDaemonThread = 4;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/event/ClientDaemonThreadEvent.java
// public class ClientDaemonThreadEvent {
// private byte eventType = ClientDaemonThreadEventType.noEvent;
//
// public ClientDaemonThreadEvent(byte eventType) {
// this.eventType = eventType;
// }
//
// public byte getEventType() {
// return eventType;
// }
//
// public void setEventType(byte eventType) {
// this.eventType = eventType;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/commonhandler/DisconnectDetectHandler.java
import github.mappingrpc.core.constant.ClientDaemonThreadEventType;
import github.mappingrpc.core.event.ClientDaemonThreadEvent;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import java.util.concurrent.BlockingQueue;
package github.mappingrpc.core.io.commonhandler;
@Sharable
public class DisconnectDetectHandler extends ChannelDuplexHandler {
private BlockingQueue<ClientDaemonThreadEvent> nettyEventToOuter;
public DisconnectDetectHandler(BlockingQueue<ClientDaemonThreadEvent> nettyEventToOuter) {
this.nettyEventToOuter = nettyEventToOuter;
}
/*
public void channelActive(ChannelHandlerContext ctx) throws Exception {
nettyEventToOuter.add(new BossThreadEvent(BossThreadEventType.channelConnected));
}*/
public void channelInactive(ChannelHandlerContext ctx) throws Exception { | nettyEventToOuter.add(new ClientDaemonThreadEvent(ClientDaemonThreadEventType.channelDisconnected)); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/HelloCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/domain/UserSessionMapping.java
// public class UserSessionMapping {
// private long userIdFromServerSide;
// private String userUuid;
// private short userAuthType;
// private String sessionId;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/WellcomeCommand.java
// public class WellcomeCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.wellcome;
// private String session;
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public String getSession() {
// return session;
// }
//
// public void setSession(String session) {
// this.session = session;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, session};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.api.serverside.domain.UserSessionMapping;
import github.mappingrpc.core.io.wamp.domain.command.WellcomeCommand;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class HelloCommandHandler {
static Logger log = LoggerFactory.getLogger(HelloCommandHandler.class);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/domain/UserSessionMapping.java
// public class UserSessionMapping {
// private long userIdFromServerSide;
// private String userUuid;
// private short userAuthType;
// private String sessionId;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/WellcomeCommand.java
// public class WellcomeCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.wellcome;
// private String session;
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public String getSession() {
// return session;
// }
//
// public void setSession(String session) {
// this.session = session;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, session};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/HelloCommandHandler.java
import github.mappingrpc.api.serverside.domain.UserSessionMapping;
import github.mappingrpc.core.io.wamp.domain.command.WellcomeCommand;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class HelloCommandHandler {
static Logger log = LoggerFactory.getLogger(HelloCommandHandler.class);
| static Map<String, UserSessionMapping> sessionPool = new ConcurrentHashMap<>(300); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/HelloCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/domain/UserSessionMapping.java
// public class UserSessionMapping {
// private long userIdFromServerSide;
// private String userUuid;
// private short userAuthType;
// private String sessionId;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/WellcomeCommand.java
// public class WellcomeCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.wellcome;
// private String session;
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public String getSession() {
// return session;
// }
//
// public void setSession(String session) {
// this.session = session;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, session};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.api.serverside.domain.UserSessionMapping;
import github.mappingrpc.core.io.wamp.domain.command.WellcomeCommand;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class HelloCommandHandler {
static Logger log = LoggerFactory.getLogger(HelloCommandHandler.class);
static Map<String, UserSessionMapping> sessionPool = new ConcurrentHashMap<>(300);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/domain/UserSessionMapping.java
// public class UserSessionMapping {
// private long userIdFromServerSide;
// private String userUuid;
// private short userAuthType;
// private String sessionId;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/WellcomeCommand.java
// public class WellcomeCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.wellcome;
// private String session;
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public String getSession() {
// return session;
// }
//
// public void setSession(String session) {
// this.session = session;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, session};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/HelloCommandHandler.java
import github.mappingrpc.api.serverside.domain.UserSessionMapping;
import github.mappingrpc.core.io.wamp.domain.command.WellcomeCommand;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class HelloCommandHandler {
static Logger log = LoggerFactory.getLogger(HelloCommandHandler.class);
static Map<String, UserSessionMapping> sessionPool = new ConcurrentHashMap<>(300);
| public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) { |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/HelloCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/domain/UserSessionMapping.java
// public class UserSessionMapping {
// private long userIdFromServerSide;
// private String userUuid;
// private short userAuthType;
// private String sessionId;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/WellcomeCommand.java
// public class WellcomeCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.wellcome;
// private String session;
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public String getSession() {
// return session;
// }
//
// public void setSession(String session) {
// this.session = session;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, session};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.api.serverside.domain.UserSessionMapping;
import github.mappingrpc.core.io.wamp.domain.command.WellcomeCommand;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class HelloCommandHandler {
static Logger log = LoggerFactory.getLogger(HelloCommandHandler.class);
static Map<String, UserSessionMapping> sessionPool = new ConcurrentHashMap<>(300);
public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
String realm = jsonArray.getString(1);
if (realm.equals("newSession")) {
UserSessionMapping userSession = new UserSessionMapping();
String sessionId = UUID.randomUUID().toString();
if (sessionPool.putIfAbsent(sessionId, userSession) != null) {
log.warn("{msg:'uuid碰撞'}");
channelCtx.close();
} | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/serverside/domain/UserSessionMapping.java
// public class UserSessionMapping {
// private long userIdFromServerSide;
// private String userUuid;
// private short userAuthType;
// private String sessionId;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/WellcomeCommand.java
// public class WellcomeCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.wellcome;
// private String session;
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public String getSession() {
// return session;
// }
//
// public void setSession(String session) {
// this.session = session;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, session};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/HelloCommandHandler.java
import github.mappingrpc.api.serverside.domain.UserSessionMapping;
import github.mappingrpc.core.io.wamp.domain.command.WellcomeCommand;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class HelloCommandHandler {
static Logger log = LoggerFactory.getLogger(HelloCommandHandler.class);
static Map<String, UserSessionMapping> sessionPool = new ConcurrentHashMap<>(300);
public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
String realm = jsonArray.getString(1);
if (realm.equals("newSession")) {
UserSessionMapping userSession = new UserSessionMapping();
String sessionId = UUID.randomUUID().toString();
if (sessionPool.putIfAbsent(sessionId, userSession) != null) {
log.warn("{msg:'uuid碰撞'}");
channelCtx.close();
} | WellcomeCommand wellcome = new WellcomeCommand(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/exception/TimeoutException.java
// public class TimeoutException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public TimeoutException(String msg){
// super(msg);
// }
// }
| import github.mappingrpc.api.exception.TimeoutException;
import com.alibaba.fastjson.JSONObject; | package github.mappingrpc.core.rpc;
public class CallResultFuture {
private Object result;
private JSONObject detail;
Object lock = new Object();
private Class<?> returnType;
public CallResultFuture(Class<?> returnType) {
this.returnType = returnType;
}
public void waitReturn(long timeoutInMs) {
synchronized (lock) {
try {
lock.wait(timeoutInMs);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if (result == null && returnType != null) { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/exception/TimeoutException.java
// public class TimeoutException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public TimeoutException(String msg){
// super(msg);
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
import github.mappingrpc.api.exception.TimeoutException;
import com.alibaba.fastjson.JSONObject;
package github.mappingrpc.core.rpc;
public class CallResultFuture {
private Object result;
private JSONObject detail;
Object lock = new Object();
private Class<?> returnType;
public CallResultFuture(Class<?> returnType) {
this.returnType = returnType;
}
public void waitReturn(long timeoutInMs) {
synchronized (lock) {
try {
lock.wait(timeoutInMs);
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if (result == null && returnType != null) { | throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}"); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CallCommandTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
| import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import org.junit.Test; | package mappingrpc.test.commandjson;
public class CallCommandTest {
@Test
public void test_setCookieWithJsonString(){ | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/CallCommand.java
// public class CallCommand implements WampCommandBase {
// private int msgType = MsgTypeConstant.call;
// private long requestId = 1;
// private JSONObject options = new JSONObject();
// private String procedureUri;
// private Object[] args;
//
// static AtomicLong requestIdPool = new AtomicLong(1);
//
// public CallCommand(){
// requestId = requestIdPool.incrementAndGet();
// }
//
// @Override
// public int getMsgType() {
// return msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getOptions() {
// return options;
// }
//
// public void setOptions(JSONObject options) {
// this.options = options;
// }
//
// public String getProcedureUri() {
// return procedureUri;
// }
//
// public void setProcedureUri(String procedureUrl) {
// this.procedureUri = procedureUrl;
// }
//
// public Object[] getArgs() {
// return args;
// }
//
// public void setArgs(Object[] args) {
// this.args = args;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[]{msgType, requestId, options, procedureUri, args};
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray());
// }
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/CallCommandTest.java
import github.mappingrpc.core.io.wamp.domain.command.CallCommand;
import org.junit.Test;
package mappingrpc.test.commandjson;
public class CallCommandTest {
@Test
public void test_setCookieWithJsonString(){ | CallCommand callCmd = new CallCommand(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/ExceptionErrorCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class ExceptionErrorCommandHandler {
static Logger log = LoggerFactory.getLogger(ExceptionErrorCommandHandler.class);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/ExceptionErrorCommandHandler.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class ExceptionErrorCommandHandler {
static Logger log = LoggerFactory.getLogger(ExceptionErrorCommandHandler.class);
| public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) { |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/custompackage/WampJsonArrayHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java
// public class WampCommandBaseHandler implements Runnable {
//
// static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
//
// private MetaHolder metaHolder;
// private JSONArray jsonArray;
// private ChannelHandlerContext channelCtx;
//
// public WampCommandBaseHandler(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
// this.metaHolder = metaHolder;
// this.channelCtx = channelCtx;
// this.jsonArray = jsonArray;
// }
//
// @Override
// public void run() {
// int commandType = jsonArray.getIntValue(0);
// try {
// runInCatch(commandType);
// } catch (Throwable ex) {
// log.error("{commandType:" + commandType + "}", ex);
// }
// }
//
// private void runInCatch(int commandType) {
// switch (commandType) {
// case MsgTypeConstant.call:
// CallCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.result:
// ResultCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.error:
// ExceptionErrorCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.hello:
// HelloCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.wellcome:
// WellcomeCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// }
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.core.io.wamp.handler.WampCommandBaseHandler;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.custompackage;
@Sharable
public class WampJsonArrayHandler extends ChannelInboundHandlerAdapter { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java
// public class WampCommandBaseHandler implements Runnable {
//
// static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
//
// private MetaHolder metaHolder;
// private JSONArray jsonArray;
// private ChannelHandlerContext channelCtx;
//
// public WampCommandBaseHandler(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
// this.metaHolder = metaHolder;
// this.channelCtx = channelCtx;
// this.jsonArray = jsonArray;
// }
//
// @Override
// public void run() {
// int commandType = jsonArray.getIntValue(0);
// try {
// runInCatch(commandType);
// } catch (Throwable ex) {
// log.error("{commandType:" + commandType + "}", ex);
// }
// }
//
// private void runInCatch(int commandType) {
// switch (commandType) {
// case MsgTypeConstant.call:
// CallCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.result:
// ResultCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.error:
// ExceptionErrorCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.hello:
// HelloCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.wellcome:
// WellcomeCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// }
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/custompackage/WampJsonArrayHandler.java
import github.mappingrpc.core.io.wamp.handler.WampCommandBaseHandler;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.custompackage;
@Sharable
public class WampJsonArrayHandler extends ChannelInboundHandlerAdapter { | private MetaHolder metaHolder; |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/custompackage/WampJsonArrayHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java
// public class WampCommandBaseHandler implements Runnable {
//
// static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
//
// private MetaHolder metaHolder;
// private JSONArray jsonArray;
// private ChannelHandlerContext channelCtx;
//
// public WampCommandBaseHandler(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
// this.metaHolder = metaHolder;
// this.channelCtx = channelCtx;
// this.jsonArray = jsonArray;
// }
//
// @Override
// public void run() {
// int commandType = jsonArray.getIntValue(0);
// try {
// runInCatch(commandType);
// } catch (Throwable ex) {
// log.error("{commandType:" + commandType + "}", ex);
// }
// }
//
// private void runInCatch(int commandType) {
// switch (commandType) {
// case MsgTypeConstant.call:
// CallCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.result:
// ResultCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.error:
// ExceptionErrorCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.hello:
// HelloCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.wellcome:
// WellcomeCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// }
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.core.io.wamp.handler.WampCommandBaseHandler;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.custompackage;
@Sharable
public class WampJsonArrayHandler extends ChannelInboundHandlerAdapter {
private MetaHolder metaHolder;
public WampJsonArrayHandler(MetaHolder metaHolder) {
this.metaHolder = metaHolder;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof JSONArray)) {
super.channelRead(ctx, msg);
}
JSONArray jsonArray = (JSONArray) msg; | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java
// public class WampCommandBaseHandler implements Runnable {
//
// static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
//
// private MetaHolder metaHolder;
// private JSONArray jsonArray;
// private ChannelHandlerContext channelCtx;
//
// public WampCommandBaseHandler(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
// this.metaHolder = metaHolder;
// this.channelCtx = channelCtx;
// this.jsonArray = jsonArray;
// }
//
// @Override
// public void run() {
// int commandType = jsonArray.getIntValue(0);
// try {
// runInCatch(commandType);
// } catch (Throwable ex) {
// log.error("{commandType:" + commandType + "}", ex);
// }
// }
//
// private void runInCatch(int commandType) {
// switch (commandType) {
// case MsgTypeConstant.call:
// CallCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.result:
// ResultCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.error:
// ExceptionErrorCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.hello:
// HelloCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// case MsgTypeConstant.wellcome:
// WellcomeCommandHandler.processCommand(metaHolder, channelCtx, jsonArray);
// break;
// }
// }
//
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/custompackage/WampJsonArrayHandler.java
import github.mappingrpc.core.io.wamp.handler.WampCommandBaseHandler;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.custompackage;
@Sharable
public class WampJsonArrayHandler extends ChannelInboundHandlerAdapter {
private MetaHolder metaHolder;
public WampJsonArrayHandler(MetaHolder metaHolder) {
this.metaHolder = metaHolder;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof JSONArray)) {
super.channelRead(ctx, msg);
}
JSONArray jsonArray = (JSONArray) msg; | WampCommandBaseHandler commandHandler = new WampCommandBaseHandler(metaHolder, ctx, jsonArray); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/ResultCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
| import github.mappingrpc.core.metadata.MetaHolder;
import github.mappingrpc.core.rpc.CallResultFuture;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class ResultCommandHandler {
static Logger log = LoggerFactory.getLogger(ResultCommandHandler.class);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/ResultCommandHandler.java
import github.mappingrpc.core.metadata.MetaHolder;
import github.mappingrpc.core.rpc.CallResultFuture;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class ResultCommandHandler {
static Logger log = LoggerFactory.getLogger(ResultCommandHandler.class);
| public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) { |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/ResultCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
| import github.mappingrpc.core.metadata.MetaHolder;
import github.mappingrpc.core.rpc.CallResultFuture;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class ResultCommandHandler {
static Logger log = LoggerFactory.getLogger(ResultCommandHandler.class);
public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
long requestId = jsonArray.getLongValue(1); | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/rpc/CallResultFuture.java
// public class CallResultFuture {
// private Object result;
// private JSONObject detail;
// Object lock = new Object();
//
// private Class<?> returnType;
//
// public CallResultFuture(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// public void waitReturn(long timeoutInMs) {
// synchronized (lock) {
// try {
// lock.wait(timeoutInMs);
// } catch (InterruptedException e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// if (result == null && returnType != null) {
// throw new TimeoutException("{timeoutInMs:" + timeoutInMs + "}");
// }
// if (result instanceof Throwable) {
// Throwable e = (Throwable) result;
// throw new RuntimeException(e);
// }
// }
//
// public void putResultAndReturn(Object result) {
// this.result = result;
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// public void returnWithVoid(){
// synchronized (lock) {
// lock.notifyAll();
// }
// }
//
// @Deprecated
// /**
// * Deprecated: not in use
// * @param detail
// * @return
// */
// public CallResultFuture putDetail(JSONObject detail){
// this.detail = detail;
// return this;
// }
//
// public Object getResult(){
// return result;
// }
//
// public JSONObject getDetail() {
// return detail;
// }
//
// public void setDetail(JSONObject detail) {
// this.detail = detail;
// }
//
// public Class<?> getReturnType() {
// return returnType;
// }
//
// public void setReturnType(Class<?> returnType) {
// this.returnType = returnType;
// }
//
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/ResultCommandHandler.java
import github.mappingrpc.core.metadata.MetaHolder;
import github.mappingrpc.core.rpc.CallResultFuture;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class ResultCommandHandler {
static Logger log = LoggerFactory.getLogger(ResultCommandHandler.class);
public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
long requestId = jsonArray.getLongValue(1); | CallResultFuture callResult = metaHolder.getRequestPool().get(requestId); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/custompackage/MappingPackageServer.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package github.mappingrpc.core.io.custompackage;
public class MappingPackageServer implements Closeable {
static Logger log = LoggerFactory.getLogger(MappingPackageServer.class);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/custompackage/MappingPackageServer.java
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.io.Closeable;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package github.mappingrpc.core.io.custompackage;
public class MappingPackageServer implements Closeable {
static Logger log = LoggerFactory.getLogger(MappingPackageServer.class);
| private MetaHolder metaHolder; |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WellcomeCommandHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class WellcomeCommandHandler {
static Logger log = LoggerFactory.getLogger(WellcomeCommandHandler.class);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WellcomeCommandHandler.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class WellcomeCommandHandler {
static Logger log = LoggerFactory.getLogger(WellcomeCommandHandler.class);
| public static void processCommand(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) { |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/testcase/LocalServerTest.java | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
| import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User; | package mappingrpc.test.testcase;
@ContextConfiguration({"/localServerSide/spring-context.xml"})
public class LocalServerTest extends AbstractJUnit4SpringContextTests {
@Autowired | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/testcase/LocalServerTest.java
import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
package mappingrpc.test.testcase;
@ContextConfiguration({"/localServerSide/spring-context.xml"})
public class LocalServerTest extends AbstractJUnit4SpringContextTests {
@Autowired | UserService userService; |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/testcase/LocalServerTest.java | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
| import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User; | package mappingrpc.test.testcase;
@ContextConfiguration({"/localServerSide/spring-context.xml"})
public class LocalServerTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@Test
public void test() throws Exception {
Assert.assertNotNull("注入", userService); | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/testcase/LocalServerTest.java
import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
package mappingrpc.test.testcase;
@ContextConfiguration({"/localServerSide/spring-context.xml"})
public class LocalServerTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@Test
public void test() throws Exception {
Assert.assertNotNull("注入", userService); | User user = new User(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java
import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired | UserService userService; |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@BeforeClass
public static void beforeClass(){
System.err.println("beforeClass");
}
@Test
public void test() throws Exception{
Assert.assertNotNull("注入", userService); | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java
import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@BeforeClass
public static void beforeClass(){
System.err.println("beforeClass");
}
@Test
public void test() throws Exception{
Assert.assertNotNull("注入", userService); | User user = new User(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@BeforeClass
public static void beforeClass(){
System.err.println("beforeClass");
}
@Test
public void test() throws Exception{
Assert.assertNotNull("注入", userService);
User user = new User();
user.setDisplayName("lokki");
User result = userService.registerUser(user, "234");
System.err.println(result.getDisplayName() + "\nid:" + result.getId());
//Thread.sleep(60000);
user.setDisplayName("zhoufeng"); | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java
import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@BeforeClass
public static void beforeClass(){
System.err.println("beforeClass");
}
@Test
public void test() throws Exception{
Assert.assertNotNull("注入", userService);
User user = new User();
user.setDisplayName("lokki");
User result = userService.registerUser(user, "234");
System.err.println(result.getDisplayName() + "\nid:" + result.getId());
//Thread.sleep(60000);
user.setDisplayName("zhoufeng"); | LoginOption option = new LoginOption(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
| import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult; | package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@BeforeClass
public static void beforeClass(){
System.err.println("beforeClass");
}
@Test
public void test() throws Exception{
Assert.assertNotNull("注入", userService);
User user = new User();
user.setDisplayName("lokki");
User result = userService.registerUser(user, "234");
System.err.println(result.getDisplayName() + "\nid:" + result.getId());
//Thread.sleep(60000);
user.setDisplayName("zhoufeng");
LoginOption option = new LoginOption(); | // Path: mappingrpc-connector/src/test/java/mappingrpc/test/centerserver/service/UserService.java
// public interface UserService {
//
// @Deprecated
// @RequestMapping("/userservice/register/20140305/")
// public User registerUser(User user, String password);
//
// @RequestMapping("/userService/registerUser/v20140308/")
// public User registerUser(User user, String password, RegisterOption option);
//
// @RequestMapping("/userService/loginMobile/v20141013/")
// public ModelResult<User> login(User user, String password, LoginOption option);
//
// @RequestMapping("/userService/loginNoGenericsResult/v20141110/")
// public User loginNoGenericsResult(User user, String password, LoginOption option);
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/User.java
// public class User implements Serializable {
// private static final long serialVersionUID = -5128432017050518465L;
//
// private long id;
// private String displayName;
// private long flagBit;
// private String features = "{}";
// transient private JSONObject featuresJson = null;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// public long getFlagBit() {
// return flagBit;
// }
//
// public void setFlagBit(long flagBit) {
// this.flagBit = flagBit;
// }
//
// public String getFeatures() {
// return features;
// }
//
// public void setFeatures(String features) {
// this.features = features;
// }
//
// public JSONObject getFeaturesJson() {
// return featuresJson;
// }
//
// public void setFeaturesJson(JSONObject featuresJson) {
// this.featuresJson = featuresJson;
// }
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/option/LoginOption.java
// public class LoginOption {
//
// }
//
// Path: mappingrpc-connector/src/test/java/com/github/mappingrpc/connector/test/domain/result/ModelResult.java
// public class ModelResult<T> {
// private boolean success = true;
// private T model;
//
// public ModelResult() {
// }
//
// public ModelResult(T model) {
// this.model = model;
// }
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// public T getModel() {
// return model;
// }
//
// public void setModel(T result) {
// this.model = result;
// }
//
// public ModelResult<T> putResult(T result) {
// this.model = result;
// return this;
// }
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/testcase/AppSideCookieTest.java
import mappingrpc.test.centerserver.service.UserService;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.github.mappingrpc.connector.test.domain.User;
import com.github.mappingrpc.connector.test.domain.option.LoginOption;
import com.github.mappingrpc.connector.test.domain.result.ModelResult;
package mappingrpc.test.testcase;
@ContextConfiguration({"/cookieTestcase/test1/spring-context.xml"})
public class AppSideCookieTest extends AbstractJUnit4SpringContextTests {
@Autowired
UserService userService;
@BeforeClass
public static void beforeClass(){
System.err.println("beforeClass");
}
@Test
public void test() throws Exception{
Assert.assertNotNull("注入", userService);
User user = new User();
user.setDisplayName("lokki");
User result = userService.registerUser(user, "234");
System.err.println(result.getDisplayName() + "\nid:" + result.getId());
//Thread.sleep(60000);
user.setDisplayName("zhoufeng");
LoginOption option = new LoginOption(); | ModelResult<User> loginResult = userService.login(user, "234", option); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/ResultCommandTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/domain/Cookie.java
// public class Cookie implements JSONAware {
// private String name;
// private String value;
// private int maxAge = -1;
//
// public Cookie() {
// }
//
// public Cookie(String cookieName, String cookieValue, int maxAge) {
// super();
// this.name = cookieName;
// this.value = cookieValue;
// this.maxAge = maxAge;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String cookieName) {
// this.name = cookieName;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String cookieValue) {
// this.value = cookieValue;
// }
//
// public int getMaxAge() {
// return maxAge;
// }
//
// /**
// *
// * @param maxAge
// * TimeUnit.SECOND
// */
// public void setMaxAge(int maxAge) {
// this.maxAge = maxAge;
// }
//
// public String toString() {
// return JSONObject.toJSONString(this);
// }
//
// @Override
// public String toJSONString() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("name", name);
// map.put("value", value);
// map.put("maxAge", maxAge);
// return JSONObject.toJSONString(map);
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/ResultCommand.java
// public class ResultCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.result;
// private long requestId = 0;
// private JSONObject details = new JSONObject();
// private Object[] yieldResult = new Object[1];
//
// public ResultCommand() {
//
// }
//
// public ResultCommand(long requestId, Object result) {
// this.requestId = requestId;
// yieldResult[0] = result;
// }
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getDetails() {
// return details;
// }
//
// public void setDetails(JSONObject details) {
// this.details = details;
// }
//
// public Object[] getYieldResult() {
// return yieldResult;
// }
//
// public void setYieldResult(String[] yieldResult) {
// this.yieldResult = yieldResult;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[] { msgType, requestId, details, yieldResult };
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray()); // SerializerFeature.WriteClassName);
// }
//
// }
| import github.mappingrpc.api.clientside.domain.Cookie;
import github.mappingrpc.core.io.wamp.domain.command.ResultCommand;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; | package mappingrpc.test.commandjson;
public class ResultCommandTest {
@Test
public void test_toCommandJson() { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/domain/Cookie.java
// public class Cookie implements JSONAware {
// private String name;
// private String value;
// private int maxAge = -1;
//
// public Cookie() {
// }
//
// public Cookie(String cookieName, String cookieValue, int maxAge) {
// super();
// this.name = cookieName;
// this.value = cookieValue;
// this.maxAge = maxAge;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String cookieName) {
// this.name = cookieName;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String cookieValue) {
// this.value = cookieValue;
// }
//
// public int getMaxAge() {
// return maxAge;
// }
//
// /**
// *
// * @param maxAge
// * TimeUnit.SECOND
// */
// public void setMaxAge(int maxAge) {
// this.maxAge = maxAge;
// }
//
// public String toString() {
// return JSONObject.toJSONString(this);
// }
//
// @Override
// public String toJSONString() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("name", name);
// map.put("value", value);
// map.put("maxAge", maxAge);
// return JSONObject.toJSONString(map);
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/ResultCommand.java
// public class ResultCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.result;
// private long requestId = 0;
// private JSONObject details = new JSONObject();
// private Object[] yieldResult = new Object[1];
//
// public ResultCommand() {
//
// }
//
// public ResultCommand(long requestId, Object result) {
// this.requestId = requestId;
// yieldResult[0] = result;
// }
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getDetails() {
// return details;
// }
//
// public void setDetails(JSONObject details) {
// this.details = details;
// }
//
// public Object[] getYieldResult() {
// return yieldResult;
// }
//
// public void setYieldResult(String[] yieldResult) {
// this.yieldResult = yieldResult;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[] { msgType, requestId, details, yieldResult };
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray()); // SerializerFeature.WriteClassName);
// }
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/ResultCommandTest.java
import github.mappingrpc.api.clientside.domain.Cookie;
import github.mappingrpc.core.io.wamp.domain.command.ResultCommand;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
package mappingrpc.test.commandjson;
public class ResultCommandTest {
@Test
public void test_toCommandJson() { | ResultCommand resultCmd = new ResultCommand(1256, "'''"); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/ResultCommandTest.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/domain/Cookie.java
// public class Cookie implements JSONAware {
// private String name;
// private String value;
// private int maxAge = -1;
//
// public Cookie() {
// }
//
// public Cookie(String cookieName, String cookieValue, int maxAge) {
// super();
// this.name = cookieName;
// this.value = cookieValue;
// this.maxAge = maxAge;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String cookieName) {
// this.name = cookieName;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String cookieValue) {
// this.value = cookieValue;
// }
//
// public int getMaxAge() {
// return maxAge;
// }
//
// /**
// *
// * @param maxAge
// * TimeUnit.SECOND
// */
// public void setMaxAge(int maxAge) {
// this.maxAge = maxAge;
// }
//
// public String toString() {
// return JSONObject.toJSONString(this);
// }
//
// @Override
// public String toJSONString() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("name", name);
// map.put("value", value);
// map.put("maxAge", maxAge);
// return JSONObject.toJSONString(map);
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/ResultCommand.java
// public class ResultCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.result;
// private long requestId = 0;
// private JSONObject details = new JSONObject();
// private Object[] yieldResult = new Object[1];
//
// public ResultCommand() {
//
// }
//
// public ResultCommand(long requestId, Object result) {
// this.requestId = requestId;
// yieldResult[0] = result;
// }
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getDetails() {
// return details;
// }
//
// public void setDetails(JSONObject details) {
// this.details = details;
// }
//
// public Object[] getYieldResult() {
// return yieldResult;
// }
//
// public void setYieldResult(String[] yieldResult) {
// this.yieldResult = yieldResult;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[] { msgType, requestId, details, yieldResult };
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray()); // SerializerFeature.WriteClassName);
// }
//
// }
| import github.mappingrpc.api.clientside.domain.Cookie;
import github.mappingrpc.core.io.wamp.domain.command.ResultCommand;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; | package mappingrpc.test.commandjson;
public class ResultCommandTest {
@Test
public void test_toCommandJson() {
ResultCommand resultCmd = new ResultCommand(1256, "'''"); | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/api/clientside/domain/Cookie.java
// public class Cookie implements JSONAware {
// private String name;
// private String value;
// private int maxAge = -1;
//
// public Cookie() {
// }
//
// public Cookie(String cookieName, String cookieValue, int maxAge) {
// super();
// this.name = cookieName;
// this.value = cookieValue;
// this.maxAge = maxAge;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String cookieName) {
// this.name = cookieName;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String cookieValue) {
// this.value = cookieValue;
// }
//
// public int getMaxAge() {
// return maxAge;
// }
//
// /**
// *
// * @param maxAge
// * TimeUnit.SECOND
// */
// public void setMaxAge(int maxAge) {
// this.maxAge = maxAge;
// }
//
// public String toString() {
// return JSONObject.toJSONString(this);
// }
//
// @Override
// public String toJSONString() {
// Map<String, Object> map = new HashMap<String, Object>();
// map.put("name", name);
// map.put("value", value);
// map.put("maxAge", maxAge);
// return JSONObject.toJSONString(map);
// }
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/domain/command/ResultCommand.java
// public class ResultCommand implements WampCommandBase {
//
// private int msgType = MsgTypeConstant.result;
// private long requestId = 0;
// private JSONObject details = new JSONObject();
// private Object[] yieldResult = new Object[1];
//
// public ResultCommand() {
//
// }
//
// public ResultCommand(long requestId, Object result) {
// this.requestId = requestId;
// yieldResult[0] = result;
// }
//
// public int getMsgType() {
// return msgType;
// }
//
// public void setMsgType(int msgType) {
// this.msgType = msgType;
// }
//
// public long getRequestId() {
// return requestId;
// }
//
// public void setRequestId(long requestId) {
// this.requestId = requestId;
// }
//
// public JSONObject getDetails() {
// return details;
// }
//
// public void setDetails(JSONObject details) {
// this.details = details;
// }
//
// public Object[] getYieldResult() {
// return yieldResult;
// }
//
// public void setYieldResult(String[] yieldResult) {
// this.yieldResult = yieldResult;
// }
//
// @Override
// public Object[] fieldToArray() {
// return new Object[] { msgType, requestId, details, yieldResult };
// }
//
// @Override
// public String toCommandJson() {
// return JSONObject.toJSONString(fieldToArray()); // SerializerFeature.WriteClassName);
// }
//
// }
// Path: mappingrpc-connector/src/test/java/mappingrpc/test/commandjson/ResultCommandTest.java
import github.mappingrpc.api.clientside.domain.Cookie;
import github.mappingrpc.core.io.wamp.domain.command.ResultCommand;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
package mappingrpc.test.commandjson;
public class ResultCommandTest {
@Test
public void test_toCommandJson() {
ResultCommand resultCmd = new ResultCommand(1256, "'''"); | Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class WampCommandBaseHandler implements Runnable {
static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
| // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java
import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class WampCommandBaseHandler implements Runnable {
static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
| private MetaHolder metaHolder; |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
| import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray; | package github.mappingrpc.core.io.wamp.handler;
public class WampCommandBaseHandler implements Runnable {
static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
private MetaHolder metaHolder;
private JSONArray jsonArray;
private ChannelHandlerContext channelCtx;
public WampCommandBaseHandler(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
this.metaHolder = metaHolder;
this.channelCtx = channelCtx;
this.jsonArray = jsonArray;
}
@Override
public void run() {
int commandType = jsonArray.getIntValue(0);
try {
runInCatch(commandType);
} catch (Throwable ex) {
log.error("{commandType:" + commandType + "}", ex);
}
}
private void runInCatch(int commandType) {
switch (commandType) { | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/constant/MsgTypeConstant.java
// public class MsgTypeConstant {
// public static final int hello = 1; // doing
// public static final int wellcome = 2; // doing
// public static final int error = 8;
// public static final int call = 48;
// public static final int result = 50;
// }
//
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/metadata/MetaHolder.java
// public class MetaHolder {
// private Map<String, ProviderMeta> providerHolder = new HashMap<>();
// private Map<String, ServiceInvocationHandler> clientProxyHolder = new HashMap<>();
// private Map<Long, CallResultFuture> requestPool = new ConcurrentHashMap<>();
// private long feature1;
// private ExecutorService threadPool;
// private ExecutorService sysThreadPool;// for QOS
//
// public Map<String, ProviderMeta> getProviderHolder() {
// return providerHolder;
// }
//
// public Map<String, ServiceInvocationHandler> getClientProxyHolder() {
// return clientProxyHolder;
// }
//
// public Map<Long, CallResultFuture> getRequestPool() {
// return requestPool;
// }
//
// public void setRequestPool(Map<Long, CallResultFuture> requestPool) {
// this.requestPool = requestPool;
// }
//
// public ExecutorService getThreadPool() {
// return threadPool;
// }
//
// public void setThreadPool(ExecutorService threadPool) {
// this.threadPool = threadPool;
// }
//
// public long getFeature1() {
// return feature1;
// }
//
// public void setFeature1(long feature1) {
// this.feature1 = feature1;
// }
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/io/wamp/handler/WampCommandBaseHandler.java
import github.mappingrpc.core.io.wamp.constant.MsgTypeConstant;
import github.mappingrpc.core.metadata.MetaHolder;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
package github.mappingrpc.core.io.wamp.handler;
public class WampCommandBaseHandler implements Runnable {
static Logger log = LoggerFactory.getLogger(WampCommandBaseHandler.class);
private MetaHolder metaHolder;
private JSONArray jsonArray;
private ChannelHandlerContext channelCtx;
public WampCommandBaseHandler(MetaHolder metaHolder, ChannelHandlerContext channelCtx, JSONArray jsonArray) {
this.metaHolder = metaHolder;
this.channelCtx = channelCtx;
this.jsonArray = jsonArray;
}
@Override
public void run() {
int commandType = jsonArray.getIntValue(0);
try {
runInCatch(commandType);
} catch (Throwable ex) {
log.error("{commandType:" + commandType + "}", ex);
}
}
private void runInCatch(int commandType) {
switch (commandType) { | case MsgTypeConstant.call: |
zhoufenglokki/mappingrpc | mappingrpc-connector/src/main/java/github/mappingrpc/core/event/TimerAndEventDaemonThread.java | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/constant/ClientDaemonThreadEventType.java
// public class ClientDaemonThreadEventType {
// public static final byte noEvent = 0;
//
// @Deprecated
// public static final byte channelConnecting = 1;
//
// @Deprecated
// public static final byte channelConnected = 2;
// public static final byte channelDisconnected = 3;
// public static final byte closeDaemonThread = 4;
// }
| import github.mappingrpc.core.constant.ClientDaemonThreadEventType;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package github.mappingrpc.core.event;
public class TimerAndEventDaemonThread extends Thread {
static Logger log = LoggerFactory.getLogger(TimerAndEventDaemonThread.class);
private volatile boolean toStop = false;
private BlockingQueue<ClientDaemonThreadEvent> blockingQueue;
private List<Runnable> timerJobList = new CopyOnWriteArrayList<Runnable>();
private Map<Byte, Runnable> eventHandlerMap = new ConcurrentHashMap<Byte, Runnable>();
public TimerAndEventDaemonThread(BlockingQueue<ClientDaemonThreadEvent> blockingQueue) {
super("MappingPackageClient-Daemon");
setDaemon(true);
this.blockingQueue = blockingQueue;
}
public void close() {
toStop = true; | // Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/constant/ClientDaemonThreadEventType.java
// public class ClientDaemonThreadEventType {
// public static final byte noEvent = 0;
//
// @Deprecated
// public static final byte channelConnecting = 1;
//
// @Deprecated
// public static final byte channelConnected = 2;
// public static final byte channelDisconnected = 3;
// public static final byte closeDaemonThread = 4;
// }
// Path: mappingrpc-connector/src/main/java/github/mappingrpc/core/event/TimerAndEventDaemonThread.java
import github.mappingrpc.core.constant.ClientDaemonThreadEventType;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package github.mappingrpc.core.event;
public class TimerAndEventDaemonThread extends Thread {
static Logger log = LoggerFactory.getLogger(TimerAndEventDaemonThread.class);
private volatile boolean toStop = false;
private BlockingQueue<ClientDaemonThreadEvent> blockingQueue;
private List<Runnable> timerJobList = new CopyOnWriteArrayList<Runnable>();
private Map<Byte, Runnable> eventHandlerMap = new ConcurrentHashMap<Byte, Runnable>();
public TimerAndEventDaemonThread(BlockingQueue<ClientDaemonThreadEvent> blockingQueue) {
super("MappingPackageClient-Daemon");
setDaemon(true);
this.blockingQueue = blockingQueue;
}
public void close() {
toStop = true; | blockingQueue.offer(new ClientDaemonThreadEvent(ClientDaemonThreadEventType.closeDaemonThread)); |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/Bfs.java | // Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/IntArrayStrategy.java
// public final class IntArrayStrategy implements Strategy<int[]> {
//
//
// @Override
// public boolean equals(int[] o1, int[] o2) {
// return Arrays.equals(o1, o2);
// }
//
// @Override
// public int hashCode(int[] o) {
// return Arrays.hashCode(o);
// }
//
//
// }
| import de.mpii.gsm.taxonomy.*;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.IntArrayStrategy;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map; | package de.mpii.gsm.localmining;
public class Bfs {
// -- parameters
// --------------------------------------------------------------------------------
/** Minimum support */
protected int sigma;
/** Maximum gap */
protected int gamma;
/** Maximum length */
protected int lambda;
/**
* Start of pivot range (see class description). Set to 0 to mine all frequent
* sequences.
*/
protected int beginItem = 0;
/**
* End of pivot range (see class description). Set to {@link Integer.MAXVALUE}
* to mine all frequent sequences.
*/
protected int endItem = Integer.MAX_VALUE;
// -- internal variables
// ------------------------------------------------------------------------
// At any point of time, we store an inverted index that maps subsequences of
// length k
// to their posting lists.
//
// During data input, we have k=2. Every input transaction is added to the
// index (by generating
// all its (2,gamma)-subsequences and then discarded.
//
// During frequent sequence mining, we compute repeatedly compute length-(k+1)
// subsequences
// from the length-k subsequences.
/** Length of subsequences currently being mined */
protected int k;
/**
* A list of sequences of length k; no sequence occurs more than once. Each
* sequence is stored in either uncompressed or compressed format.
*
* In uncompressed format, each sequence is encoded as an array of exactly k
* item identifiers. When k=2, all sequences are stored in uncompressed
* format.
*
* In compressed format, each sequence is encoded as a length-2 array (p, w).
* To reconstruct the uncompressed sequence, take the first k-1 items from the
* sequence at position p in kSequences (p is a "prefix pointer") and set the
* k-th item to w (suffix item). When k>2, an entry is compressed when it has
* two elements and uncompressed when it has k elements.
*/
protected ArrayList<int[]> kSequences = new ArrayList<int[]>();
/**
* Maps 2-sequence to their position in kSequences (lowest 32 bits) and their
* largest transaction id (highest 32 bits). Only used during data input, k=2.
*/
Map<int[], KSequenceIndexEntry> kSequenceIndex = new Object2ObjectOpenCustomHashMap<int[], KSequenceIndexEntry>( | // Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/IntArrayStrategy.java
// public final class IntArrayStrategy implements Strategy<int[]> {
//
//
// @Override
// public boolean equals(int[] o1, int[] o2) {
// return Arrays.equals(o1, o2);
// }
//
// @Override
// public int hashCode(int[] o) {
// return Arrays.hashCode(o);
// }
//
//
// }
// Path: src/main/java/de/mpii/gsm/localmining/Bfs.java
import de.mpii.gsm.taxonomy.*;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.IntArrayStrategy;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
package de.mpii.gsm.localmining;
public class Bfs {
// -- parameters
// --------------------------------------------------------------------------------
/** Minimum support */
protected int sigma;
/** Maximum gap */
protected int gamma;
/** Maximum length */
protected int lambda;
/**
* Start of pivot range (see class description). Set to 0 to mine all frequent
* sequences.
*/
protected int beginItem = 0;
/**
* End of pivot range (see class description). Set to {@link Integer.MAXVALUE}
* to mine all frequent sequences.
*/
protected int endItem = Integer.MAX_VALUE;
// -- internal variables
// ------------------------------------------------------------------------
// At any point of time, we store an inverted index that maps subsequences of
// length k
// to their posting lists.
//
// During data input, we have k=2. Every input transaction is added to the
// index (by generating
// all its (2,gamma)-subsequences and then discarded.
//
// During frequent sequence mining, we compute repeatedly compute length-(k+1)
// subsequences
// from the length-k subsequences.
/** Length of subsequences currently being mined */
protected int k;
/**
* A list of sequences of length k; no sequence occurs more than once. Each
* sequence is stored in either uncompressed or compressed format.
*
* In uncompressed format, each sequence is encoded as an array of exactly k
* item identifiers. When k=2, all sequences are stored in uncompressed
* format.
*
* In compressed format, each sequence is encoded as a length-2 array (p, w).
* To reconstruct the uncompressed sequence, take the first k-1 items from the
* sequence at position p in kSequences (p is a "prefix pointer") and set the
* k-th item to w (suffix item). When k>2, an entry is compressed when it has
* two elements and uncompressed when it has k elements.
*/
protected ArrayList<int[]> kSequences = new ArrayList<int[]>();
/**
* Maps 2-sequence to their position in kSequences (lowest 32 bits) and their
* largest transaction id (highest 32 bits). Only used during data input, k=2.
*/
Map<int[], KSequenceIndexEntry> kSequenceIndex = new Object2ObjectOpenCustomHashMap<int[], KSequenceIndexEntry>( | new IntArrayStrategy()); |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/Bfs.java | // Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/IntArrayStrategy.java
// public final class IntArrayStrategy implements Strategy<int[]> {
//
//
// @Override
// public boolean equals(int[] o1, int[] o2) {
// return Arrays.equals(o1, o2);
// }
//
// @Override
// public int hashCode(int[] o) {
// return Arrays.hashCode(o);
// }
//
//
// }
| import de.mpii.gsm.taxonomy.*;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.IntArrayStrategy;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map; | // uncomment next line to save some space during 1st phase (but:
// increased runtime)
// postingList.trimToSize();
id++; // next id
} else {
// delete the current sequence (by moving the last sequence to the
// current position)
int size1 = kPostingLists.size() - 1;
if (id < size1) {
kSequences.set(id, kSequences.remove(size1));
kPostingLists.set(id, kPostingLists.remove(size1));
kTotalSupports.set(id, kTotalSupports.get(size1));
kTotalSupports.remove(size1);
} else {
kSequences.remove(size1);
kPostingLists.remove(size1);
kTotalSupports.remove(size1);
}
// same id again (now holding a different kSequence)
}
}
}
public int noOfPatterns() {
return noOfPatterns_;
}
// -- mining phase
// ------------------------------------------------------------------------------
| // Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/IntArrayStrategy.java
// public final class IntArrayStrategy implements Strategy<int[]> {
//
//
// @Override
// public boolean equals(int[] o1, int[] o2) {
// return Arrays.equals(o1, o2);
// }
//
// @Override
// public int hashCode(int[] o) {
// return Arrays.hashCode(o);
// }
//
//
// }
// Path: src/main/java/de/mpii/gsm/localmining/Bfs.java
import de.mpii.gsm.taxonomy.*;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.IntArrayStrategy;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenCustomHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
// uncomment next line to save some space during 1st phase (but:
// increased runtime)
// postingList.trimToSize();
id++; // next id
} else {
// delete the current sequence (by moving the last sequence to the
// current position)
int size1 = kPostingLists.size() - 1;
if (id < size1) {
kSequences.set(id, kSequences.remove(size1));
kPostingLists.set(id, kPostingLists.remove(size1));
kTotalSupports.set(id, kTotalSupports.get(size1));
kTotalSupports.remove(size1);
} else {
kSequences.remove(size1);
kPostingLists.remove(size1);
kTotalSupports.remove(size1);
}
// same id again (now holding a different kSequence)
}
}
}
public int noOfPatterns() {
return noOfPatterns_;
}
// -- mining phase
// ------------------------------------------------------------------------------
| public void mineAndClear(GsmWriter writer) throws IOException, InterruptedException { |
uma-pi1/lash | src/main/java/de/mpii/gsm/utils/Dictionary.java | // Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import de.mpii.gsm.utils.PrimitiveUtils;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.mahout.math.list.IntArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import org.apache.mahout.math.map.OpenIntObjectHashMap; | package de.mpii.gsm.utils;
public class Dictionary {
//Combines itemId and support value in a long value
protected ArrayList<Long> items = new ArrayList<Long>();
protected int[] parentIds;
OpenIntObjectHashMap<String> itemIdToItemMap = new OpenIntObjectHashMap<String>();
public void load(Configuration conf, String fileName, int minSupport) throws IOException {
BufferedReader br = null;
if (conf == null) {
@SuppressWarnings("resource")
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
} else {
FileSystem fs = FileSystem.get(conf);
FSDataInputStream dis = fs.open(new Path(fileName));
br = new BufferedReader(new InputStreamReader(dis));
}
OpenIntIntHashMap parentMap = new OpenIntIntHashMap();
String line = null;
while ((line = br.readLine()) != null) {
String[] splits = line.split("\t");
int itemId = Integer.parseInt(splits[3]);
int itemSupport = Integer.parseInt(splits[2]);
int parentId = Integer.parseInt(splits[4]);
parentMap.put(itemId, parentId);
if (itemSupport >= minSupport) { | // Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/utils/Dictionary.java
import de.mpii.gsm.utils.PrimitiveUtils;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.mahout.math.list.IntArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import org.apache.mahout.math.map.OpenIntObjectHashMap;
package de.mpii.gsm.utils;
public class Dictionary {
//Combines itemId and support value in a long value
protected ArrayList<Long> items = new ArrayList<Long>();
protected int[] parentIds;
OpenIntObjectHashMap<String> itemIdToItemMap = new OpenIntObjectHashMap<String>();
public void load(Configuration conf, String fileName, int minSupport) throws IOException {
BufferedReader br = null;
if (conf == null) {
@SuppressWarnings("resource")
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
br = new BufferedReader(new InputStreamReader(in));
} else {
FileSystem fs = FileSystem.get(conf);
FSDataInputStream dis = fs.open(new Path(fileName));
br = new BufferedReader(new InputStreamReader(dis));
}
OpenIntIntHashMap parentMap = new OpenIntIntHashMap();
String line = null;
while ((line = br.readLine()) != null) {
String[] splits = line.split("\t");
int itemId = Integer.parseInt(splits[3]);
int itemSupport = Integer.parseInt(splits[2]);
int parentId = Integer.parseInt(splits[4]);
parentMap.put(itemId, parentId);
if (itemSupport >= minSupport) { | items.add(PrimitiveUtils.combine(itemId, itemSupport)); |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/PSM.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils; | package de.mpii.gsm.localmining;
public class PSM {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
| // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/localmining/PSM.java
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
package de.mpii.gsm.localmining;
public class PSM {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
| protected Taxonomy taxonomy; |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/PSM.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils; | package de.mpii.gsm.localmining;
public class PSM {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
protected Taxonomy taxonomy;
protected Items pivotItems = new Items();
private int _noOfFrequentPatterns = 0;
protected int beginItem = 0;
protected int endItem = Integer.MAX_VALUE;
IntOpenHashSet tempSet = new IntOpenHashSet();
OpenIntIntHashMap globallyFrequentItems = new OpenIntIntHashMap();
private int[] transaction = null;
| // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/localmining/PSM.java
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
package de.mpii.gsm.localmining;
public class PSM {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
protected Taxonomy taxonomy;
protected Items pivotItems = new Items();
private int _noOfFrequentPatterns = 0;
protected int beginItem = 0;
protected int endItem = Integer.MAX_VALUE;
IntOpenHashSet tempSet = new IntOpenHashSet();
OpenIntIntHashMap globallyFrequentItems = new OpenIntIntHashMap();
private int[] transaction = null;
| GsmWriter writer; |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/PSM.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils; |
private static final class Item {
int support;
int lastTransactionId;
long lastPosition;
ByteArrayList transactionIds;
Item() {
support = 0;
lastTransactionId = -1;
lastPosition = -1;
transactionIds = new ByteArrayList();
}
}
private static final class Items {
Int2ObjectOpenHashMap<Item> itemIndex = new Int2ObjectOpenHashMap<Item>();
public void addItem(int itemId, int transactionId, int support, int l, int r) {
Item item = itemIndex.get(itemId);
if (item == null) {
item = new Item();
itemIndex.put(itemId, item);
// baseItems.add(itemId);
} | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/localmining/PSM.java
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import org.apache.mahout.math.map.OpenIntIntHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
private static final class Item {
int support;
int lastTransactionId;
long lastPosition;
ByteArrayList transactionIds;
Item() {
support = 0;
lastTransactionId = -1;
lastPosition = -1;
transactionIds = new ByteArrayList();
}
}
private static final class Items {
Int2ObjectOpenHashMap<Item> itemIndex = new Int2ObjectOpenHashMap<Item>();
public void addItem(int itemId, int transactionId, int support, int l, int r) {
Item item = itemIndex.get(itemId);
if (item == null) {
item = new Item();
itemIndex.put(itemId, item);
// baseItems.add(itemId);
} | long lr = PrimitiveUtils.combine(l, r); |
uma-pi1/lash | src/main/java/de/mpii/gsm/driver/GsmDriver.java | // Path: src/main/java/de/mpii/gsm/driver/GsmConfig.java
// public static enum Mode {
// SEQUENTIAL, DISTRIBUTED
// };
| import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import de.mpii.gsm.driver.GsmConfig.Mode; |
// support
if (cmd.hasOption("s")) {
LOGGER.log(Level.INFO, "Using cli argument -s=" + cmd.getOptionValue("s"));
config.setSigma(Integer.parseInt(cmd.getOptionValue("s")));
} else {
LOGGER.log(Level.INFO, "Missing minimum support, using default value " + config.getSigma());
}
// gap
if (cmd.hasOption("g")) {
LOGGER.log(Level.INFO, "Using cli argument -g=" + cmd.getOptionValue("g"));
config.setGamma(Integer.parseInt(cmd.getOptionValue("g")));
} else {
LOGGER.log(Level.INFO, "Missing maximum gap, using default value " + config.getGamma());
}
// length
if (cmd.hasOption("l")) {
LOGGER.log(Level.INFO, "Using cli argument -l=" + cmd.getOptionValue("l"));
config.setLambda(Integer.parseInt(cmd.getOptionValue("l")));
} else {
LOGGER.log(Level.INFO, "Missing maximum length, using default value " + config.getLambda());
}
// mode
if (cmd.hasOption("m")) {
LOGGER.log(Level.INFO, "Using cli argument -m=" + cmd.getOptionValue("m"));
// config.setMode(cmd.getOptionValue("m"));
if (cmd.getOptionValue("m").equals("s")) { | // Path: src/main/java/de/mpii/gsm/driver/GsmConfig.java
// public static enum Mode {
// SEQUENTIAL, DISTRIBUTED
// };
// Path: src/main/java/de/mpii/gsm/driver/GsmDriver.java
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import de.mpii.gsm.driver.GsmConfig.Mode;
// support
if (cmd.hasOption("s")) {
LOGGER.log(Level.INFO, "Using cli argument -s=" + cmd.getOptionValue("s"));
config.setSigma(Integer.parseInt(cmd.getOptionValue("s")));
} else {
LOGGER.log(Level.INFO, "Missing minimum support, using default value " + config.getSigma());
}
// gap
if (cmd.hasOption("g")) {
LOGGER.log(Level.INFO, "Using cli argument -g=" + cmd.getOptionValue("g"));
config.setGamma(Integer.parseInt(cmd.getOptionValue("g")));
} else {
LOGGER.log(Level.INFO, "Missing maximum gap, using default value " + config.getGamma());
}
// length
if (cmd.hasOption("l")) {
LOGGER.log(Level.INFO, "Using cli argument -l=" + cmd.getOptionValue("l"));
config.setLambda(Integer.parseInt(cmd.getOptionValue("l")));
} else {
LOGGER.log(Level.INFO, "Missing maximum length, using default value " + config.getLambda());
}
// mode
if (cmd.hasOption("m")) {
LOGGER.log(Level.INFO, "Using cli argument -m=" + cmd.getOptionValue("m"));
// config.setMode(cmd.getOptionValue("m"));
if (cmd.getOptionValue("m").equals("s")) { | config.setMode(Mode.SEQUENTIAL); |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/PSMwithIndex.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet; | package de.mpii.gsm.localmining;
public class PSMwithIndex {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
| // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/localmining/PSMwithIndex.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
package de.mpii.gsm.localmining;
public class PSMwithIndex {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
| protected Taxonomy taxonomy; |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/PSMwithIndex.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet; | package de.mpii.gsm.localmining;
public class PSMwithIndex {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
protected Taxonomy taxonomy;
protected int beginItem = 0;
protected int endItem = Integer.MAX_VALUE;
Int2IntOpenHashMap globallyFrequentItems = new Int2IntOpenHashMap();
IntOpenHashSet tempSet = new IntOpenHashSet();
| // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/localmining/PSMwithIndex.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
package de.mpii.gsm.localmining;
public class PSMwithIndex {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
protected Taxonomy taxonomy;
protected int beginItem = 0;
protected int endItem = Integer.MAX_VALUE;
Int2IntOpenHashMap globallyFrequentItems = new Int2IntOpenHashMap();
IntOpenHashSet tempSet = new IntOpenHashSet();
| GsmWriter writer; |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/PSMwithIndex.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
| import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet; | return totalSequences;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// -- HELPER CLASSES --
private static final class Item {
int support;
int lastTransactionId;
long lastPosition;
ByteArrayList transactionIds;
Item() {
support = 0;
lastTransactionId = -1;
lastPosition = -1;
transactionIds = new ByteArrayList();
}
public void addTransaction(int transactionId, int support, int l, int r) {
this.support = support;
| // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
//
// Path: src/main/java/de/mpii/gsm/utils/PrimitiveUtils.java
// public final class PrimitiveUtils {
//
// /**
// * Combines the two given int values into a single long value.
// *
// * @param l
// * @param r
// * @return
// */
// public static long combine(int l, int r) {
// return ((long) l << 32) | ((long) r & 0xFFFFFFFFL);
// }
//
// /**
// * Extracts int value corresponding to left-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getLeft(long c) {
// return (int) (c >> 32);
// }
//
// /**
// * Extracts int value corresponding to right-most 32 bits of given long value.
// *
// * @param c
// * @return
// */
// public static int getRight(long c) {
// return (int) c;
// }
// }
// Path: src/main/java/de/mpii/gsm/localmining/PSMwithIndex.java
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
import de.mpii.gsm.utils.PrimitiveUtils;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
return totalSequences;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// -- HELPER CLASSES --
private static final class Item {
int support;
int lastTransactionId;
long lastPosition;
ByteArrayList transactionIds;
Item() {
support = 0;
lastTransactionId = -1;
lastPosition = -1;
transactionIds = new ByteArrayList();
}
public void addTransaction(int transactionId, int support, int l, int r) {
this.support = support;
| long lr = PrimitiveUtils.combine(l, r); |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/Dfs.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
| import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter; | package de.mpii.gsm.localmining;
/**
* @author Kaustubh Beedkar ([email protected])
*
*/
public class Dfs {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
| // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
// Path: src/main/java/de/mpii/gsm/localmining/Dfs.java
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
package de.mpii.gsm.localmining;
/**
* @author Kaustubh Beedkar ([email protected])
*
*/
public class Dfs {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
| protected Taxonomy taxonomy; |
uma-pi1/lash | src/main/java/de/mpii/gsm/localmining/Dfs.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
| import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter; | package de.mpii.gsm.localmining;
/**
* @author Kaustubh Beedkar ([email protected])
*
*/
public class Dfs {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
protected Taxonomy taxonomy;
private int _noOfFrequentPatterns = 0;
protected int beginItem = 0;
protected int endItem = Integer.MAX_VALUE;
protected Items globalItems = new Items();
private int[] transaction = null; | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
//
// Path: src/main/java/de/mpii/gsm/writer/GsmWriter.java
// public interface GsmWriter {
// void write(int[] sequence, long count) throws IOException, InterruptedException;
// }
// Path: src/main/java/de/mpii/gsm/localmining/Dfs.java
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.bytes.ByteArrayList;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
import de.mpii.gsm.taxonomy.Taxonomy;
import de.mpii.gsm.writer.GsmWriter;
package de.mpii.gsm.localmining;
/**
* @author Kaustubh Beedkar ([email protected])
*
*/
public class Dfs {
protected int sigma;
protected int gamma;
protected int lambda;
protected ArrayList<int[]> inputTransactions = new ArrayList<int[]>();
protected IntArrayList transactionSupports = new IntArrayList();
protected Taxonomy taxonomy;
private int _noOfFrequentPatterns = 0;
protected int beginItem = 0;
protected int endItem = Integer.MAX_VALUE;
protected Items globalItems = new Items();
private int[] transaction = null; | GsmWriter writer; |
uma-pi1/lash | src/main/java/de/mpii/gsm/lash/encoders/BaseGapEncoder.java | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
| import java.io.IOException;
import de.mpii.gsm.taxonomy.Taxonomy; | package de.mpii.gsm.lash.encoders;
public abstract class BaseGapEncoder {
// -- variables
// ---------------------------------------------------------------------------------
/** the maximum gap allowed within a subsequence */
protected int gamma;
/** the maximum length of frequent subsequences */
protected int lambda;
/**
* left reachability is measured as the minimum number of hops to reach a
* pivot at the left from current item
*/
protected int[] leftHops;
/**
* right reachability is measured as the minimum number of hops to reach a
* pivot at the right from current item
*/
protected int[] rightHops;
/** auxiliary variables for computing distances */
protected int lastPdist = -1; // distance of last reachable item from the
// pivot
protected int lastHops = -1; // number of hops to reach that item
protected int prevPdist = -1; // distance from pivot of last reachable item
// with smaller
// distance
/** minimum allowed length */
protected final int MINIMUM_LENGTH = 2;
/** whether unreachable items are removed */
protected boolean removeUnreachable = true;
/**
* whether gaps will be compressed (multiple consecutive gaps grouped
* together, leading and trailing gaps removed)
*/
protected boolean compressGaps = true;
/**
* Taxonomy
*/ | // Path: src/main/java/de/mpii/gsm/taxonomy/Taxonomy.java
// public interface Taxonomy {
//
// public void load(String fileName) throws Exception;
//
// public void load(Configuration conf, String taxonomyURI) throws IOException, ClassNotFoundException;
//
// public void load(int[] p);
//
// /**
// * @param child Item from the taxonomy
// * @return parent id
// */
// public int getParent(int item);
//
// /**
// * @param child Item from the taxonomy
// * @return true/false
// */
// public boolean hasParent(int item);
//
// /**
// * @param child
// * @return
// */
// public int getDepth(int item);
//
//
// /**
// * @param item
// * @return
// */
// public int getRoot(int item);
//
//
// /**
// * @param item1
// * @param item2
// * @return
// */
// public int getCommonParent(int item1, int item2);
//
// public boolean isParent(int parent, int child);
//
// public boolean isGeneralizationOf(int item1, int item2);
//
//
// public int maxDepth();
//
// public int[] getParents();
//
// }
// Path: src/main/java/de/mpii/gsm/lash/encoders/BaseGapEncoder.java
import java.io.IOException;
import de.mpii.gsm.taxonomy.Taxonomy;
package de.mpii.gsm.lash.encoders;
public abstract class BaseGapEncoder {
// -- variables
// ---------------------------------------------------------------------------------
/** the maximum gap allowed within a subsequence */
protected int gamma;
/** the maximum length of frequent subsequences */
protected int lambda;
/**
* left reachability is measured as the minimum number of hops to reach a
* pivot at the left from current item
*/
protected int[] leftHops;
/**
* right reachability is measured as the minimum number of hops to reach a
* pivot at the right from current item
*/
protected int[] rightHops;
/** auxiliary variables for computing distances */
protected int lastPdist = -1; // distance of last reachable item from the
// pivot
protected int lastHops = -1; // number of hops to reach that item
protected int prevPdist = -1; // distance from pivot of last reachable item
// with smaller
// distance
/** minimum allowed length */
protected final int MINIMUM_LENGTH = 2;
/** whether unreachable items are removed */
protected boolean removeUnreachable = true;
/**
* whether gaps will be compressed (multiple consecutive gaps grouped
* together, leading and trailing gaps removed)
*/
protected boolean compressGaps = true;
/**
* Taxonomy
*/ | Taxonomy taxonomy; |
uma-pi1/lash | src/main/java/de/mpii/gsm/lash/encoders/SplitGapEncoder.java | // Path: src/main/java/de/mpii/gsm/utils/IntArrayComparator.java
// public class IntArrayComparator {
//
// public static int compare(int[] array1, int[] array2, int len1, int len2) {
//
// if (len1 > len2) return 1;
// if (len1 < len2) return -1;
//
// // arrays of the same size check elements one by one
// for (int a1 = 0; a1 < len1; a1++) {
// if (array1[a1] == array2[a1]) {
// continue;
// } else {
// return array1[a1] - array2[a1];
// }
//
// }
// return 0;
//
// }
//
// }
| import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.WritableUtils;
import de.mpii.gsm.utils.IntArrayComparator; |
// subsequences_.get(committedSubsequences_ - 1).dropRedundantGaps();
}
public void optimizeAll() {
// Flags for subsequences
// 0: subsequence not yet checked
// -1: subsequence can be omitted e.g., same subsequence exists
// >0: subsequence merged with subsequence at position = flag - 1
subsequencesFlags = new int[committedSubsequences]; // TODO: avoid new
// initially no index is built
subsequencesIndices_ = new boolean[committedSubsequences]; // TODO: avoid new
for (int subseq1 = 0; subseq1 < committedSubsequences; subseq1++) {
if (subsequencesFlags[subseq1] == 0) {
subsequencesFlags[subseq1] = subseq1 + 1;
}
if (subsequencesFlags[subseq1] == -1) {
continue;
}
for (int subseq2 = subseq1 + 1; subseq2 < committedSubsequences; subseq2++) {
if (subsequencesFlags[subseq2] == -1) {
continue;
}
boolean canBeSeparated = true;
Subsequence s1 = subsequences.get(subseq1), s2 = subsequences.get(subseq2);
// first check equivalence | // Path: src/main/java/de/mpii/gsm/utils/IntArrayComparator.java
// public class IntArrayComparator {
//
// public static int compare(int[] array1, int[] array2, int len1, int len2) {
//
// if (len1 > len2) return 1;
// if (len1 < len2) return -1;
//
// // arrays of the same size check elements one by one
// for (int a1 = 0; a1 < len1; a1++) {
// if (array1[a1] == array2[a1]) {
// continue;
// } else {
// return array1[a1] - array2[a1];
// }
//
// }
// return 0;
//
// }
//
// }
// Path: src/main/java/de/mpii/gsm/lash/encoders/SplitGapEncoder.java
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.WritableUtils;
import de.mpii.gsm.utils.IntArrayComparator;
// subsequences_.get(committedSubsequences_ - 1).dropRedundantGaps();
}
public void optimizeAll() {
// Flags for subsequences
// 0: subsequence not yet checked
// -1: subsequence can be omitted e.g., same subsequence exists
// >0: subsequence merged with subsequence at position = flag - 1
subsequencesFlags = new int[committedSubsequences]; // TODO: avoid new
// initially no index is built
subsequencesIndices_ = new boolean[committedSubsequences]; // TODO: avoid new
for (int subseq1 = 0; subseq1 < committedSubsequences; subseq1++) {
if (subsequencesFlags[subseq1] == 0) {
subsequencesFlags[subseq1] = subseq1 + 1;
}
if (subsequencesFlags[subseq1] == -1) {
continue;
}
for (int subseq2 = subseq1 + 1; subseq2 < committedSubsequences; subseq2++) {
if (subsequencesFlags[subseq2] == -1) {
continue;
}
boolean canBeSeparated = true;
Subsequence s1 = subsequences.get(subseq1), s2 = subsequences.get(subseq2);
// first check equivalence | if (IntArrayComparator |
Meituan-Dianping/walle | plugin/src/main/java/com/android/apksigner/core/ApkSignerEngine.java | // Path: plugin/src/main/java/com/android/apksigner/core/util/DataSink.java
// public interface DataSink {
//
// /**
// * Consumes the provided chunk of data.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(byte[] buf, int offset, int length) throws IOException;
//
// /**
// * Consumes all remaining data in the provided buffer and advances the buffer's position
// * to the buffer's limit.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(ByteBuffer buf) throws IOException;
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
| import java.io.Closeable;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.List;
import com.android.apksigner.core.util.DataSink;
import com.android.apksigner.core.util.DataSource; | return mInspectJarEntryRequest;
}
/**
* Output policy for an input APK's JAR entry.
*/
public static enum OutputPolicy {
/** Entry must not be output. */
SKIP,
/** Entry should be output. */
OUTPUT,
/** Entry will be output by the engine. The client can thus ignore this input entry. */
OUTPUT_BY_ENGINE,
}
}
/**
* Request to inspect the specified JAR entry.
*
* <p>The entry's uncompressed data must be provided to the data sink returned by
* {@link #getDataSink()}. Once the entry's data has been provided to the sink, {@link #done()}
* must be invoked.
*/
interface InspectJarEntryRequest {
/**
* Returns the data sink into which the entry's uncompressed data should be sent.
*/ | // Path: plugin/src/main/java/com/android/apksigner/core/util/DataSink.java
// public interface DataSink {
//
// /**
// * Consumes the provided chunk of data.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(byte[] buf, int offset, int length) throws IOException;
//
// /**
// * Consumes all remaining data in the provided buffer and advances the buffer's position
// * to the buffer's limit.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(ByteBuffer buf) throws IOException;
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
// Path: plugin/src/main/java/com/android/apksigner/core/ApkSignerEngine.java
import java.io.Closeable;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.SignatureException;
import java.util.List;
import com.android.apksigner.core.util.DataSink;
import com.android.apksigner.core.util.DataSource;
return mInspectJarEntryRequest;
}
/**
* Output policy for an input APK's JAR entry.
*/
public static enum OutputPolicy {
/** Entry must not be output. */
SKIP,
/** Entry should be output. */
OUTPUT,
/** Entry will be output by the engine. The client can thus ignore this input entry. */
OUTPUT_BY_ENGINE,
}
}
/**
* Request to inspect the specified JAR entry.
*
* <p>The entry's uncompressed data must be provided to the data sink returned by
* {@link #getDataSink()}. Once the entry's data has been provided to the sink, {@link #done()}
* must be invoked.
*/
interface InspectJarEntryRequest {
/**
* Returns the data sink into which the entry's uncompressed data should be sent.
*/ | DataSink getDataSink(); |
Meituan-Dianping/walle | walle-cli/src/main/java/com/meituan/android/walle/commands/ShowCommand.java | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelReader.java
// public final class ChannelReader {
// public static final String CHANNEL_KEY = "channel";
//
// private ChannelReader() {
// super();
// }
//
// /**
// * easy api for get channel & extra info.<br/>
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static ChannelInfo get(final File apkFile) {
// final Map<String, String> result = getMap(apkFile);
// if (result == null) {
// return null;
// }
// final String channel = result.get(CHANNEL_KEY);
// result.remove(CHANNEL_KEY);
// return new ChannelInfo(channel, result);
// }
//
// /**
// * get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static Map<String, String> getMap(final File apkFile) {
// try {
// final String rawString = getRaw(apkFile);
// if (rawString == null) {
// return null;
// }
// final JSONObject jsonObject = new JSONObject(rawString);
// final Iterator keys = jsonObject.keys();
// final Map<String, String> result = new HashMap<String, String>();
// while (keys.hasNext()) {
// final String key = keys.next().toString();
// result.put(key, jsonObject.getString(key));
// }
// return result;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * get raw string from channel id
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static String getRaw(final File apkFile) {
// return PayloadReader.getString(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
| import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.ChannelReader;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.util.List;
import java.util.Map; | package com.meituan.android.walle.commands;
@Parameters(commandDescription = "get channel info from apk and show all by default")
public class ShowCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Parameter(names = {"-e", "--extraInfo"}, description = "get channel extra info")
private boolean showExtraInfo;
@Parameter(names = {"-c", "--channel"}, description = "get channel")
private boolean shoChannel;
@Parameter(names = {"-r", "--raw"}, description = "get raw string from Channel id")
private boolean showRaw;
@Override
public void parse() {
if (showRaw) { | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelReader.java
// public final class ChannelReader {
// public static final String CHANNEL_KEY = "channel";
//
// private ChannelReader() {
// super();
// }
//
// /**
// * easy api for get channel & extra info.<br/>
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static ChannelInfo get(final File apkFile) {
// final Map<String, String> result = getMap(apkFile);
// if (result == null) {
// return null;
// }
// final String channel = result.get(CHANNEL_KEY);
// result.remove(CHANNEL_KEY);
// return new ChannelInfo(channel, result);
// }
//
// /**
// * get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static Map<String, String> getMap(final File apkFile) {
// try {
// final String rawString = getRaw(apkFile);
// if (rawString == null) {
// return null;
// }
// final JSONObject jsonObject = new JSONObject(rawString);
// final Iterator keys = jsonObject.keys();
// final Map<String, String> result = new HashMap<String, String>();
// while (keys.hasNext()) {
// final String key = keys.next().toString();
// result.put(key, jsonObject.getString(key));
// }
// return result;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * get raw string from channel id
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static String getRaw(final File apkFile) {
// return PayloadReader.getString(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
// Path: walle-cli/src/main/java/com/meituan/android/walle/commands/ShowCommand.java
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.ChannelReader;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.util.List;
import java.util.Map;
package com.meituan.android.walle.commands;
@Parameters(commandDescription = "get channel info from apk and show all by default")
public class ShowCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Parameter(names = {"-e", "--extraInfo"}, description = "get channel extra info")
private boolean showExtraInfo;
@Parameter(names = {"-c", "--channel"}, description = "get channel")
private boolean shoChannel;
@Parameter(names = {"-r", "--raw"}, description = "get raw string from Channel id")
private boolean showRaw;
@Override
public void parse() {
if (showRaw) { | printInfo(new Fun1<File, String>() { |
Meituan-Dianping/walle | walle-cli/src/main/java/com/meituan/android/walle/commands/ShowCommand.java | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelReader.java
// public final class ChannelReader {
// public static final String CHANNEL_KEY = "channel";
//
// private ChannelReader() {
// super();
// }
//
// /**
// * easy api for get channel & extra info.<br/>
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static ChannelInfo get(final File apkFile) {
// final Map<String, String> result = getMap(apkFile);
// if (result == null) {
// return null;
// }
// final String channel = result.get(CHANNEL_KEY);
// result.remove(CHANNEL_KEY);
// return new ChannelInfo(channel, result);
// }
//
// /**
// * get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static Map<String, String> getMap(final File apkFile) {
// try {
// final String rawString = getRaw(apkFile);
// if (rawString == null) {
// return null;
// }
// final JSONObject jsonObject = new JSONObject(rawString);
// final Iterator keys = jsonObject.keys();
// final Map<String, String> result = new HashMap<String, String>();
// while (keys.hasNext()) {
// final String key = keys.next().toString();
// result.put(key, jsonObject.getString(key));
// }
// return result;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * get raw string from channel id
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static String getRaw(final File apkFile) {
// return PayloadReader.getString(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
| import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.ChannelReader;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.util.List;
import java.util.Map; | package com.meituan.android.walle.commands;
@Parameters(commandDescription = "get channel info from apk and show all by default")
public class ShowCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Parameter(names = {"-e", "--extraInfo"}, description = "get channel extra info")
private boolean showExtraInfo;
@Parameter(names = {"-c", "--channel"}, description = "get channel")
private boolean shoChannel;
@Parameter(names = {"-r", "--raw"}, description = "get raw string from Channel id")
private boolean showRaw;
@Override
public void parse() {
if (showRaw) {
printInfo(new Fun1<File, String>() {
@Override
public String apply(final File file) { | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelReader.java
// public final class ChannelReader {
// public static final String CHANNEL_KEY = "channel";
//
// private ChannelReader() {
// super();
// }
//
// /**
// * easy api for get channel & extra info.<br/>
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static ChannelInfo get(final File apkFile) {
// final Map<String, String> result = getMap(apkFile);
// if (result == null) {
// return null;
// }
// final String channel = result.get(CHANNEL_KEY);
// result.remove(CHANNEL_KEY);
// return new ChannelInfo(channel, result);
// }
//
// /**
// * get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static Map<String, String> getMap(final File apkFile) {
// try {
// final String rawString = getRaw(apkFile);
// if (rawString == null) {
// return null;
// }
// final JSONObject jsonObject = new JSONObject(rawString);
// final Iterator keys = jsonObject.keys();
// final Map<String, String> result = new HashMap<String, String>();
// while (keys.hasNext()) {
// final String key = keys.next().toString();
// result.put(key, jsonObject.getString(key));
// }
// return result;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * get raw string from channel id
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static String getRaw(final File apkFile) {
// return PayloadReader.getString(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
// Path: walle-cli/src/main/java/com/meituan/android/walle/commands/ShowCommand.java
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.ChannelReader;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.util.List;
import java.util.Map;
package com.meituan.android.walle.commands;
@Parameters(commandDescription = "get channel info from apk and show all by default")
public class ShowCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Parameter(names = {"-e", "--extraInfo"}, description = "get channel extra info")
private boolean showExtraInfo;
@Parameter(names = {"-c", "--channel"}, description = "get channel")
private boolean shoChannel;
@Parameter(names = {"-r", "--raw"}, description = "get raw string from Channel id")
private boolean showRaw;
@Override
public void parse() {
if (showRaw) {
printInfo(new Fun1<File, String>() {
@Override
public String apply(final File file) { | final String rawChannelInfo = ChannelReader.getRaw(file); |
Meituan-Dianping/walle | walle-cli/src/main/java/com/meituan/android/walle/commands/ShowCommand.java | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelReader.java
// public final class ChannelReader {
// public static final String CHANNEL_KEY = "channel";
//
// private ChannelReader() {
// super();
// }
//
// /**
// * easy api for get channel & extra info.<br/>
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static ChannelInfo get(final File apkFile) {
// final Map<String, String> result = getMap(apkFile);
// if (result == null) {
// return null;
// }
// final String channel = result.get(CHANNEL_KEY);
// result.remove(CHANNEL_KEY);
// return new ChannelInfo(channel, result);
// }
//
// /**
// * get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static Map<String, String> getMap(final File apkFile) {
// try {
// final String rawString = getRaw(apkFile);
// if (rawString == null) {
// return null;
// }
// final JSONObject jsonObject = new JSONObject(rawString);
// final Iterator keys = jsonObject.keys();
// final Map<String, String> result = new HashMap<String, String>();
// while (keys.hasNext()) {
// final String key = keys.next().toString();
// result.put(key, jsonObject.getString(key));
// }
// return result;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * get raw string from channel id
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static String getRaw(final File apkFile) {
// return PayloadReader.getString(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
| import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.ChannelReader;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.util.List;
import java.util.Map; | package com.meituan.android.walle.commands;
@Parameters(commandDescription = "get channel info from apk and show all by default")
public class ShowCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Parameter(names = {"-e", "--extraInfo"}, description = "get channel extra info")
private boolean showExtraInfo;
@Parameter(names = {"-c", "--channel"}, description = "get channel")
private boolean shoChannel;
@Parameter(names = {"-r", "--raw"}, description = "get raw string from Channel id")
private boolean showRaw;
@Override
public void parse() {
if (showRaw) {
printInfo(new Fun1<File, String>() {
@Override
public String apply(final File file) {
final String rawChannelInfo = ChannelReader.getRaw(file);
return rawChannelInfo == null ? "" : rawChannelInfo;
}
});
}
if (showExtraInfo) {
printInfo(new Fun1<File, String>() {
@Override
public String apply(final File file) { | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelReader.java
// public final class ChannelReader {
// public static final String CHANNEL_KEY = "channel";
//
// private ChannelReader() {
// super();
// }
//
// /**
// * easy api for get channel & extra info.<br/>
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static ChannelInfo get(final File apkFile) {
// final Map<String, String> result = getMap(apkFile);
// if (result == null) {
// return null;
// }
// final String channel = result.get(CHANNEL_KEY);
// result.remove(CHANNEL_KEY);
// return new ChannelInfo(channel, result);
// }
//
// /**
// * get channel & extra info by map, use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} get channel
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static Map<String, String> getMap(final File apkFile) {
// try {
// final String rawString = getRaw(apkFile);
// if (rawString == null) {
// return null;
// }
// final JSONObject jsonObject = new JSONObject(rawString);
// final Iterator keys = jsonObject.keys();
// final Map<String, String> result = new HashMap<String, String>();
// while (keys.hasNext()) {
// final String key = keys.next().toString();
// result.put(key, jsonObject.getString(key));
// }
// return result;
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * get raw string from channel id
// *
// * @param apkFile apk file
// * @return null if not found
// */
// public static String getRaw(final File apkFile) {
// return PayloadReader.getString(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
// Path: walle-cli/src/main/java/com/meituan/android/walle/commands/ShowCommand.java
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.ChannelReader;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.util.List;
import java.util.Map;
package com.meituan.android.walle.commands;
@Parameters(commandDescription = "get channel info from apk and show all by default")
public class ShowCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Parameter(names = {"-e", "--extraInfo"}, description = "get channel extra info")
private boolean showExtraInfo;
@Parameter(names = {"-c", "--channel"}, description = "get channel")
private boolean shoChannel;
@Parameter(names = {"-r", "--raw"}, description = "get raw string from Channel id")
private boolean showRaw;
@Override
public void parse() {
if (showRaw) {
printInfo(new Fun1<File, String>() {
@Override
public String apply(final File file) {
final String rawChannelInfo = ChannelReader.getRaw(file);
return rawChannelInfo == null ? "" : rawChannelInfo;
}
});
}
if (showExtraInfo) {
printInfo(new Fun1<File, String>() {
@Override
public String apply(final File file) { | final ChannelInfo channelInfo = ChannelReader.get(file); |
Meituan-Dianping/walle | plugin/src/main/java/com/android/apksigner/core/internal/zip/ZipUtils.java | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/Pair.java
// public final class Pair<A, B> {
// private final A mFirst;
// private final B mSecond;
//
// private Pair(A first, B second) {
// mFirst = first;
// mSecond = second;
// }
//
// public static <A, B> Pair<A, B> of(A first, B second) {
// return new Pair<A, B>(first, second);
// }
//
// public A getFirst() {
// return mFirst;
// }
//
// public B getSecond() {
// return mSecond;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
// result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// @SuppressWarnings("rawtypes")
// Pair other = (Pair) obj;
// if (mFirst == null) {
// if (other.mFirst != null) {
// return false;
// }
// } else if (!mFirst.equals(other.mFirst)) {
// return false;
// }
// if (mSecond == null) {
// if (other.mSecond != null) {
// return false;
// }
// } else if (!mSecond.equals(other.mSecond)) {
// return false;
// }
// return true;
// }
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
| import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.android.apksigner.core.internal.util.Pair;
import com.android.apksigner.core.util.DataSource; | */
public static long getZipEocdCentralDirectorySizeBytes(ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt32(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_SIZE_FIELD_OFFSET);
}
/**
* Returns the total number of records in ZIP Central Directory.
*
* <p>NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian.
*/
public static int getZipEocdCentralDirectoryTotalRecordCount(
ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt16(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position()
+ ZIP_EOCD_CENTRAL_DIR_TOTAL_RECORD_COUNT_OFFSET);
}
/**
* Returns the ZIP End of Central Directory record of the provided ZIP file.
*
* @return contents of the ZIP End of Central Directory record and the record's offset in the
* file or {@code null} if the file does not contain the record.
*
* @throws IOException if an I/O error occurs while reading the file.
*/ | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/Pair.java
// public final class Pair<A, B> {
// private final A mFirst;
// private final B mSecond;
//
// private Pair(A first, B second) {
// mFirst = first;
// mSecond = second;
// }
//
// public static <A, B> Pair<A, B> of(A first, B second) {
// return new Pair<A, B>(first, second);
// }
//
// public A getFirst() {
// return mFirst;
// }
//
// public B getSecond() {
// return mSecond;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
// result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// @SuppressWarnings("rawtypes")
// Pair other = (Pair) obj;
// if (mFirst == null) {
// if (other.mFirst != null) {
// return false;
// }
// } else if (!mFirst.equals(other.mFirst)) {
// return false;
// }
// if (mSecond == null) {
// if (other.mSecond != null) {
// return false;
// }
// } else if (!mSecond.equals(other.mSecond)) {
// return false;
// }
// return true;
// }
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
// Path: plugin/src/main/java/com/android/apksigner/core/internal/zip/ZipUtils.java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.android.apksigner.core.internal.util.Pair;
import com.android.apksigner.core.util.DataSource;
*/
public static long getZipEocdCentralDirectorySizeBytes(ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt32(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_SIZE_FIELD_OFFSET);
}
/**
* Returns the total number of records in ZIP Central Directory.
*
* <p>NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian.
*/
public static int getZipEocdCentralDirectoryTotalRecordCount(
ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt16(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position()
+ ZIP_EOCD_CENTRAL_DIR_TOTAL_RECORD_COUNT_OFFSET);
}
/**
* Returns the ZIP End of Central Directory record of the provided ZIP file.
*
* @return contents of the ZIP End of Central Directory record and the record's offset in the
* file or {@code null} if the file does not contain the record.
*
* @throws IOException if an I/O error occurs while reading the file.
*/ | public static Pair<ByteBuffer, Long> findZipEndOfCentralDirectoryRecord(DataSource zip) |
Meituan-Dianping/walle | plugin/src/main/java/com/android/apksigner/core/internal/zip/ZipUtils.java | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/Pair.java
// public final class Pair<A, B> {
// private final A mFirst;
// private final B mSecond;
//
// private Pair(A first, B second) {
// mFirst = first;
// mSecond = second;
// }
//
// public static <A, B> Pair<A, B> of(A first, B second) {
// return new Pair<A, B>(first, second);
// }
//
// public A getFirst() {
// return mFirst;
// }
//
// public B getSecond() {
// return mSecond;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
// result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// @SuppressWarnings("rawtypes")
// Pair other = (Pair) obj;
// if (mFirst == null) {
// if (other.mFirst != null) {
// return false;
// }
// } else if (!mFirst.equals(other.mFirst)) {
// return false;
// }
// if (mSecond == null) {
// if (other.mSecond != null) {
// return false;
// }
// } else if (!mSecond.equals(other.mSecond)) {
// return false;
// }
// return true;
// }
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
| import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.android.apksigner.core.internal.util.Pair;
import com.android.apksigner.core.util.DataSource; | */
public static long getZipEocdCentralDirectorySizeBytes(ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt32(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_SIZE_FIELD_OFFSET);
}
/**
* Returns the total number of records in ZIP Central Directory.
*
* <p>NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian.
*/
public static int getZipEocdCentralDirectoryTotalRecordCount(
ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt16(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position()
+ ZIP_EOCD_CENTRAL_DIR_TOTAL_RECORD_COUNT_OFFSET);
}
/**
* Returns the ZIP End of Central Directory record of the provided ZIP file.
*
* @return contents of the ZIP End of Central Directory record and the record's offset in the
* file or {@code null} if the file does not contain the record.
*
* @throws IOException if an I/O error occurs while reading the file.
*/ | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/Pair.java
// public final class Pair<A, B> {
// private final A mFirst;
// private final B mSecond;
//
// private Pair(A first, B second) {
// mFirst = first;
// mSecond = second;
// }
//
// public static <A, B> Pair<A, B> of(A first, B second) {
// return new Pair<A, B>(first, second);
// }
//
// public A getFirst() {
// return mFirst;
// }
//
// public B getSecond() {
// return mSecond;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
// result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// @SuppressWarnings("rawtypes")
// Pair other = (Pair) obj;
// if (mFirst == null) {
// if (other.mFirst != null) {
// return false;
// }
// } else if (!mFirst.equals(other.mFirst)) {
// return false;
// }
// if (mSecond == null) {
// if (other.mSecond != null) {
// return false;
// }
// } else if (!mSecond.equals(other.mSecond)) {
// return false;
// }
// return true;
// }
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
// Path: plugin/src/main/java/com/android/apksigner/core/internal/zip/ZipUtils.java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import com.android.apksigner.core.internal.util.Pair;
import com.android.apksigner.core.util.DataSource;
*/
public static long getZipEocdCentralDirectorySizeBytes(ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt32(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position() + ZIP_EOCD_CENTRAL_DIR_SIZE_FIELD_OFFSET);
}
/**
* Returns the total number of records in ZIP Central Directory.
*
* <p>NOTE: Byte order of {@code zipEndOfCentralDirectory} must be little-endian.
*/
public static int getZipEocdCentralDirectoryTotalRecordCount(
ByteBuffer zipEndOfCentralDirectory) {
assertByteOrderLittleEndian(zipEndOfCentralDirectory);
return getUnsignedInt16(
zipEndOfCentralDirectory,
zipEndOfCentralDirectory.position()
+ ZIP_EOCD_CENTRAL_DIR_TOTAL_RECORD_COUNT_OFFSET);
}
/**
* Returns the ZIP End of Central Directory record of the provided ZIP file.
*
* @return contents of the ZIP End of Central Directory record and the record's offset in the
* file or {@code null} if the file does not contain the record.
*
* @throws IOException if an I/O error occurs while reading the file.
*/ | public static Pair<ByteBuffer, Long> findZipEndOfCentralDirectoryRecord(DataSource zip) |
Meituan-Dianping/walle | walle-cli/src/main/java/com/meituan/android/walle/commands/RemoveCommand.java | // Path: payload_writer/src/main/java/com/meituan/android/walle/ChannelWriter.java
// public final class ChannelWriter {
// private ChannelWriter() {
// super();
// }
//
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, false);
// }
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, null, lowMemory);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, extraInfo, false);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// final Map<String, String> newData = new HashMap<String, String>();
// final Map<String, String> existsData = ChannelReader.getMap(apkFile);
// if (existsData != null) {
// newData.putAll(existsData);
// }
// if (extraInfo != null) {
// // can't use
// extraInfo.remove(ChannelReader.CHANNEL_KEY);
// newData.putAll(extraInfo);
// }
// if (channel != null && channel.length() > 0) {
// newData.put(ChannelReader.CHANNEL_KEY, channel);
// }
// final JSONObject jsonObject = new JSONObject(newData);
// putRaw(apkFile, jsonObject.toString(), lowMemory);
// }
// /**
// * write custom content with channel fixed id <br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string) throws IOException, SignatureNotFoundException {
// putRaw(apkFile, string, false);
// }
// /**
// * write custom content with channel fixed id<br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.put(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, string, lowMemory);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile) throws IOException, SignatureNotFoundException {
// remove(apkFile, false);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.remove(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, lowMemory);
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/SignatureNotFoundException.java
// public class SignatureNotFoundException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public SignatureNotFoundException(final String message) {
// super(message);
// }
//
// public SignatureNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
| import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.io.IOException;
import java.util.List; | package com.meituan.android.walle.commands;
@Parameters(commandDescription = "remove channel info for apk")
public class RemoveCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Override
public void parse() { | // Path: payload_writer/src/main/java/com/meituan/android/walle/ChannelWriter.java
// public final class ChannelWriter {
// private ChannelWriter() {
// super();
// }
//
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, false);
// }
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, null, lowMemory);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, extraInfo, false);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// final Map<String, String> newData = new HashMap<String, String>();
// final Map<String, String> existsData = ChannelReader.getMap(apkFile);
// if (existsData != null) {
// newData.putAll(existsData);
// }
// if (extraInfo != null) {
// // can't use
// extraInfo.remove(ChannelReader.CHANNEL_KEY);
// newData.putAll(extraInfo);
// }
// if (channel != null && channel.length() > 0) {
// newData.put(ChannelReader.CHANNEL_KEY, channel);
// }
// final JSONObject jsonObject = new JSONObject(newData);
// putRaw(apkFile, jsonObject.toString(), lowMemory);
// }
// /**
// * write custom content with channel fixed id <br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string) throws IOException, SignatureNotFoundException {
// putRaw(apkFile, string, false);
// }
// /**
// * write custom content with channel fixed id<br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.put(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, string, lowMemory);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile) throws IOException, SignatureNotFoundException {
// remove(apkFile, false);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.remove(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, lowMemory);
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/SignatureNotFoundException.java
// public class SignatureNotFoundException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public SignatureNotFoundException(final String message) {
// super(message);
// }
//
// public SignatureNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
// Path: walle-cli/src/main/java/com/meituan/android/walle/commands/RemoveCommand.java
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.io.IOException;
import java.util.List;
package com.meituan.android.walle.commands;
@Parameters(commandDescription = "remove channel info for apk")
public class RemoveCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Override
public void parse() { | removeInfo(new Fun1<File, Boolean>() { |
Meituan-Dianping/walle | walle-cli/src/main/java/com/meituan/android/walle/commands/RemoveCommand.java | // Path: payload_writer/src/main/java/com/meituan/android/walle/ChannelWriter.java
// public final class ChannelWriter {
// private ChannelWriter() {
// super();
// }
//
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, false);
// }
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, null, lowMemory);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, extraInfo, false);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// final Map<String, String> newData = new HashMap<String, String>();
// final Map<String, String> existsData = ChannelReader.getMap(apkFile);
// if (existsData != null) {
// newData.putAll(existsData);
// }
// if (extraInfo != null) {
// // can't use
// extraInfo.remove(ChannelReader.CHANNEL_KEY);
// newData.putAll(extraInfo);
// }
// if (channel != null && channel.length() > 0) {
// newData.put(ChannelReader.CHANNEL_KEY, channel);
// }
// final JSONObject jsonObject = new JSONObject(newData);
// putRaw(apkFile, jsonObject.toString(), lowMemory);
// }
// /**
// * write custom content with channel fixed id <br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string) throws IOException, SignatureNotFoundException {
// putRaw(apkFile, string, false);
// }
// /**
// * write custom content with channel fixed id<br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.put(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, string, lowMemory);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile) throws IOException, SignatureNotFoundException {
// remove(apkFile, false);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.remove(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, lowMemory);
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/SignatureNotFoundException.java
// public class SignatureNotFoundException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public SignatureNotFoundException(final String message) {
// super(message);
// }
//
// public SignatureNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
| import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.io.IOException;
import java.util.List; | package com.meituan.android.walle.commands;
@Parameters(commandDescription = "remove channel info for apk")
public class RemoveCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Override
public void parse() {
removeInfo(new Fun1<File, Boolean>() {
@Override
public Boolean apply(final File file) {
try { | // Path: payload_writer/src/main/java/com/meituan/android/walle/ChannelWriter.java
// public final class ChannelWriter {
// private ChannelWriter() {
// super();
// }
//
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, false);
// }
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, null, lowMemory);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, extraInfo, false);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// final Map<String, String> newData = new HashMap<String, String>();
// final Map<String, String> existsData = ChannelReader.getMap(apkFile);
// if (existsData != null) {
// newData.putAll(existsData);
// }
// if (extraInfo != null) {
// // can't use
// extraInfo.remove(ChannelReader.CHANNEL_KEY);
// newData.putAll(extraInfo);
// }
// if (channel != null && channel.length() > 0) {
// newData.put(ChannelReader.CHANNEL_KEY, channel);
// }
// final JSONObject jsonObject = new JSONObject(newData);
// putRaw(apkFile, jsonObject.toString(), lowMemory);
// }
// /**
// * write custom content with channel fixed id <br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string) throws IOException, SignatureNotFoundException {
// putRaw(apkFile, string, false);
// }
// /**
// * write custom content with channel fixed id<br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.put(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, string, lowMemory);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile) throws IOException, SignatureNotFoundException {
// remove(apkFile, false);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.remove(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, lowMemory);
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/SignatureNotFoundException.java
// public class SignatureNotFoundException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public SignatureNotFoundException(final String message) {
// super(message);
// }
//
// public SignatureNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
// Path: walle-cli/src/main/java/com/meituan/android/walle/commands/RemoveCommand.java
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.io.IOException;
import java.util.List;
package com.meituan.android.walle.commands;
@Parameters(commandDescription = "remove channel info for apk")
public class RemoveCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Override
public void parse() {
removeInfo(new Fun1<File, Boolean>() {
@Override
public Boolean apply(final File file) {
try { | ChannelWriter.remove(file); |
Meituan-Dianping/walle | walle-cli/src/main/java/com/meituan/android/walle/commands/RemoveCommand.java | // Path: payload_writer/src/main/java/com/meituan/android/walle/ChannelWriter.java
// public final class ChannelWriter {
// private ChannelWriter() {
// super();
// }
//
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, false);
// }
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, null, lowMemory);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, extraInfo, false);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// final Map<String, String> newData = new HashMap<String, String>();
// final Map<String, String> existsData = ChannelReader.getMap(apkFile);
// if (existsData != null) {
// newData.putAll(existsData);
// }
// if (extraInfo != null) {
// // can't use
// extraInfo.remove(ChannelReader.CHANNEL_KEY);
// newData.putAll(extraInfo);
// }
// if (channel != null && channel.length() > 0) {
// newData.put(ChannelReader.CHANNEL_KEY, channel);
// }
// final JSONObject jsonObject = new JSONObject(newData);
// putRaw(apkFile, jsonObject.toString(), lowMemory);
// }
// /**
// * write custom content with channel fixed id <br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string) throws IOException, SignatureNotFoundException {
// putRaw(apkFile, string, false);
// }
// /**
// * write custom content with channel fixed id<br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.put(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, string, lowMemory);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile) throws IOException, SignatureNotFoundException {
// remove(apkFile, false);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.remove(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, lowMemory);
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/SignatureNotFoundException.java
// public class SignatureNotFoundException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public SignatureNotFoundException(final String message) {
// super(message);
// }
//
// public SignatureNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
| import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.io.IOException;
import java.util.List; | package com.meituan.android.walle.commands;
@Parameters(commandDescription = "remove channel info for apk")
public class RemoveCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Override
public void parse() {
removeInfo(new Fun1<File, Boolean>() {
@Override
public Boolean apply(final File file) {
try {
ChannelWriter.remove(file);
return true; | // Path: payload_writer/src/main/java/com/meituan/android/walle/ChannelWriter.java
// public final class ChannelWriter {
// private ChannelWriter() {
// super();
// }
//
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, false);
// }
// /**
// * write channel with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, null, lowMemory);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo) throws IOException, SignatureNotFoundException {
// put(apkFile, channel, extraInfo, false);
// }
// /**
// * write channel & extra info with channel fixed id
// *
// * @param apkFile apk file
// * @param channel channel (nullable)
// * @param extraInfo extra info (don't use {@link ChannelReader#CHANNEL_KEY PayloadReader.CHANNEL_KEY} as your key)
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void put(final File apkFile, final String channel, final Map<String, String> extraInfo, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// final Map<String, String> newData = new HashMap<String, String>();
// final Map<String, String> existsData = ChannelReader.getMap(apkFile);
// if (existsData != null) {
// newData.putAll(existsData);
// }
// if (extraInfo != null) {
// // can't use
// extraInfo.remove(ChannelReader.CHANNEL_KEY);
// newData.putAll(extraInfo);
// }
// if (channel != null && channel.length() > 0) {
// newData.put(ChannelReader.CHANNEL_KEY, channel);
// }
// final JSONObject jsonObject = new JSONObject(newData);
// putRaw(apkFile, jsonObject.toString(), lowMemory);
// }
// /**
// * write custom content with channel fixed id <br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string) throws IOException, SignatureNotFoundException {
// putRaw(apkFile, string, false);
// }
// /**
// * write custom content with channel fixed id<br/>
// * NOTE: {@link ChannelReader#get(File)} and {@link ChannelReader#getMap(File)} may be affected
// *
// * @param apkFile apk file
// * @param string custom content
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void putRaw(final File apkFile, final String string, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.put(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, string, lowMemory);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile) throws IOException, SignatureNotFoundException {
// remove(apkFile, false);
// }
// /**
// * remove channel id content
// *
// * @param apkFile apk file
// * @param lowMemory if need low memory operation, maybe a little slower
// * @throws IOException
// * @throws SignatureNotFoundException
// */
// public static void remove(final File apkFile, final boolean lowMemory) throws IOException, SignatureNotFoundException {
// PayloadWriter.remove(apkFile, ApkUtil.APK_CHANNEL_BLOCK_ID, lowMemory);
// }
// }
//
// Path: payload_reader/src/main/java/com/meituan/android/walle/SignatureNotFoundException.java
// public class SignatureNotFoundException extends Exception {
// private static final long serialVersionUID = 1L;
//
// public SignatureNotFoundException(final String message) {
// super(message);
// }
//
// public SignatureNotFoundException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: walle-cli/src/main/java/com/meituan/android/walle/utils/Fun1.java
// public interface Fun1<T, R> {
// R apply(T v);
// }
// Path: walle-cli/src/main/java/com/meituan/android/walle/commands/RemoveCommand.java
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.converters.FileConverter;
import com.meituan.android.walle.ChannelWriter;
import com.meituan.android.walle.SignatureNotFoundException;
import com.meituan.android.walle.utils.Fun1;
import java.io.File;
import java.io.IOException;
import java.util.List;
package com.meituan.android.walle.commands;
@Parameters(commandDescription = "remove channel info for apk")
public class RemoveCommand implements IWalleCommand {
@Parameter(required = true, description = "file1 file2 file3 ...", converter = FileConverter.class, variableArity = true)
private List<File> files;
@Override
public void parse() {
removeInfo(new Fun1<File, Boolean>() {
@Override
public Boolean apply(final File file) {
try {
ChannelWriter.remove(file);
return true; | } catch (IOException | SignatureNotFoundException e) { |
Meituan-Dianping/walle | plugin/src/main/java/com/android/apksigner/core/internal/apk/v2/SignatureAlgorithm.java | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/Pair.java
// public final class Pair<A, B> {
// private final A mFirst;
// private final B mSecond;
//
// private Pair(A first, B second) {
// mFirst = first;
// mSecond = second;
// }
//
// public static <A, B> Pair<A, B> of(A first, B second) {
// return new Pair<A, B>(first, second);
// }
//
// public A getFirst() {
// return mFirst;
// }
//
// public B getSecond() {
// return mSecond;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
// result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// @SuppressWarnings("rawtypes")
// Pair other = (Pair) obj;
// if (mFirst == null) {
// if (other.mFirst != null) {
// return false;
// }
// } else if (!mFirst.equals(other.mFirst)) {
// return false;
// }
// if (mSecond == null) {
// if (other.mSecond != null) {
// return false;
// }
// } else if (!mSecond.equals(other.mSecond)) {
// return false;
// }
// return true;
// }
// }
| import com.android.apksigner.core.internal.util.Pair;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec; | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.apksigner.core.internal.apk.v2;
/**
* APK Signature Scheme v2 signature algorithm.
*/
public enum SignatureAlgorithm {
/**
* RSASSA-PSS with SHA2-256 digest, SHA2-256 MGF1, 32 bytes of salt, trailer: 0xbc, content
* digested using SHA2-256 in 1 MB chunks.
*/
RSA_PSS_WITH_SHA256(
0x0101,
ContentDigestAlgorithm.CHUNKED_SHA256,
"RSA", | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/Pair.java
// public final class Pair<A, B> {
// private final A mFirst;
// private final B mSecond;
//
// private Pair(A first, B second) {
// mFirst = first;
// mSecond = second;
// }
//
// public static <A, B> Pair<A, B> of(A first, B second) {
// return new Pair<A, B>(first, second);
// }
//
// public A getFirst() {
// return mFirst;
// }
//
// public B getSecond() {
// return mSecond;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((mFirst == null) ? 0 : mFirst.hashCode());
// result = prime * result + ((mSecond == null) ? 0 : mSecond.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// @SuppressWarnings("rawtypes")
// Pair other = (Pair) obj;
// if (mFirst == null) {
// if (other.mFirst != null) {
// return false;
// }
// } else if (!mFirst.equals(other.mFirst)) {
// return false;
// }
// if (mSecond == null) {
// if (other.mSecond != null) {
// return false;
// }
// } else if (!mSecond.equals(other.mSecond)) {
// return false;
// }
// return true;
// }
// }
// Path: plugin/src/main/java/com/android/apksigner/core/internal/apk/v2/SignatureAlgorithm.java
import com.android.apksigner.core.internal.util.Pair;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.apksigner.core.internal.apk.v2;
/**
* APK Signature Scheme v2 signature algorithm.
*/
public enum SignatureAlgorithm {
/**
* RSASSA-PSS with SHA2-256 digest, SHA2-256 MGF1, 32 bytes of salt, trailer: 0xbc, content
* digested using SHA2-256 in 1 MB chunks.
*/
RSA_PSS_WITH_SHA256(
0x0101,
ContentDigestAlgorithm.CHUNKED_SHA256,
"RSA", | Pair.of("SHA256withRSA/PSS", |
Meituan-Dianping/walle | plugin/src/main/java/com/android/apksigner/core/internal/util/ByteBufferDataSource.java | // Path: plugin/src/main/java/com/android/apksigner/core/util/DataSink.java
// public interface DataSink {
//
// /**
// * Consumes the provided chunk of data.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(byte[] buf, int offset, int length) throws IOException;
//
// /**
// * Consumes all remaining data in the provided buffer and advances the buffer's position
// * to the buffer's limit.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(ByteBuffer buf) throws IOException;
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
| import com.android.apksigner.core.util.DataSink;
import com.android.apksigner.core.util.DataSource;
import java.io.IOException;
import java.nio.ByteBuffer; |
@Override
public ByteBuffer getByteBuffer(long offset, int size) {
checkChunkValid(offset, size);
// checkChunkValid ensures that it's OK to cast offset to int.
int chunkPosition = (int) offset;
int chunkLimit = chunkPosition + size;
// Creating a slice of ByteBuffer modifies the state of the source ByteBuffer (position
// and limit fields, to be more specific). We thus use synchronization around these
// state-changing operations to make instances of this class thread-safe.
synchronized (mBuffer) {
// ByteBuffer.limit(int) and .position(int) check that that the position >= limit
// invariant is not broken. Thus, the only way to safely change position and limit
// without caring about their current values is to first set position to 0 or set the
// limit to capacity.
mBuffer.position(0);
mBuffer.limit(chunkLimit);
mBuffer.position(chunkPosition);
return mBuffer.slice();
}
}
@Override
public void copyTo(long offset, int size, ByteBuffer dest) {
dest.put(getByteBuffer(offset, size));
}
@Override | // Path: plugin/src/main/java/com/android/apksigner/core/util/DataSink.java
// public interface DataSink {
//
// /**
// * Consumes the provided chunk of data.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(byte[] buf, int offset, int length) throws IOException;
//
// /**
// * Consumes all remaining data in the provided buffer and advances the buffer's position
// * to the buffer's limit.
// *
// * <p>This data sink guarantees to not hold references to the provided buffer after this method
// * terminates.
// */
// void consume(ByteBuffer buf) throws IOException;
// }
//
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSource.java
// public interface DataSource {
//
// /**
// * Returns the amount of data (in bytes) contained in this data source.
// */
// long size();
//
// /**
// * Feeds the specified chunk from this data source into the provided sink.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void feed(long offset, long size, DataSink sink) throws IOException;
//
// /**
// * Returns a buffer holding the contents of the specified chunk of data from this data source.
// * Changes to the data source are not guaranteed to be reflected in the returned buffer.
// * Similarly, changes in the buffer are not guaranteed to be reflected in the data source.
// *
// * <p>The returned buffer's position is {@code 0}, and the buffer's limit and capacity is
// * {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// ByteBuffer getByteBuffer(long offset, int size) throws IOException;
//
// /**
// * Copies the specified chunk from this data source into the provided destination buffer,
// * advancing the destination buffer's position by {@code size}.
// *
// * @param offset index (in bytes) at which the chunk starts inside data source
// * @param size size (in bytes) of the chunk
// */
// void copyTo(long offset, int size, ByteBuffer dest) throws IOException;
//
// /**
// * Returns a data source representing the specified region of data of this data source. Changes
// * to data represented by this data source will also be visible in the returned data source.
// *
// * @param offset index (in bytes) at which the region starts inside data source
// * @param size size (in bytes) of the region
// */
// DataSource slice(long offset, long size);
// }
// Path: plugin/src/main/java/com/android/apksigner/core/internal/util/ByteBufferDataSource.java
import com.android.apksigner.core.util.DataSink;
import com.android.apksigner.core.util.DataSource;
import java.io.IOException;
import java.nio.ByteBuffer;
@Override
public ByteBuffer getByteBuffer(long offset, int size) {
checkChunkValid(offset, size);
// checkChunkValid ensures that it's OK to cast offset to int.
int chunkPosition = (int) offset;
int chunkLimit = chunkPosition + size;
// Creating a slice of ByteBuffer modifies the state of the source ByteBuffer (position
// and limit fields, to be more specific). We thus use synchronization around these
// state-changing operations to make instances of this class thread-safe.
synchronized (mBuffer) {
// ByteBuffer.limit(int) and .position(int) check that that the position >= limit
// invariant is not broken. Thus, the only way to safely change position and limit
// without caring about their current values is to first set position to 0 or set the
// limit to capacity.
mBuffer.position(0);
mBuffer.limit(chunkLimit);
mBuffer.position(chunkPosition);
return mBuffer.slice();
}
}
@Override
public void copyTo(long offset, int size, ByteBuffer dest) {
dest.put(getByteBuffer(offset, size));
}
@Override | public void feed(long offset, long size, DataSink sink) throws IOException { |
Meituan-Dianping/walle | app/src/main/java/com/meituan/android/walle/sample/MainActivity.java | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: library/src/main/java/com/meituan/android/walle/WalleChannelReader.java
// public final class WalleChannelReader {
// private WalleChannelReader() {
// super();
// }
//
// /**
// * get channel
// *
// * @param context context
// * @return channel, null if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context) {
// return getChannel(context, null);
// }
//
// /**
// * get channel or default
// *
// * @param context context
// * @param defaultChannel default channel
// * @return channel, default if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context, @NonNull final String defaultChannel) {
// final ChannelInfo channelInfo = getChannelInfo(context);
// if (channelInfo == null) {
// return defaultChannel;
// }
// return channelInfo.getChannel();
// }
//
// /**
// * get channel info (include channle & extraInfo)
// *
// * @param context context
// * @return channel info
// */
// @Nullable
// public static ChannelInfo getChannelInfo(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.get(new File(apkPath));
// }
//
// /**
// * get value by key
// *
// * @param context context
// * @param key the key you store
// * @return value
// */
// @Nullable
// public static String get(@NonNull final Context context, @NonNull final String key) {
// final Map<String, String> channelMap = getChannelInfoMap(context);
// if (channelMap == null) {
// return null;
// }
// return channelMap.get(key);
// }
//
// /**
// * get all channl info with map
// *
// * @param context context
// * @return map
// */
// @Nullable
// public static Map<String, String> getChannelInfoMap(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.getMap(new File(apkPath));
// }
//
// @Nullable
// private static String getApkPath(@NonNull final Context context) {
// String apkPath = null;
// try {
// final ApplicationInfo applicationInfo = context.getApplicationInfo();
// if (applicationInfo == null) {
// return null;
// }
// apkPath = applicationInfo.sourceDir;
// } catch (Throwable e) {
// }
// return apkPath;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.WalleChannelReader; | package com.meituan.android.walle.sample;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.read_channel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
readChannel();
}
});
}
private void readChannel() {
final TextView tv = (TextView) findViewById(R.id.tv_channel);
final long startTime = System.currentTimeMillis(); | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: library/src/main/java/com/meituan/android/walle/WalleChannelReader.java
// public final class WalleChannelReader {
// private WalleChannelReader() {
// super();
// }
//
// /**
// * get channel
// *
// * @param context context
// * @return channel, null if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context) {
// return getChannel(context, null);
// }
//
// /**
// * get channel or default
// *
// * @param context context
// * @param defaultChannel default channel
// * @return channel, default if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context, @NonNull final String defaultChannel) {
// final ChannelInfo channelInfo = getChannelInfo(context);
// if (channelInfo == null) {
// return defaultChannel;
// }
// return channelInfo.getChannel();
// }
//
// /**
// * get channel info (include channle & extraInfo)
// *
// * @param context context
// * @return channel info
// */
// @Nullable
// public static ChannelInfo getChannelInfo(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.get(new File(apkPath));
// }
//
// /**
// * get value by key
// *
// * @param context context
// * @param key the key you store
// * @return value
// */
// @Nullable
// public static String get(@NonNull final Context context, @NonNull final String key) {
// final Map<String, String> channelMap = getChannelInfoMap(context);
// if (channelMap == null) {
// return null;
// }
// return channelMap.get(key);
// }
//
// /**
// * get all channl info with map
// *
// * @param context context
// * @return map
// */
// @Nullable
// public static Map<String, String> getChannelInfoMap(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.getMap(new File(apkPath));
// }
//
// @Nullable
// private static String getApkPath(@NonNull final Context context) {
// String apkPath = null;
// try {
// final ApplicationInfo applicationInfo = context.getApplicationInfo();
// if (applicationInfo == null) {
// return null;
// }
// apkPath = applicationInfo.sourceDir;
// } catch (Throwable e) {
// }
// return apkPath;
// }
// }
// Path: app/src/main/java/com/meituan/android/walle/sample/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.WalleChannelReader;
package com.meituan.android.walle.sample;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.read_channel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
readChannel();
}
});
}
private void readChannel() {
final TextView tv = (TextView) findViewById(R.id.tv_channel);
final long startTime = System.currentTimeMillis(); | final ChannelInfo channelInfo = WalleChannelReader.getChannelInfo(this.getApplicationContext()); |
Meituan-Dianping/walle | app/src/main/java/com/meituan/android/walle/sample/MainActivity.java | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: library/src/main/java/com/meituan/android/walle/WalleChannelReader.java
// public final class WalleChannelReader {
// private WalleChannelReader() {
// super();
// }
//
// /**
// * get channel
// *
// * @param context context
// * @return channel, null if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context) {
// return getChannel(context, null);
// }
//
// /**
// * get channel or default
// *
// * @param context context
// * @param defaultChannel default channel
// * @return channel, default if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context, @NonNull final String defaultChannel) {
// final ChannelInfo channelInfo = getChannelInfo(context);
// if (channelInfo == null) {
// return defaultChannel;
// }
// return channelInfo.getChannel();
// }
//
// /**
// * get channel info (include channle & extraInfo)
// *
// * @param context context
// * @return channel info
// */
// @Nullable
// public static ChannelInfo getChannelInfo(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.get(new File(apkPath));
// }
//
// /**
// * get value by key
// *
// * @param context context
// * @param key the key you store
// * @return value
// */
// @Nullable
// public static String get(@NonNull final Context context, @NonNull final String key) {
// final Map<String, String> channelMap = getChannelInfoMap(context);
// if (channelMap == null) {
// return null;
// }
// return channelMap.get(key);
// }
//
// /**
// * get all channl info with map
// *
// * @param context context
// * @return map
// */
// @Nullable
// public static Map<String, String> getChannelInfoMap(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.getMap(new File(apkPath));
// }
//
// @Nullable
// private static String getApkPath(@NonNull final Context context) {
// String apkPath = null;
// try {
// final ApplicationInfo applicationInfo = context.getApplicationInfo();
// if (applicationInfo == null) {
// return null;
// }
// apkPath = applicationInfo.sourceDir;
// } catch (Throwable e) {
// }
// return apkPath;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.WalleChannelReader; | package com.meituan.android.walle.sample;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.read_channel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
readChannel();
}
});
}
private void readChannel() {
final TextView tv = (TextView) findViewById(R.id.tv_channel);
final long startTime = System.currentTimeMillis(); | // Path: payload_reader/src/main/java/com/meituan/android/walle/ChannelInfo.java
// public class ChannelInfo {
// private final String channel;
// private final Map<String, String> extraInfo;
//
// public ChannelInfo(final String channel, final Map<String, String> extraInfo) {
// this.channel = channel;
// this.extraInfo = extraInfo;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public Map<String, String> getExtraInfo() {
// return extraInfo;
// }
// }
//
// Path: library/src/main/java/com/meituan/android/walle/WalleChannelReader.java
// public final class WalleChannelReader {
// private WalleChannelReader() {
// super();
// }
//
// /**
// * get channel
// *
// * @param context context
// * @return channel, null if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context) {
// return getChannel(context, null);
// }
//
// /**
// * get channel or default
// *
// * @param context context
// * @param defaultChannel default channel
// * @return channel, default if not fount
// */
// @Nullable
// public static String getChannel(@NonNull final Context context, @NonNull final String defaultChannel) {
// final ChannelInfo channelInfo = getChannelInfo(context);
// if (channelInfo == null) {
// return defaultChannel;
// }
// return channelInfo.getChannel();
// }
//
// /**
// * get channel info (include channle & extraInfo)
// *
// * @param context context
// * @return channel info
// */
// @Nullable
// public static ChannelInfo getChannelInfo(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.get(new File(apkPath));
// }
//
// /**
// * get value by key
// *
// * @param context context
// * @param key the key you store
// * @return value
// */
// @Nullable
// public static String get(@NonNull final Context context, @NonNull final String key) {
// final Map<String, String> channelMap = getChannelInfoMap(context);
// if (channelMap == null) {
// return null;
// }
// return channelMap.get(key);
// }
//
// /**
// * get all channl info with map
// *
// * @param context context
// * @return map
// */
// @Nullable
// public static Map<String, String> getChannelInfoMap(@NonNull final Context context) {
// final String apkPath = getApkPath(context);
// if (TextUtils.isEmpty(apkPath)) {
// return null;
// }
// return ChannelReader.getMap(new File(apkPath));
// }
//
// @Nullable
// private static String getApkPath(@NonNull final Context context) {
// String apkPath = null;
// try {
// final ApplicationInfo applicationInfo = context.getApplicationInfo();
// if (applicationInfo == null) {
// return null;
// }
// apkPath = applicationInfo.sourceDir;
// } catch (Throwable e) {
// }
// return apkPath;
// }
// }
// Path: app/src/main/java/com/meituan/android/walle/sample/MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.meituan.android.walle.ChannelInfo;
import com.meituan.android.walle.WalleChannelReader;
package com.meituan.android.walle.sample;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.read_channel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
readChannel();
}
});
}
private void readChannel() {
final TextView tv = (TextView) findViewById(R.id.tv_channel);
final long startTime = System.currentTimeMillis(); | final ChannelInfo channelInfo = WalleChannelReader.getChannelInfo(this.getApplicationContext()); |
Meituan-Dianping/walle | plugin/src/main/java/com/android/apksigner/core/util/DataSources.java | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/ByteBufferDataSource.java
// public class ByteBufferDataSource implements DataSource {
//
// private final ByteBuffer mBuffer;
// private final int mSize;
//
// /**
// * Constructs a new {@code ByteBufferDigestSource} based on the data contained in the provided
// * buffer between the buffer's position and limit.
// */
// public ByteBufferDataSource(ByteBuffer buffer) {
// this(buffer, true);
// }
//
// /**
// * Constructs a new {@code ByteBufferDigestSource} based on the data contained in the provided
// * buffer between the buffer's position and limit.
// */
// private ByteBufferDataSource(ByteBuffer buffer, boolean sliceRequired) {
// mBuffer = (sliceRequired) ? buffer.slice() : buffer;
// mSize = buffer.remaining();
// }
//
// @Override
// public long size() {
// return mSize;
// }
//
// @Override
// public ByteBuffer getByteBuffer(long offset, int size) {
// checkChunkValid(offset, size);
//
// // checkChunkValid ensures that it's OK to cast offset to int.
// int chunkPosition = (int) offset;
// int chunkLimit = chunkPosition + size;
// // Creating a slice of ByteBuffer modifies the state of the source ByteBuffer (position
// // and limit fields, to be more specific). We thus use synchronization around these
// // state-changing operations to make instances of this class thread-safe.
// synchronized (mBuffer) {
// // ByteBuffer.limit(int) and .position(int) check that that the position >= limit
// // invariant is not broken. Thus, the only way to safely change position and limit
// // without caring about their current values is to first set position to 0 or set the
// // limit to capacity.
// mBuffer.position(0);
//
// mBuffer.limit(chunkLimit);
// mBuffer.position(chunkPosition);
// return mBuffer.slice();
// }
// }
//
// @Override
// public void copyTo(long offset, int size, ByteBuffer dest) {
// dest.put(getByteBuffer(offset, size));
// }
//
// @Override
// public void feed(long offset, long size, DataSink sink) throws IOException {
// if ((size < 0) || (size > mSize)) {
// throw new IllegalArgumentException("size: " + size + ", source size: " + mSize);
// }
// sink.consume(getByteBuffer(offset, (int) size));
// }
//
// @Override
// public ByteBufferDataSource slice(long offset, long size) {
// if ((offset == 0) && (size == mSize)) {
// return this;
// }
// if ((size < 0) || (size > mSize)) {
// throw new IllegalArgumentException("size: " + size + ", source size: " + mSize);
// }
// return new ByteBufferDataSource(
// getByteBuffer(offset, (int) size),
// false // no need to slice -- it's already a slice
// );
// }
//
// private void checkChunkValid(long offset, long size) {
// if (offset < 0) {
// throw new IllegalArgumentException("offset: " + offset);
// }
// if (size < 0) {
// throw new IllegalArgumentException("size: " + size);
// }
// if (offset > mSize) {
// throw new IllegalArgumentException(
// "offset (" + offset + ") > source size (" + mSize + ")");
// }
// long endOffset = offset + size;
// if (endOffset < offset) {
// throw new IllegalArgumentException(
// "offset (" + offset + ") + size (" + size + ") overflow");
// }
// if (endOffset > mSize) {
// throw new IllegalArgumentException(
// "offset (" + offset + ") + size (" + size + ") > source size (" + mSize +")");
// }
// }
// }
| import com.android.apksigner.core.internal.util.ByteBufferDataSource;
import java.nio.ByteBuffer; | package com.android.apksigner.core.util;
/**
* Utility methods for working with {@link DataSource} abstraction.
*/
public abstract class DataSources {
private DataSources() {}
/**
* Returns a {@link DataSource} backed by the provided {@link ByteBuffer}. The data source
* represents the data contained between the position and limit of the buffer. Changes to the
* buffer's contents will be visible in the data source.
*/
public static DataSource asDataSource(ByteBuffer buffer) {
if (buffer == null) {
throw new NullPointerException();
} | // Path: plugin/src/main/java/com/android/apksigner/core/internal/util/ByteBufferDataSource.java
// public class ByteBufferDataSource implements DataSource {
//
// private final ByteBuffer mBuffer;
// private final int mSize;
//
// /**
// * Constructs a new {@code ByteBufferDigestSource} based on the data contained in the provided
// * buffer between the buffer's position and limit.
// */
// public ByteBufferDataSource(ByteBuffer buffer) {
// this(buffer, true);
// }
//
// /**
// * Constructs a new {@code ByteBufferDigestSource} based on the data contained in the provided
// * buffer between the buffer's position and limit.
// */
// private ByteBufferDataSource(ByteBuffer buffer, boolean sliceRequired) {
// mBuffer = (sliceRequired) ? buffer.slice() : buffer;
// mSize = buffer.remaining();
// }
//
// @Override
// public long size() {
// return mSize;
// }
//
// @Override
// public ByteBuffer getByteBuffer(long offset, int size) {
// checkChunkValid(offset, size);
//
// // checkChunkValid ensures that it's OK to cast offset to int.
// int chunkPosition = (int) offset;
// int chunkLimit = chunkPosition + size;
// // Creating a slice of ByteBuffer modifies the state of the source ByteBuffer (position
// // and limit fields, to be more specific). We thus use synchronization around these
// // state-changing operations to make instances of this class thread-safe.
// synchronized (mBuffer) {
// // ByteBuffer.limit(int) and .position(int) check that that the position >= limit
// // invariant is not broken. Thus, the only way to safely change position and limit
// // without caring about their current values is to first set position to 0 or set the
// // limit to capacity.
// mBuffer.position(0);
//
// mBuffer.limit(chunkLimit);
// mBuffer.position(chunkPosition);
// return mBuffer.slice();
// }
// }
//
// @Override
// public void copyTo(long offset, int size, ByteBuffer dest) {
// dest.put(getByteBuffer(offset, size));
// }
//
// @Override
// public void feed(long offset, long size, DataSink sink) throws IOException {
// if ((size < 0) || (size > mSize)) {
// throw new IllegalArgumentException("size: " + size + ", source size: " + mSize);
// }
// sink.consume(getByteBuffer(offset, (int) size));
// }
//
// @Override
// public ByteBufferDataSource slice(long offset, long size) {
// if ((offset == 0) && (size == mSize)) {
// return this;
// }
// if ((size < 0) || (size > mSize)) {
// throw new IllegalArgumentException("size: " + size + ", source size: " + mSize);
// }
// return new ByteBufferDataSource(
// getByteBuffer(offset, (int) size),
// false // no need to slice -- it's already a slice
// );
// }
//
// private void checkChunkValid(long offset, long size) {
// if (offset < 0) {
// throw new IllegalArgumentException("offset: " + offset);
// }
// if (size < 0) {
// throw new IllegalArgumentException("size: " + size);
// }
// if (offset > mSize) {
// throw new IllegalArgumentException(
// "offset (" + offset + ") > source size (" + mSize + ")");
// }
// long endOffset = offset + size;
// if (endOffset < offset) {
// throw new IllegalArgumentException(
// "offset (" + offset + ") + size (" + size + ") overflow");
// }
// if (endOffset > mSize) {
// throw new IllegalArgumentException(
// "offset (" + offset + ") + size (" + size + ") > source size (" + mSize +")");
// }
// }
// }
// Path: plugin/src/main/java/com/android/apksigner/core/util/DataSources.java
import com.android.apksigner.core.internal.util.ByteBufferDataSource;
import java.nio.ByteBuffer;
package com.android.apksigner.core.util;
/**
* Utility methods for working with {@link DataSource} abstraction.
*/
public abstract class DataSources {
private DataSources() {}
/**
* Returns a {@link DataSource} backed by the provided {@link ByteBuffer}. The data source
* represents the data contained between the position and limit of the buffer. Changes to the
* buffer's contents will be visible in the data source.
*/
public static DataSource asDataSource(ByteBuffer buffer) {
if (buffer == null) {
throw new NullPointerException();
} | return new ByteBufferDataSource(buffer); |
rburgst/okhttp-digest | src/test/java/com/burgstaller/okhttp/basic/BasicAuthenticatorWithMockWebserverTest.java | // Path: src/main/java/com/burgstaller/okhttp/AuthenticationCacheInterceptor.java
// public class AuthenticationCacheInterceptor implements Interceptor {
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache) {
// this(authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Response intercept(Chain chain) throws IOException {
// final Request request = chain.request();
// final String key = cacheKeyProvider.getCachingKey(request);
// CachingAuthenticator authenticator = authCache.get(key);
// Request authRequest = null;
// Connection connection = chain.connection();
// Route route = connection != null ? connection.route() : null;
// if (authenticator != null) {
// authRequest = authenticator.authenticateWithState(route, request);
// }
// if (authRequest == null) {
// authRequest = request;
// }
// Response response = chain.proceed(authRequest);
//
// // Cached response was used, but it produced unauthorized response (cache expired).
// int responseCode = response != null ? response.code() : 0;
// if (authenticator != null && (responseCode == HTTP_UNAUTHORIZED || responseCode == HTTP_PROXY_AUTH)) {
// // Remove cached authenticator and resend request
// if (authCache.remove(key) != null) {
// response.body().close();
// Platform.get().log("Cached authentication expired. Sending a new request.", Platform.INFO, null);
// // Force sending a new request without "Authorization" header
// response = chain.proceed(request);
// }
// }
// return response;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/CachingAuthenticatorDecorator.java
// public class CachingAuthenticatorDecorator implements Authenticator {
// private final Authenticator innerAuthenticator;
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.innerAuthenticator = innerAuthenticator;
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache) {
// this(innerAuthenticator, authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// Request authenticated = innerAuthenticator.authenticate(route, response);
// if (authenticated != null) {
// String authorizationValue = authenticated.header("Authorization");
// if (authorizationValue != null && innerAuthenticator instanceof CachingAuthenticator) {
// final String key = cacheKeyProvider.getCachingKey(authenticated);
// authCache.put(key, (CachingAuthenticator) innerAuthenticator);
// }
// }
// return authenticated;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
| import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package com.burgstaller.okhttp.basic;
/**
* Unit test for basic authenticator.
*
* @author Rainer Burgstaller
*/
public class BasicAuthenticatorWithMockWebserverTest {
@Rule
public MockWebServer mockServer = new MockWebServer();
private BasicAuthenticator sut;
private BasicAuthenticator spy;
private OkHttpClient client;
private MockResponse unauthorizedResponse;
private MockResponse successResponse; | // Path: src/main/java/com/burgstaller/okhttp/AuthenticationCacheInterceptor.java
// public class AuthenticationCacheInterceptor implements Interceptor {
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache) {
// this(authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Response intercept(Chain chain) throws IOException {
// final Request request = chain.request();
// final String key = cacheKeyProvider.getCachingKey(request);
// CachingAuthenticator authenticator = authCache.get(key);
// Request authRequest = null;
// Connection connection = chain.connection();
// Route route = connection != null ? connection.route() : null;
// if (authenticator != null) {
// authRequest = authenticator.authenticateWithState(route, request);
// }
// if (authRequest == null) {
// authRequest = request;
// }
// Response response = chain.proceed(authRequest);
//
// // Cached response was used, but it produced unauthorized response (cache expired).
// int responseCode = response != null ? response.code() : 0;
// if (authenticator != null && (responseCode == HTTP_UNAUTHORIZED || responseCode == HTTP_PROXY_AUTH)) {
// // Remove cached authenticator and resend request
// if (authCache.remove(key) != null) {
// response.body().close();
// Platform.get().log("Cached authentication expired. Sending a new request.", Platform.INFO, null);
// // Force sending a new request without "Authorization" header
// response = chain.proceed(request);
// }
// }
// return response;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/CachingAuthenticatorDecorator.java
// public class CachingAuthenticatorDecorator implements Authenticator {
// private final Authenticator innerAuthenticator;
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.innerAuthenticator = innerAuthenticator;
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache) {
// this(innerAuthenticator, authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// Request authenticated = innerAuthenticator.authenticate(route, response);
// if (authenticated != null) {
// String authorizationValue = authenticated.header("Authorization");
// if (authorizationValue != null && innerAuthenticator instanceof CachingAuthenticator) {
// final String key = cacheKeyProvider.getCachingKey(authenticated);
// authCache.put(key, (CachingAuthenticator) innerAuthenticator);
// }
// }
// return authenticated;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
// Path: src/test/java/com/burgstaller/okhttp/basic/BasicAuthenticatorWithMockWebserverTest.java
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package com.burgstaller.okhttp.basic;
/**
* Unit test for basic authenticator.
*
* @author Rainer Burgstaller
*/
public class BasicAuthenticatorWithMockWebserverTest {
@Rule
public MockWebServer mockServer = new MockWebServer();
private BasicAuthenticator sut;
private BasicAuthenticator spy;
private OkHttpClient client;
private MockResponse unauthorizedResponse;
private MockResponse successResponse; | private Credentials credentials; |
rburgst/okhttp-digest | src/test/java/com/burgstaller/okhttp/basic/BasicAuthenticatorWithMockWebserverTest.java | // Path: src/main/java/com/burgstaller/okhttp/AuthenticationCacheInterceptor.java
// public class AuthenticationCacheInterceptor implements Interceptor {
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache) {
// this(authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Response intercept(Chain chain) throws IOException {
// final Request request = chain.request();
// final String key = cacheKeyProvider.getCachingKey(request);
// CachingAuthenticator authenticator = authCache.get(key);
// Request authRequest = null;
// Connection connection = chain.connection();
// Route route = connection != null ? connection.route() : null;
// if (authenticator != null) {
// authRequest = authenticator.authenticateWithState(route, request);
// }
// if (authRequest == null) {
// authRequest = request;
// }
// Response response = chain.proceed(authRequest);
//
// // Cached response was used, but it produced unauthorized response (cache expired).
// int responseCode = response != null ? response.code() : 0;
// if (authenticator != null && (responseCode == HTTP_UNAUTHORIZED || responseCode == HTTP_PROXY_AUTH)) {
// // Remove cached authenticator and resend request
// if (authCache.remove(key) != null) {
// response.body().close();
// Platform.get().log("Cached authentication expired. Sending a new request.", Platform.INFO, null);
// // Force sending a new request without "Authorization" header
// response = chain.proceed(request);
// }
// }
// return response;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/CachingAuthenticatorDecorator.java
// public class CachingAuthenticatorDecorator implements Authenticator {
// private final Authenticator innerAuthenticator;
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.innerAuthenticator = innerAuthenticator;
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache) {
// this(innerAuthenticator, authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// Request authenticated = innerAuthenticator.authenticate(route, response);
// if (authenticated != null) {
// String authorizationValue = authenticated.header("Authorization");
// if (authorizationValue != null && innerAuthenticator instanceof CachingAuthenticator) {
// final String key = cacheKeyProvider.getCachingKey(authenticated);
// authCache.put(key, (CachingAuthenticator) innerAuthenticator);
// }
// }
// return authenticated;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
| import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package com.burgstaller.okhttp.basic;
/**
* Unit test for basic authenticator.
*
* @author Rainer Burgstaller
*/
public class BasicAuthenticatorWithMockWebserverTest {
@Rule
public MockWebServer mockServer = new MockWebServer();
private BasicAuthenticator sut;
private BasicAuthenticator spy;
private OkHttpClient client;
private MockResponse unauthorizedResponse;
private MockResponse successResponse;
private Credentials credentials;
@Before
public void setUp() throws Exception {
credentials = new Credentials("user1", "user1");
sut = new BasicAuthenticator(credentials);
OkHttpClient.Builder builder = new OkHttpClient.Builder(); | // Path: src/main/java/com/burgstaller/okhttp/AuthenticationCacheInterceptor.java
// public class AuthenticationCacheInterceptor implements Interceptor {
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public AuthenticationCacheInterceptor(Map<String, CachingAuthenticator> authCache) {
// this(authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Response intercept(Chain chain) throws IOException {
// final Request request = chain.request();
// final String key = cacheKeyProvider.getCachingKey(request);
// CachingAuthenticator authenticator = authCache.get(key);
// Request authRequest = null;
// Connection connection = chain.connection();
// Route route = connection != null ? connection.route() : null;
// if (authenticator != null) {
// authRequest = authenticator.authenticateWithState(route, request);
// }
// if (authRequest == null) {
// authRequest = request;
// }
// Response response = chain.proceed(authRequest);
//
// // Cached response was used, but it produced unauthorized response (cache expired).
// int responseCode = response != null ? response.code() : 0;
// if (authenticator != null && (responseCode == HTTP_UNAUTHORIZED || responseCode == HTTP_PROXY_AUTH)) {
// // Remove cached authenticator and resend request
// if (authCache.remove(key) != null) {
// response.body().close();
// Platform.get().log("Cached authentication expired. Sending a new request.", Platform.INFO, null);
// // Force sending a new request without "Authorization" header
// response = chain.proceed(request);
// }
// }
// return response;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/CachingAuthenticatorDecorator.java
// public class CachingAuthenticatorDecorator implements Authenticator {
// private final Authenticator innerAuthenticator;
// private final Map<String, CachingAuthenticator> authCache;
// private final CacheKeyProvider cacheKeyProvider;
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache, CacheKeyProvider cacheKeyProvider) {
// this.innerAuthenticator = innerAuthenticator;
// this.authCache = authCache;
// this.cacheKeyProvider = cacheKeyProvider;
// }
//
// public CachingAuthenticatorDecorator(Authenticator innerAuthenticator, Map<String, CachingAuthenticator> authCache) {
// this(innerAuthenticator, authCache, new DefaultCacheKeyProvider());
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// Request authenticated = innerAuthenticator.authenticate(route, response);
// if (authenticated != null) {
// String authorizationValue = authenticated.header("Authorization");
// if (authorizationValue != null && innerAuthenticator instanceof CachingAuthenticator) {
// final String key = cacheKeyProvider.getCachingKey(authenticated);
// authCache.put(key, (CachingAuthenticator) innerAuthenticator);
// }
// }
// return authenticated;
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
// Path: src/test/java/com/burgstaller/okhttp/basic/BasicAuthenticatorWithMockWebserverTest.java
import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package com.burgstaller.okhttp.basic;
/**
* Unit test for basic authenticator.
*
* @author Rainer Burgstaller
*/
public class BasicAuthenticatorWithMockWebserverTest {
@Rule
public MockWebServer mockServer = new MockWebServer();
private BasicAuthenticator sut;
private BasicAuthenticator spy;
private OkHttpClient client;
private MockResponse unauthorizedResponse;
private MockResponse successResponse;
private Credentials credentials;
@Before
public void setUp() throws Exception {
credentials = new Credentials("user1", "user1");
sut = new BasicAuthenticator(credentials);
OkHttpClient.Builder builder = new OkHttpClient.Builder(); | final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); |
rburgst/okhttp-digest | src/test/java/com/burgstaller/okhttp/AuthenticationCacheInterceptorTest.java | // Path: src/main/java/com/burgstaller/okhttp/basic/BasicAuthenticator.java
// public class BasicAuthenticator implements CachingAuthenticator {
// private final Credentials credentials;
// private final Charset credentialCharset;
// private boolean proxy;
//
// public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
// this.credentials = credentials;
// this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
// }
//
// public BasicAuthenticator(Credentials credentials) {
// this(credentials, StandardCharsets.ISO_8859_1);
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// final Request request = response.request();
// proxy = response.code() == HTTP_PROXY_AUTH;
// return authFromRequest(request);
// }
//
// private Request authFromRequest(Request request) {
// // prevent infinite loops when the password is wrong
// String header = proxy ? "Proxy-Authorization" : "Authorization";
//
// final String authorizationHeader = request.header(header);
// if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
// Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
// return null;
// }
// String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
// return request.newBuilder()
// .header(header, authValue)
// .build();
// }
//
// @Override
// public Request authenticateWithState(Route route, Request request) throws IOException {
// return authFromRequest(request);
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
| import com.burgstaller.okhttp.basic.BasicAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import okhttp3.Address;
import okhttp3.Authenticator;
import okhttp3.Connection;
import okhttp3.ConnectionSpec;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given; | package com.burgstaller.okhttp;
/**
* Unit test for authenticator caching.
*
* @author Alexey Vasilyev
*/
public class AuthenticationCacheInterceptorTest {
@Mock
private Connection mockConnection;
private Route mockRoute;
@Mock
private Dns mockDns;
@Mock
private SocketFactory socketFactory;
@Mock
private Authenticator proxyAuthenticator;
@Mock
private ProxySelector proxySelector;
@Mock
Proxy proxy;
@Before
public void beforeMethod() {
MockitoAnnotations.initMocks(this);
// setup some dummy data so that we dont get NPEs
Address address = new Address("localhost", 8080, mockDns, socketFactory, null, null,
null, proxyAuthenticator, null, Collections.singletonList(Protocol.HTTP_1_1),
Collections.singletonList(ConnectionSpec.MODERN_TLS), proxySelector);
InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 8080);
mockRoute = new Route(address, proxy, inetSocketAddress);
given(mockConnection.route()).willReturn(mockRoute);
}
@Test
public void testCaching_withExpiredAuthentication() throws Exception { | // Path: src/main/java/com/burgstaller/okhttp/basic/BasicAuthenticator.java
// public class BasicAuthenticator implements CachingAuthenticator {
// private final Credentials credentials;
// private final Charset credentialCharset;
// private boolean proxy;
//
// public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
// this.credentials = credentials;
// this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
// }
//
// public BasicAuthenticator(Credentials credentials) {
// this(credentials, StandardCharsets.ISO_8859_1);
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// final Request request = response.request();
// proxy = response.code() == HTTP_PROXY_AUTH;
// return authFromRequest(request);
// }
//
// private Request authFromRequest(Request request) {
// // prevent infinite loops when the password is wrong
// String header = proxy ? "Proxy-Authorization" : "Authorization";
//
// final String authorizationHeader = request.header(header);
// if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
// Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
// return null;
// }
// String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
// return request.newBuilder()
// .header(header, authValue)
// .build();
// }
//
// @Override
// public Request authenticateWithState(Route route, Request request) throws IOException {
// return authFromRequest(request);
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
// Path: src/test/java/com/burgstaller/okhttp/AuthenticationCacheInterceptorTest.java
import com.burgstaller.okhttp.basic.BasicAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import okhttp3.Address;
import okhttp3.Authenticator;
import okhttp3.Connection;
import okhttp3.ConnectionSpec;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given;
package com.burgstaller.okhttp;
/**
* Unit test for authenticator caching.
*
* @author Alexey Vasilyev
*/
public class AuthenticationCacheInterceptorTest {
@Mock
private Connection mockConnection;
private Route mockRoute;
@Mock
private Dns mockDns;
@Mock
private SocketFactory socketFactory;
@Mock
private Authenticator proxyAuthenticator;
@Mock
private ProxySelector proxySelector;
@Mock
Proxy proxy;
@Before
public void beforeMethod() {
MockitoAnnotations.initMocks(this);
// setup some dummy data so that we dont get NPEs
Address address = new Address("localhost", 8080, mockDns, socketFactory, null, null,
null, proxyAuthenticator, null, Collections.singletonList(Protocol.HTTP_1_1),
Collections.singletonList(ConnectionSpec.MODERN_TLS), proxySelector);
InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 8080);
mockRoute = new Route(address, proxy, inetSocketAddress);
given(mockConnection.route()).willReturn(mockRoute);
}
@Test
public void testCaching_withExpiredAuthentication() throws Exception { | Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); |
rburgst/okhttp-digest | src/test/java/com/burgstaller/okhttp/AuthenticationCacheInterceptorTest.java | // Path: src/main/java/com/burgstaller/okhttp/basic/BasicAuthenticator.java
// public class BasicAuthenticator implements CachingAuthenticator {
// private final Credentials credentials;
// private final Charset credentialCharset;
// private boolean proxy;
//
// public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
// this.credentials = credentials;
// this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
// }
//
// public BasicAuthenticator(Credentials credentials) {
// this(credentials, StandardCharsets.ISO_8859_1);
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// final Request request = response.request();
// proxy = response.code() == HTTP_PROXY_AUTH;
// return authFromRequest(request);
// }
//
// private Request authFromRequest(Request request) {
// // prevent infinite loops when the password is wrong
// String header = proxy ? "Proxy-Authorization" : "Authorization";
//
// final String authorizationHeader = request.header(header);
// if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
// Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
// return null;
// }
// String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
// return request.newBuilder()
// .header(header, authValue)
// .build();
// }
//
// @Override
// public Request authenticateWithState(Route route, Request request) throws IOException {
// return authFromRequest(request);
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
| import com.burgstaller.okhttp.basic.BasicAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import okhttp3.Address;
import okhttp3.Authenticator;
import okhttp3.Connection;
import okhttp3.ConnectionSpec;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given; | public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private String whenInterceptAuthenticationForUrlWithNoConnection(Interceptor interceptor, final String url) throws IOException {
// we need a result holder for passing into the anonymous class
final AtomicReference<String> authResultHeader = new AtomicReference<>();
final Request request = new Request.Builder()
.url(url)
.get()
.build();
interceptor.intercept(new ChainAdapter(request, mockConnection) {
@Override
public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private void givenCachedAuthenticationFor(String url, Map<String, CachingAuthenticator> authCache) throws IOException {
Authenticator decorator = new CachingAuthenticatorDecorator( | // Path: src/main/java/com/burgstaller/okhttp/basic/BasicAuthenticator.java
// public class BasicAuthenticator implements CachingAuthenticator {
// private final Credentials credentials;
// private final Charset credentialCharset;
// private boolean proxy;
//
// public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
// this.credentials = credentials;
// this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
// }
//
// public BasicAuthenticator(Credentials credentials) {
// this(credentials, StandardCharsets.ISO_8859_1);
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// final Request request = response.request();
// proxy = response.code() == HTTP_PROXY_AUTH;
// return authFromRequest(request);
// }
//
// private Request authFromRequest(Request request) {
// // prevent infinite loops when the password is wrong
// String header = proxy ? "Proxy-Authorization" : "Authorization";
//
// final String authorizationHeader = request.header(header);
// if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
// Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
// return null;
// }
// String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
// return request.newBuilder()
// .header(header, authValue)
// .build();
// }
//
// @Override
// public Request authenticateWithState(Route route, Request request) throws IOException {
// return authFromRequest(request);
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
// Path: src/test/java/com/burgstaller/okhttp/AuthenticationCacheInterceptorTest.java
import com.burgstaller.okhttp.basic.BasicAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import okhttp3.Address;
import okhttp3.Authenticator;
import okhttp3.Connection;
import okhttp3.ConnectionSpec;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given;
public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private String whenInterceptAuthenticationForUrlWithNoConnection(Interceptor interceptor, final String url) throws IOException {
// we need a result holder for passing into the anonymous class
final AtomicReference<String> authResultHeader = new AtomicReference<>();
final Request request = new Request.Builder()
.url(url)
.get()
.build();
interceptor.intercept(new ChainAdapter(request, mockConnection) {
@Override
public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private void givenCachedAuthenticationFor(String url, Map<String, CachingAuthenticator> authCache) throws IOException {
Authenticator decorator = new CachingAuthenticatorDecorator( | new BasicAuthenticator(new Credentials("user1", "user1")), |
rburgst/okhttp-digest | src/test/java/com/burgstaller/okhttp/AuthenticationCacheInterceptorTest.java | // Path: src/main/java/com/burgstaller/okhttp/basic/BasicAuthenticator.java
// public class BasicAuthenticator implements CachingAuthenticator {
// private final Credentials credentials;
// private final Charset credentialCharset;
// private boolean proxy;
//
// public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
// this.credentials = credentials;
// this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
// }
//
// public BasicAuthenticator(Credentials credentials) {
// this(credentials, StandardCharsets.ISO_8859_1);
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// final Request request = response.request();
// proxy = response.code() == HTTP_PROXY_AUTH;
// return authFromRequest(request);
// }
//
// private Request authFromRequest(Request request) {
// // prevent infinite loops when the password is wrong
// String header = proxy ? "Proxy-Authorization" : "Authorization";
//
// final String authorizationHeader = request.header(header);
// if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
// Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
// return null;
// }
// String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
// return request.newBuilder()
// .header(header, authValue)
// .build();
// }
//
// @Override
// public Request authenticateWithState(Route route, Request request) throws IOException {
// return authFromRequest(request);
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
| import com.burgstaller.okhttp.basic.BasicAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import okhttp3.Address;
import okhttp3.Authenticator;
import okhttp3.Connection;
import okhttp3.ConnectionSpec;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given; | public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private String whenInterceptAuthenticationForUrlWithNoConnection(Interceptor interceptor, final String url) throws IOException {
// we need a result holder for passing into the anonymous class
final AtomicReference<String> authResultHeader = new AtomicReference<>();
final Request request = new Request.Builder()
.url(url)
.get()
.build();
interceptor.intercept(new ChainAdapter(request, mockConnection) {
@Override
public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private void givenCachedAuthenticationFor(String url, Map<String, CachingAuthenticator> authCache) throws IOException {
Authenticator decorator = new CachingAuthenticatorDecorator( | // Path: src/main/java/com/burgstaller/okhttp/basic/BasicAuthenticator.java
// public class BasicAuthenticator implements CachingAuthenticator {
// private final Credentials credentials;
// private final Charset credentialCharset;
// private boolean proxy;
//
// public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
// this.credentials = credentials;
// this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
// }
//
// public BasicAuthenticator(Credentials credentials) {
// this(credentials, StandardCharsets.ISO_8859_1);
// }
//
// @Override
// public Request authenticate(Route route, Response response) throws IOException {
// final Request request = response.request();
// proxy = response.code() == HTTP_PROXY_AUTH;
// return authFromRequest(request);
// }
//
// private Request authFromRequest(Request request) {
// // prevent infinite loops when the password is wrong
// String header = proxy ? "Proxy-Authorization" : "Authorization";
//
// final String authorizationHeader = request.header(header);
// if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
// Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
// return null;
// }
// String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
// return request.newBuilder()
// .header(header, authValue)
// .build();
// }
//
// @Override
// public Request authenticateWithState(Route route, Request request) throws IOException {
// return authFromRequest(request);
// }
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
//
// Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
// Path: src/test/java/com/burgstaller/okhttp/AuthenticationCacheInterceptorTest.java
import com.burgstaller.okhttp.basic.BasicAuthenticator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import okhttp3.Address;
import okhttp3.Authenticator;
import okhttp3.Connection;
import okhttp3.ConnectionSpec;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.BDDMockito.given;
public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private String whenInterceptAuthenticationForUrlWithNoConnection(Interceptor interceptor, final String url) throws IOException {
// we need a result holder for passing into the anonymous class
final AtomicReference<String> authResultHeader = new AtomicReference<>();
final Request request = new Request.Builder()
.url(url)
.get()
.build();
interceptor.intercept(new ChainAdapter(request, mockConnection) {
@Override
public Response proceed(Request request) {
final String authorization = request.header("Authorization");
authResultHeader.set(authorization);
return null;
}
});
return authResultHeader.get();
}
private void givenCachedAuthenticationFor(String url, Map<String, CachingAuthenticator> authCache) throws IOException {
Authenticator decorator = new CachingAuthenticatorDecorator( | new BasicAuthenticator(new Credentials("user1", "user1")), |
rburgst/okhttp-digest | src/test/java/com/burgstaller/okhttp/basic/BasicAuthenticatorTest.java | // Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
| import com.burgstaller.okhttp.digest.Credentials;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.Assertions.assertThat; | package com.burgstaller.okhttp.basic;
/**
* Unit test for basic authenticator.
*
* @author Rainer Burgstaller
*/
public class BasicAuthenticatorTest {
private BasicAuthenticator authenticator;
@Before
public void setUp() throws Exception { | // Path: src/main/java/com/burgstaller/okhttp/digest/Credentials.java
// public class Credentials {
// private String userName;
// private String password;
//
// public Credentials(String userName, String password) {
// if (userName == null || password == null) {
// throw new IllegalArgumentException("username and password cannot be null");
// }
// this.userName = userName;
// this.password = password;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
// }
// Path: src/test/java/com/burgstaller/okhttp/basic/BasicAuthenticatorTest.java
import com.burgstaller.okhttp.digest.Credentials;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.assertj.core.api.Assertions.assertThat;
package com.burgstaller.okhttp.basic;
/**
* Unit test for basic authenticator.
*
* @author Rainer Burgstaller
*/
public class BasicAuthenticatorTest {
private BasicAuthenticator authenticator;
@Before
public void setUp() throws Exception { | authenticator = new BasicAuthenticator(new Credentials("user1", "user1")); |
rburgst/okhttp-digest | src/main/java/com/burgstaller/okhttp/CachingAuthenticatorDecorator.java | // Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
| import java.io.IOException;
import java.util.Map;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route; | package com.burgstaller.okhttp;
/**
* An authenticator decorator which saves the generated authentication headers for a specific host.
* To be used in tandem with {@link AuthenticationCacheInterceptor}.
* Depending on your use case you will probably need to use a {@link java.util.concurrent.ConcurrentHashMap}.
*/
public class CachingAuthenticatorDecorator implements Authenticator {
private final Authenticator innerAuthenticator; | // Path: src/main/java/com/burgstaller/okhttp/digest/CachingAuthenticator.java
// public interface CachingAuthenticator extends Authenticator {
// /**
// * Authenticate the new request using cached information already established from an earlier
// * authentication.
// *
// * @param route the route to use
// * @param request the new request to be authenticated.
// * @return the modified request with updated auth headers.
// * @throws IOException in case of a communication problem
// */
// Request authenticateWithState(Route route, Request request) throws IOException;
// }
// Path: src/main/java/com/burgstaller/okhttp/CachingAuthenticatorDecorator.java
import java.io.IOException;
import java.util.Map;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
package com.burgstaller.okhttp;
/**
* An authenticator decorator which saves the generated authentication headers for a specific host.
* To be used in tandem with {@link AuthenticationCacheInterceptor}.
* Depending on your use case you will probably need to use a {@link java.util.concurrent.ConcurrentHashMap}.
*/
public class CachingAuthenticatorDecorator implements Authenticator {
private final Authenticator innerAuthenticator; | private final Map<String, CachingAuthenticator> authCache; |
Subsets and Splits