_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8400 | KeyStoreManager.getPrivateKeyForLocalCert | train | public synchronized PrivateKey getPrivateKeyForLocalCert(final X509Certificate cert)
throws CertificateEncodingException, KeyStoreException, UnrecoverableKeyException,
NoSuchAlgorithmException
{
String thumbprint = ThumbprintUtil.getThumbprint(cert);
return (PrivateKey)_ks.getKey(thumbprint, _keypassword);
} | java | {
"resource": ""
} |
q8401 | KeyStoreManager.mapPublicKeys | train | public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute)
{
_mappedPublicKeys.put(original, substitute);
if(persistImmediately) { persistPublicKeyMap(); }
} | java | {
"resource": ""
} |
q8402 | ScriptService.getScript | train | public Script getScript(int id) {
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = SQLService.getInstance().getConnection()) {
statement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_SCRIPT +
" WHERE id = ?"
);
statement.setInt(1, id);
results = statement.executeQuery();
if (results.next()) {
return scriptFromSQLResult(results);
}
} catch (Exception e) {
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return null;
} | java | {
"resource": ""
} |
q8403 | ScriptService.getScripts | train | public Script[] getScripts(Integer type) {
ArrayList<Script> returnData = new ArrayList<>();
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = SQLService.getInstance().getConnection()) {
statement = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_SCRIPT +
" ORDER BY " + Constants.GENERIC_ID);
if (type != null) {
statement = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_SCRIPT +
" WHERE " + Constants.SCRIPT_TYPE + "= ?" +
" ORDER BY " + Constants.GENERIC_ID);
statement.setInt(1, type);
}
logger.info("Query: {}", statement);
results = statement.executeQuery();
while (results.next()) {
returnData.add(scriptFromSQLResult(results));
}
} catch (Exception e) {
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return returnData.toArray(new Script[0]);
} | java | {
"resource": ""
} |
q8404 | ScriptService.updateName | train | public Script updateName(int id, String name) throws Exception {
PreparedStatement statement = null;
try (Connection sqlConnection = SQLService.getInstance().getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_SCRIPT +
" SET " + Constants.SCRIPT_NAME + " = ? " +
" WHERE " + Constants.GENERIC_ID + " = ?"
);
statement.setString(1, name);
statement.setInt(2, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return this.getScript(id);
} | java | {
"resource": ""
} |
q8405 | ScriptService.removeScript | train | public void removeScript(int id) throws Exception {
PreparedStatement statement = null;
try (Connection sqlConnection = SQLService.getInstance().getConnection()) {
statement = sqlConnection.prepareStatement(
"DELETE FROM " + Constants.DB_TABLE_SCRIPT +
" WHERE " + Constants.GENERIC_ID + " = ?"
);
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
} | java | {
"resource": ""
} |
q8406 | RemoveHeaderFilter.doFilter | train | @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final ServletRequest r1 = request;
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
@SuppressWarnings("unchecked")
public void setHeader(String name, String value) {
ArrayList<String> headersToRemove = new ArrayList<String>();
if (r1.getAttribute("com.groupon.odo.removeHeaders") != null)
headersToRemove = (ArrayList<String>) r1.getAttribute("com.groupon.odo.removeHeaders");
boolean removeHeader = false;
// need to loop through removeHeaders to make things case insensitive
for (String headerToRemove : headersToRemove) {
if (headerToRemove.toLowerCase().equals(name.toLowerCase())) {
removeHeader = true;
break;
}
}
if (! removeHeader) {
super.setHeader(name, value);
}
}
});
} | java | {
"resource": ""
} |
q8407 | Utils.arrayFromStringOfIntegers | train | public static int[] arrayFromStringOfIntegers(String str) throws IllegalArgumentException {
StringTokenizer tokenizer = new StringTokenizer(str, ",");
int n = tokenizer.countTokens();
int[] list = new int[n];
for (int i = 0; i < n; i++) {
String token = tokenizer.nextToken();
list[i] = Integer.parseInt(token);
}
return list;
} | java | {
"resource": ""
} |
q8408 | Utils.copyResourceToLocalFile | train | public static File copyResourceToLocalFile(String sourceResource, String destFileName) throws Exception {
try {
Resource keystoreFile = new ClassPathResource(sourceResource);
InputStream in = keystoreFile.getInputStream();
File outKeyStoreFile = new File(destFileName);
FileOutputStream fop = new FileOutputStream(outKeyStoreFile);
byte[] buf = new byte[512];
int num;
while ((num = in.read(buf)) != -1) {
fop.write(buf, 0, num);
}
fop.flush();
fop.close();
in.close();
return outKeyStoreFile;
} catch (IOException ioe) {
throw new Exception("Could not copy keystore file: " + ioe.getMessage());
}
} | java | {
"resource": ""
} |
q8409 | Utils.getSystemPort | train | public static int getSystemPort(String portIdentifier) {
int defaultPort = 0;
if (portIdentifier.compareTo(Constants.SYS_API_PORT) == 0) {
defaultPort = Constants.DEFAULT_API_PORT;
} else if (portIdentifier.compareTo(Constants.SYS_DB_PORT) == 0) {
defaultPort = Constants.DEFAULT_DB_PORT;
} else if (portIdentifier.compareTo(Constants.SYS_FWD_PORT) == 0) {
defaultPort = Constants.DEFAULT_FWD_PORT;
} else if (portIdentifier.compareTo(Constants.SYS_HTTP_PORT) == 0) {
defaultPort = Constants.DEFAULT_HTTP_PORT;
} else if (portIdentifier.compareTo(Constants.SYS_HTTPS_PORT) == 0) {
defaultPort = Constants.DEFAULT_HTTPS_PORT;
} else {
return defaultPort;
}
String portStr = System.getenv(portIdentifier);
return (portStr == null || portStr.isEmpty()) ? defaultPort : Integer.valueOf(portStr);
} | java | {
"resource": ""
} |
q8410 | Utils.getPublicIPAddress | train | public static String getPublicIPAddress() throws Exception {
final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
String ipAddr = null;
Enumeration e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress i = (InetAddress) ee.nextElement();
// Pick the first non loop back address
if ((!i.isLoopbackAddress() && i.isSiteLocalAddress()) ||
i.getHostAddress().matches(IPV4_REGEX)) {
ipAddr = i.getHostAddress();
break;
}
}
if (ipAddr != null) {
break;
}
}
return ipAddr;
} | java | {
"resource": ""
} |
q8411 | ConfigurationService.getConfiguration | train | public Configuration getConfiguration(String name) {
Configuration[] values = getConfigurations(name);
if (values == null) {
return null;
}
return values[0];
} | java | {
"resource": ""
} |
q8412 | ConfigurationService.getConfigurations | train | public Configuration[] getConfigurations(String name) {
ArrayList<Configuration> valuesList = new ArrayList<Configuration>();
logger.info("Getting data for {}", name);
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
String queryString = "SELECT * FROM " + Constants.DB_TABLE_CONFIGURATION;
if (name != null) {
queryString += " WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + "=?";
}
statement = sqlConnection.prepareStatement(queryString);
if (name != null) {
statement.setString(1, name);
}
results = statement.executeQuery();
while (results.next()) {
Configuration config = new Configuration();
config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));
config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));
config.setId(results.getInt(Constants.GENERIC_ID));
logger.info("the configValue is = {}", config.getValue());
valuesList.add(config);
}
} catch (SQLException sqe) {
logger.info("Exception in sql");
sqe.printStackTrace();
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
if (valuesList.size() == 0) {
return null;
}
return valuesList.toArray(new Configuration[0]);
} | java | {
"resource": ""
} |
q8413 | EditController.disableAll | train | @RequestMapping(value = "api/edit/disableAll", method = RequestMethod.POST)
public
@ResponseBody
String disableAll(Model model, int profileID,
@RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) {
editService.disableAll(profileID, clientUUID);
return null;
} | java | {
"resource": ""
} |
q8414 | EditController.updateRepeatNumber | train | @RequestMapping(value = "api/edit/repeatNumber", method = RequestMethod.POST)
public
@ResponseBody
String updateRepeatNumber(Model model, int newNum, int path_id,
@RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {
logger.info("want to update repeat number of path_id={}, to newNum={}", path_id, newNum);
editService.updateRepeatNumber(newNum, path_id, clientUUID);
return null;
} | java | {
"resource": ""
} |
q8415 | EditController.enableCustomResponse | train | @RequestMapping(value = "api/edit/enable/custom", method = RequestMethod.POST)
public
@ResponseBody
String enableCustomResponse(Model model, String custom, int path_id,
@RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {
if (custom.equals("undefined"))
return null;
editService.enableCustomResponse(custom, path_id, clientUUID);
return null;
} | java | {
"resource": ""
} |
q8416 | EditController.disableResponses | train | @RequestMapping(value = "api/edit/disable", method = RequestMethod.POST)
public
@ResponseBody
String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {
OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);
//TODO also need to disable custom override if there is one of those
editService.removeCustomOverride(path_id, clientUUID);
return null;
} | java | {
"resource": ""
} |
q8417 | SQLService.startServer | train | public void startServer() throws Exception {
if (!externalDatabaseHost) {
try {
this.port = Utils.getSystemPort(Constants.SYS_DB_PORT);
server = Server.createTcpServer("-tcpPort", String.valueOf(port), "-tcpAllowOthers").start();
} catch (SQLException e) {
if (e.toString().contains("java.net.UnknownHostException")) {
logger.error("Startup failure. Potential bug in OSX & Java7. Workaround: add name of local machine to '/etc/hosts.'");
logger.error("Example: 127.0.0.1 MacBook");
throw e;
}
}
}
} | java | {
"resource": ""
} |
q8418 | SQLService.stopServer | train | public void stopServer() throws Exception {
if (!externalDatabaseHost) {
try (Connection sqlConnection = getConnection()) {
sqlConnection.prepareStatement("SHUTDOWN").execute();
} catch (Exception e) {
}
try {
server.stop();
} catch (Exception e) {
}
}
} | java | {
"resource": ""
} |
q8419 | SQLService.getInstance | train | public static SQLService getInstance() throws Exception {
if (_instance == null) {
_instance = new SQLService();
_instance.startServer();
// default pool size is 20
// can be overriden by env variable
int dbPool = 20;
if (Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE) != null) {
dbPool = Integer.valueOf(Utils.getEnvironmentOptionValue(Constants.SYS_DATABASE_POOL_SIZE));
}
// initialize connection pool
PoolProperties p = new PoolProperties();
String connectString = "jdbc:h2:tcp://" + _instance.databaseHost + ":" + String.valueOf(_instance.port) + "/" +
_instance.databaseName + "/proxydb;MULTI_THREADED=true;AUTO_RECONNECT=TRUE;AUTOCOMMIT=ON";
p.setUrl(connectString);
p.setDriverClassName("org.h2.Driver");
p.setUsername("sa");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(5000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(dbPool);
p.setInitialSize(5);
p.setMaxWait(30000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
_instance.datasource = new DataSource();
_instance.datasource.setPoolProperties(p);
}
return _instance;
} | java | {
"resource": ""
} |
q8420 | SQLService.updateSchema | train | public void updateSchema(String migrationPath) {
try {
logger.info("Updating schema... ");
int current_version = 0;
// first check the current schema version
HashMap<String, Object> configuration = getFirstResult("SELECT * FROM " + Constants.DB_TABLE_CONFIGURATION +
" WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + " = \'" + Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "\'");
if (configuration == null) {
logger.info("Creating configuration table..");
// create configuration table
executeUpdate("CREATE TABLE "
+ Constants.DB_TABLE_CONFIGURATION
+ " (" + Constants.GENERIC_ID + " INTEGER IDENTITY,"
+ Constants.DB_TABLE_CONFIGURATION_NAME + " VARCHAR(256),"
+ Constants.DB_TABLE_CONFIGURATION_VALUE + " VARCHAR(1024));");
executeUpdate("INSERT INTO " + Constants.DB_TABLE_CONFIGURATION
+ "(" + Constants.DB_TABLE_CONFIGURATION_NAME + "," + Constants.DB_TABLE_CONFIGURATION_VALUE + ")"
+ " VALUES (\'"
+ Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION
+ "\', '0');");
} else {
logger.info("Getting current schema version..");
// get current version
current_version = new Integer(configuration.get("VALUE").toString());
logger.info("Current schema version is {}", current_version);
}
// loop through until we get up to the right schema version
while (current_version < Constants.DB_CURRENT_SCHEMA_VERSION) {
current_version++;
// look for a schema file for this version
logger.info("Updating to schema version {}", current_version);
String currentFile = migrationPath + "/schema."
+ current_version;
Resource migFile = new ClassPathResource(currentFile);
BufferedReader in = new BufferedReader(new InputStreamReader(
migFile.getInputStream()));
String str;
while ((str = in.readLine()) != null) {
// execute each line
if (str.length() > 0) {
executeUpdate(str);
}
}
in.close();
}
// update the configuration table with the correct version
executeUpdate("UPDATE " + Constants.DB_TABLE_CONFIGURATION
+ " SET " + Constants.DB_TABLE_CONFIGURATION_VALUE + "='" + current_version
+ "' WHERE " + Constants.DB_TABLE_CONFIGURATION_NAME + "='"
+ Constants.DB_TABLE_CONFIGURATION_DATABASE_VERSION + "';");
} catch (Exception e) {
logger.info("Error in executeUpdate");
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q8421 | SQLService.executeUpdate | train | public int executeUpdate(String query) throws Exception {
int returnVal = 0;
Statement queryStatement = null;
try (Connection sqlConnection = getConnection()) {
queryStatement = sqlConnection.createStatement();
returnVal = queryStatement.executeUpdate(query);
} catch (Exception e) {
} finally {
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
return returnVal;
} | java | {
"resource": ""
} |
q8422 | SQLService.getFirstResult | train | public HashMap<String, Object> getFirstResult(String query)
throws Exception {
HashMap<String, Object> result = null;
Statement queryStatement = null;
ResultSet results = null;
try (Connection sqlConnection = getConnection()) {
queryStatement = sqlConnection.createStatement();
results = queryStatement.executeQuery(query);
if (results.next()) {
result = new HashMap<>();
String[] columns = getColumnNames(results.getMetaData());
for (String column : columns) {
result.put(column, results.getObject(column));
}
}
} catch (Exception e) {
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
return result;
} | java | {
"resource": ""
} |
q8423 | SQLService.toClob | train | public Clob toClob(String stringName, Connection sqlConnection) {
Clob clobName = null;
try {
clobName = sqlConnection.createClob();
clobName.setString(1, stringName);
} catch (SQLException e) {
// TODO Auto-generated catch block
logger.info("Unable to create clob object");
e.printStackTrace();
}
return clobName;
} | java | {
"resource": ""
} |
q8424 | SQLService.getColumnNames | train | private String[] getColumnNames(ResultSetMetaData rsmd) throws Exception {
ArrayList<String> names = new ArrayList<String>();
// Get result set meta data
int numColumns = rsmd.getColumnCount();
// Get the column names; column indices start from 1
for (int i = 1; i < numColumns + 1; i++) {
String columnName = rsmd.getColumnName(i);
names.add(columnName);
}
return names.toArray(new String[0]);
} | java | {
"resource": ""
} |
q8425 | ServerRedirectService.tableServers | train | public List<ServerRedirect> tableServers(int clientId) {
List<ServerRedirect> servers = new ArrayList<>();
try {
Client client = ClientService.getInstance().getClient(clientId);
servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return servers;
} | java | {
"resource": ""
} |
q8426 | ServerRedirectService.tableServers | train | public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {
ArrayList<ServerRedirect> servers = new ArrayList<>();
PreparedStatement queryStatement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
queryStatement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_SERVERS +
" WHERE " + Constants.GENERIC_PROFILE_ID + " = ?" +
" AND " + Constants.SERVER_REDIRECT_GROUP_ID + " = ?"
);
queryStatement.setInt(1, profileId);
queryStatement.setInt(2, serverGroupId);
results = queryStatement.executeQuery();
while (results.next()) {
ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),
results.getString(Constants.SERVER_REDIRECT_REGION),
results.getString(Constants.SERVER_REDIRECT_SRC_URL),
results.getString(Constants.SERVER_REDIRECT_DEST_URL),
results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));
curServer.setProfileId(profileId);
servers.add(curServer);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
return servers;
} | java | {
"resource": ""
} |
q8427 | ServerRedirectService.tableServerGroups | train | public List<ServerGroup> tableServerGroups(int profileId) {
ArrayList<ServerGroup> serverGroups = new ArrayList<>();
PreparedStatement queryStatement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
queryStatement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_SERVER_GROUPS +
" WHERE " + Constants.GENERIC_PROFILE_ID + " = ? " +
"ORDER BY " + Constants.GENERIC_NAME
);
queryStatement.setInt(1, profileId);
results = queryStatement.executeQuery();
while (results.next()) {
ServerGroup curServerGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),
results.getString(Constants.GENERIC_NAME),
results.getInt(Constants.GENERIC_PROFILE_ID));
curServerGroup.setServers(tableServers(profileId, curServerGroup.getId()));
serverGroups.add(curServerGroup);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
return serverGroups;
} | java | {
"resource": ""
} |
q8428 | ServerRedirectService.getRedirect | train | public ServerRedirect getRedirect(int id) throws Exception {
PreparedStatement queryStatement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
queryStatement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_SERVERS +
" WHERE " + Constants.GENERIC_ID + " = ?"
);
queryStatement.setInt(1, id);
results = queryStatement.executeQuery();
if (results.next()) {
ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),
results.getString(Constants.SERVER_REDIRECT_REGION),
results.getString(Constants.SERVER_REDIRECT_SRC_URL),
results.getString(Constants.SERVER_REDIRECT_DEST_URL),
results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));
curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));
return curServer;
}
logger.info("Did not find the ID: {}", id);
} catch (SQLException e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
return null;
} | java | {
"resource": ""
} |
q8429 | ServerRedirectService.getServerGroup | train | public ServerGroup getServerGroup(int id, int profileId) throws Exception {
PreparedStatement queryStatement = null;
ResultSet results = null;
if (id == 0) {
return new ServerGroup(0, "Default", profileId);
}
try (Connection sqlConnection = sqlService.getConnection()) {
queryStatement = sqlConnection.prepareStatement(
"SELECT * FROM " + Constants.DB_TABLE_SERVER_GROUPS +
" WHERE " + Constants.GENERIC_ID + " = ?"
);
queryStatement.setInt(1, id);
results = queryStatement.executeQuery();
if (results.next()) {
ServerGroup curGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),
results.getString(Constants.GENERIC_NAME),
results.getInt(Constants.GENERIC_PROFILE_ID));
return curGroup;
}
logger.info("Did not find the ID: {}", id);
} catch (SQLException e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
return null;
} | java | {
"resource": ""
} |
q8430 | ServerRedirectService.addServerRedirectToProfile | train | public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,
int profileId, int clientId) throws Exception {
int serverId = -1;
try {
Client client = ClientService.getInstance().getClient(clientId);
serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());
} catch (Exception e) {
e.printStackTrace();
}
return serverId;
} | java | {
"resource": ""
} |
q8431 | ServerRedirectService.addServerRedirect | train | public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception {
int serverId = -1;
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_SERVERS
+ "(" + Constants.SERVER_REDIRECT_REGION + "," +
Constants.SERVER_REDIRECT_SRC_URL + "," +
Constants.SERVER_REDIRECT_DEST_URL + "," +
Constants.SERVER_REDIRECT_HOST_HEADER + "," +
Constants.SERVER_REDIRECT_PROFILE_ID + "," +
Constants.SERVER_REDIRECT_GROUP_ID + ")"
+ " VALUES (?, ?, ?, ?, ?, ?);", PreparedStatement.RETURN_GENERATED_KEYS);
statement.setString(1, region);
statement.setString(2, srcUrl);
statement.setString(3, destUrl);
statement.setString(4, hostHeader);
statement.setInt(5, profileId);
statement.setInt(6, groupId);
statement.executeUpdate();
results = statement.getGeneratedKeys();
if (results.next()) {
serverId = results.getInt(1);
} else {
// something went wrong
throw new Exception("Could not add path");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return serverId;
} | java | {
"resource": ""
} |
q8432 | ServerRedirectService.addServerGroup | train | public int addServerGroup(String groupName, int profileId) throws Exception {
int groupId = -1;
PreparedStatement statement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_SERVER_GROUPS
+ "(" + Constants.GENERIC_NAME + "," +
Constants.GENERIC_PROFILE_ID + ")"
+ " VALUES (?, ?);", PreparedStatement.RETURN_GENERATED_KEYS);
statement.setString(1, groupName);
statement.setInt(2, profileId);
statement.executeUpdate();
results = statement.getGeneratedKeys();
if (results.next()) {
groupId = results.getInt(1);
} else {
// something went wrong
throw new Exception("Could not add group");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
return groupId;
} | java | {
"resource": ""
} |
q8433 | ServerRedirectService.setGroupName | train | public void setGroupName(String name, int id) {
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_SERVER_GROUPS +
" SET " + Constants.GENERIC_NAME + " = ?" +
" WHERE " + Constants.GENERIC_ID + " = ?"
);
statement.setString(1, name);
statement.setInt(2, id);
statement.executeUpdate();
statement.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
} | java | {
"resource": ""
} |
q8434 | ServerRedirectService.setSourceUrl | train | public void setSourceUrl(String newUrl, int id) {
PreparedStatement statement = null;
try (Connection sqlConnection = sqlService.getConnection()) {
statement = sqlConnection.prepareStatement(
"UPDATE " + Constants.DB_TABLE_SERVERS +
" SET " + Constants.SERVER_REDIRECT_SRC_URL + " = ?" +
" WHERE " + Constants.GENERIC_ID + " = ?"
);
statement.setString(1, newUrl);
statement.setInt(2, id);
statement.executeUpdate();
statement.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
}
}
} | java | {
"resource": ""
} |
q8435 | ServerRedirectService.deleteRedirect | train | public void deleteRedirect(int id) {
try {
sqlService.executeUpdate("DELETE FROM " + Constants.DB_TABLE_SERVERS +
" WHERE " + Constants.GENERIC_ID + " = " + id + ";");
} catch (Exception e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q8436 | ServerRedirectService.deleteServerGroup | train | public void deleteServerGroup(int id) {
try {
sqlService.executeUpdate("DELETE FROM " + Constants.DB_TABLE_SERVER_GROUPS +
" WHERE " + Constants.GENERIC_ID + " = " + id + ";");
sqlService.executeUpdate("DELETE FROM " + Constants.DB_TABLE_SERVERS +
" WHERE " + Constants.SERVER_REDIRECT_GROUP_ID + " = " + id);
} catch (Exception e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q8437 | ServerRedirectService.getProfilesForServerName | train | public Profile[] getProfilesForServerName(String serverName) throws Exception {
int profileId = -1;
ArrayList<Profile> returnProfiles = new ArrayList<Profile>();
PreparedStatement queryStatement = null;
ResultSet results = null;
try (Connection sqlConnection = sqlService.getConnection()) {
queryStatement = sqlConnection.prepareStatement(
"SELECT " + Constants.GENERIC_PROFILE_ID + " FROM " + Constants.DB_TABLE_SERVERS +
" WHERE " + Constants.SERVER_REDIRECT_SRC_URL + " = ? GROUP BY " +
Constants.GENERIC_PROFILE_ID
);
queryStatement.setString(1, serverName);
results = queryStatement.executeQuery();
while (results.next()) {
profileId = results.getInt(Constants.GENERIC_PROFILE_ID);
Profile profile = ProfileService.getInstance().findProfile(profileId);
returnProfiles.add(profile);
}
} catch (SQLException e) {
throw e;
} finally {
try {
if (results != null) {
results.close();
}
} catch (Exception e) {
}
try {
if (queryStatement != null) {
queryStatement.close();
}
} catch (Exception e) {
}
}
if (returnProfiles.size() == 0) {
return null;
}
return returnProfiles.toArray(new Profile[0]);
} | java | {
"resource": ""
} |
q8438 | PluginManager.getInstance | train | public static PluginManager getInstance() {
if (_instance == null) {
_instance = new PluginManager();
_instance.classInformation = new HashMap<String, ClassInformation>();
_instance.methodInformation = new HashMap<String, com.groupon.odo.proxylib.models.Method>();
_instance.jarInformation = new ArrayList<String>();
if (_instance.proxyLibPath == null) {
//Get the System Classloader
ClassLoader sysClassLoader = Thread.currentThread().getContextClassLoader();
//Get the URLs
URL[] urls = ((URLClassLoader) sysClassLoader).getURLs();
for (int i = 0; i < urls.length; i++) {
if (urls[i].getFile().contains("proxylib")) {
// store the path to the proxylib
_instance.proxyLibPath = urls[i].getFile();
break;
}
}
}
_instance.initializePlugins();
}
return _instance;
} | java | {
"resource": ""
} |
q8439 | PluginManager.identifyClasses | train | public void identifyClasses(final String pluginDirectory) throws Exception {
methodInformation.clear();
jarInformation.clear();
try {
new FileTraversal() {
public void onDirectory(final File d) {
}
public void onFile(final File f) {
try {
// loads class files
if (f.getName().endsWith(".class")) {
// get the class name for this path
String className = f.getAbsolutePath();
className = className.replace(pluginDirectory, "");
className = getClassNameFromPath(className);
logger.info("Storing plugin information: {}, {}", className,
f.getName());
ClassInformation classInfo = new ClassInformation();
classInfo.pluginPath = pluginDirectory;
classInformation.put(className, classInfo);
} else if (f.getName().endsWith(".jar")) {
// loads JAR packages
// open up jar and discover files
// look for anything with /proxy/ in it
// this may discover things we don't need but that is OK
try {
jarInformation.add(f.getAbsolutePath());
JarFile jarFile = new JarFile(f);
Enumeration<?> enumer = jarFile.entries();
// Use the Plugin-Name manifest entry to match with the provided pluginName
String pluginPackageName = jarFile.getManifest().getMainAttributes().getValue("plugin-package");
if (pluginPackageName == null) {
return;
}
while (enumer.hasMoreElements()) {
Object element = enumer.nextElement();
String elementName = element.toString();
if (!elementName.endsWith(".class")) {
continue;
}
String className = getClassNameFromPath(elementName);
if (className.contains(pluginPackageName)) {
logger.info("Storing plugin information: {}, {}", className,
f.getAbsolutePath());
ClassInformation classInfo = new ClassInformation();
classInfo.pluginPath = f.getAbsolutePath();
classInformation.put(className, classInfo);
}
}
} catch (Exception e) {
}
}
} catch (Exception e) {
logger.warn("Exception caught: {}, {}", e.getMessage(), e.getCause());
}
}
}.traverse(new File(pluginDirectory));
} catch (IOException e) {
throw new Exception("Could not identify all plugins: " + e.getMessage());
}
} | java | {
"resource": ""
} |
q8440 | PluginManager.getClassNameFromPath | train | private String getClassNameFromPath(String path) {
String className = path.replace(".class", "");
// for *nix
if (className.startsWith("/")) {
className = className.substring(1, className.length());
}
className = className.replace("/", ".");
// for windows
if (className.startsWith("\\")) {
className = className.substring(1, className.length());
}
className = className.replace("\\", ".");
return className;
} | java | {
"resource": ""
} |
q8441 | PluginManager.loadClass | train | public void loadClass(String className) throws Exception {
ClassInformation classInfo = classInformation.get(className);
logger.info("Loading plugin.: {}, {}", className, classInfo.pluginPath);
// get URL for proxylib
// need to load this also otherwise the annotations cannot be found later on
File libFile = new File(proxyLibPath);
URL libUrl = libFile.toURI().toURL();
// store the last modified time of the plugin
File pluginDirectoryFile = new File(classInfo.pluginPath);
classInfo.lastModified = pluginDirectoryFile.lastModified();
// load the plugin directory
URL classURL = new File(classInfo.pluginPath).toURI().toURL();
URL[] urls = new URL[] {classURL};
URLClassLoader child = new URLClassLoader(urls, this.getClass().getClassLoader());
// load the class
Class<?> cls = child.loadClass(className);
// put loaded class into classInfo
classInfo.loadedClass = cls;
classInfo.loaded = true;
classInformation.put(className, classInfo);
logger.info("Loaded plugin: {}, {} method(s)", cls.toString(), cls.getDeclaredMethods().length);
} | java | {
"resource": ""
} |
q8442 | PluginManager.callFunction | train | public void callFunction(String className, String methodName, PluginArguments pluginArgs, Object... args) throws Exception {
Class<?> cls = getClass(className);
ArrayList<Object> newArgs = new ArrayList<>();
newArgs.add(pluginArgs);
com.groupon.odo.proxylib.models.Method m = preparePluginMethod(newArgs, className, methodName, args);
m.getMethod().invoke(cls, newArgs.toArray(new Object[0]));
} | java | {
"resource": ""
} |
q8443 | PluginManager.getClass | train | private synchronized Class<?> getClass(String className) throws Exception {
// see if we need to invalidate the class
ClassInformation classInfo = classInformation.get(className);
File classFile = new File(classInfo.pluginPath);
if (classFile.lastModified() > classInfo.lastModified) {
logger.info("Class {} has been modified, reloading", className);
logger.info("Thread ID: {}", Thread.currentThread().getId());
classInfo.loaded = false;
classInformation.put(className, classInfo);
// also cleanup anything in methodInformation with this className so it gets reloaded
Iterator<Map.Entry<String, com.groupon.odo.proxylib.models.Method>> iter = methodInformation.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, com.groupon.odo.proxylib.models.Method> entry = iter.next();
if (entry.getKey().startsWith(className)) {
iter.remove();
}
}
}
if (!classInfo.loaded) {
loadClass(className);
}
return classInfo.loadedClass;
} | java | {
"resource": ""
} |
q8444 | PluginManager.getMethods | train | public String[] getMethods(String pluginClass) throws Exception {
ArrayList<String> methodNames = new ArrayList<String>();
Method[] methods = getClass(pluginClass).getDeclaredMethods();
for (Method method : methods) {
logger.info("Checking {}", method.getName());
com.groupon.odo.proxylib.models.Method methodInfo = this.getMethod(pluginClass, method.getName());
if (methodInfo == null) {
continue;
}
// check annotations
Boolean matchesAnnotation = false;
if (methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_CLASS) ||
methodInfo.getMethodType().endsWith(Constants.PLUGIN_RESPONSE_OVERRIDE_V2_CLASS)) {
matchesAnnotation = true;
}
if (!methodNames.contains(method.getName()) && matchesAnnotation) {
methodNames.add(method.getName());
}
}
return methodNames.toArray(new String[0]);
} | java | {
"resource": ""
} |
q8445 | PluginManager.getMethodsNotInGroup | train | public List<com.groupon.odo.proxylib.models.Method> getMethodsNotInGroup(int groupId) throws Exception {
List<com.groupon.odo.proxylib.models.Method> allMethods = getAllMethods();
List<com.groupon.odo.proxylib.models.Method> methodsNotInGroup = new ArrayList<com.groupon.odo.proxylib.models.Method>();
List<com.groupon.odo.proxylib.models.Method> methodsInGroup = editService.getMethodsFromGroupId(groupId, null);
for (int i = 0; i < allMethods.size(); i++) {
boolean add = true;
String methodName = allMethods.get(i).getMethodName();
String className = allMethods.get(i).getClassName();
for (int j = 0; j < methodsInGroup.size(); j++) {
if ((methodName.equals(methodsInGroup.get(j).getMethodName())) &&
(className.equals(methodsInGroup.get(j).getClassName()))) {
add = false;
}
}
if (add) {
methodsNotInGroup.add(allMethods.get(i));
}
}
return methodsNotInGroup;
} | java | {
"resource": ""
} |
q8446 | PluginManager.getPlugins | train | public Plugin[] getPlugins(Boolean onlyValid) {
Configuration[] configurations = ConfigurationService.getInstance().getConfigurations(Constants.DB_TABLE_CONFIGURATION_PLUGIN_PATH);
ArrayList<Plugin> plugins = new ArrayList<Plugin>();
if (configurations == null) {
return new Plugin[0];
}
for (Configuration config : configurations) {
Plugin plugin = new Plugin();
plugin.setId(config.getId());
plugin.setPath(config.getValue());
File path = new File(plugin.getPath());
if (path.isDirectory()) {
plugin.setStatus(Constants.PLUGIN_STATUS_VALID);
plugin.setStatusMessage("Valid");
} else {
plugin.setStatus(Constants.PLUGIN_STATUS_NOT_DIRECTORY);
plugin.setStatusMessage("Path is not a directory");
}
if (!onlyValid || plugin.getStatus() == Constants.PLUGIN_STATUS_VALID) {
plugins.add(plugin);
}
}
return plugins.toArray(new Plugin[0]);
} | java | {
"resource": ""
} |
q8447 | PluginManager.getResource | train | public byte[] getResource(String pluginName, String fileName) throws Exception {
// TODO: This is going to be slow.. future improvement is to cache the data instead of searching all jars
for (String jarFilename : jarInformation) {
JarFile jarFile = new JarFile(new File(jarFilename));
Enumeration<?> enumer = jarFile.entries();
// Use the Plugin-Name manifest entry to match with the provided pluginName
String jarPluginName = jarFile.getManifest().getMainAttributes().getValue("Plugin-Name");
if (!jarPluginName.equals(pluginName)) {
continue;
}
while (enumer.hasMoreElements()) {
Object element = enumer.nextElement();
String elementName = element.toString();
// Skip items in the jar that don't start with "resources/"
if (!elementName.startsWith("resources/")) {
continue;
}
elementName = elementName.replace("resources/", "");
if (elementName.equals(fileName)) {
// get the file from the jar
ZipEntry ze = jarFile.getEntry(element.toString());
InputStream fileStream = jarFile.getInputStream(ze);
byte[] data = new byte[(int) ze.getSize()];
DataInputStream dataIs = new DataInputStream(fileStream);
dataIs.readFully(data);
dataIs.close();
return data;
}
}
}
throw new FileNotFoundException("Could not find resource");
} | java | {
"resource": ""
} |
q8448 | HostsFileUtils.changeHost | train | public static boolean changeHost(String hostName,
boolean enable,
boolean disable,
boolean remove,
boolean isEnabled,
boolean exists) throws Exception {
// Open the file that is the first
// command line parameter
File hostsFile = new File("/etc/hosts");
FileInputStream fstream = new FileInputStream("/etc/hosts");
File outFile = null;
BufferedWriter bw = null;
// only do file output for destructive operations
if (!exists && !isEnabled) {
outFile = File.createTempFile("HostsEdit", ".tmp");
bw = new BufferedWriter(new FileWriter(outFile));
System.out.println("File name: " + outFile.getPath());
}
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
boolean foundHost = false;
boolean hostEnabled = false;
/*
* Group 1 - possible commented out host entry
* Group 2 - destination address
* Group 3 - host name
* Group 4 - everything else
*/
Pattern pattern = Pattern.compile("\\s*(#?)\\s*([^\\s]+)\\s*([^\\s]+)(.*)");
while ((strLine = br.readLine()) != null) {
Matcher matcher = pattern.matcher(strLine);
// if there is a match to the pattern and the host name is the same as the one we want to set
if (matcher.find() &&
matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {
foundHost = true;
if (remove) {
// skip this line altogether
continue;
} else if (enable) {
// we will disregard group 2 and just set it to 127.0.0.1
if (!exists && !isEnabled)
bw.write("127.0.0.1 " + matcher.group(3) + matcher.group(4));
} else if (disable) {
if (!exists && !isEnabled)
bw.write("# " + matcher.group(2) + " " + matcher.group(3) + matcher.group(4));
} else if (isEnabled && matcher.group(1).compareTo("") == 0) {
// host exists and there is no # before it
hostEnabled = true;
}
} else {
// just write the line back out
if (!exists && !isEnabled)
bw.write(strLine);
}
if (!exists && !isEnabled)
bw.write('\n');
}
// if we didn't find the host in the file but need to enable it
if (!foundHost && enable) {
// write a new host entry
if (!exists && !isEnabled)
bw.write("127.0.0.1 " + hostName + '\n');
}
// Close the input stream
in.close();
if (!exists && !isEnabled) {
bw.close();
outFile.renameTo(hostsFile);
}
// return false if the host wasn't found
if (exists && !foundHost)
return false;
// return false if the host wasn't enabled
if (isEnabled && !hostEnabled)
return false;
return true;
} | java | {
"resource": ""
} |
q8449 | PluginHelper.getByteArrayDataAsString | train | public static String getByteArrayDataAsString(String contentEncoding, byte[] bytes) {
ByteArrayOutputStream byteout = null;
if (contentEncoding != null &&
contentEncoding.equals("gzip")) {
// GZIP
ByteArrayInputStream bytein = null;
GZIPInputStream zis = null;
try {
bytein = new ByteArrayInputStream(bytes);
zis = new GZIPInputStream(bytein);
byteout = new ByteArrayOutputStream();
int res = 0;
byte buf[] = new byte[1024];
while (res >= 0) {
res = zis.read(buf, 0, buf.length);
if (res > 0) {
byteout.write(buf, 0, res);
}
}
zis.close();
bytein.close();
byteout.close();
return byteout.toString();
} catch (Exception e) {
// No action to take
}
} else if (contentEncoding != null &&
contentEncoding.equals("deflate")) {
try {
// DEFLATE
byte[] buffer = new byte[1024];
Inflater decompresser = new Inflater();
byteout = new ByteArrayOutputStream();
decompresser.setInput(bytes);
while (!decompresser.finished()) {
int count = decompresser.inflate(buffer);
byteout.write(buffer, 0, count);
}
byteout.close();
decompresser.end();
return byteout.toString();
} catch (Exception e) {
// No action to take
}
}
return new String(bytes);
} | java | {
"resource": ""
} |
q8450 | BackupController.getBackup | train | @SuppressWarnings("deprecation")
@RequestMapping(value = "/api/backup", method = RequestMethod.GET)
public
@ResponseBody
String getBackup(Model model, HttpServletResponse response) throws Exception {
response.addHeader("Content-Disposition", "attachment; filename=backup.json");
response.setContentType("application/json");
Backup backup = BackupService.getInstance().getBackupData();
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
return writer.withView(ViewFilters.Default.class).writeValueAsString(backup);
} | java | {
"resource": ""
} |
q8451 | BackupController.processBackup | train | @RequestMapping(value = "/api/backup", method = RequestMethod.POST)
public
@ResponseBody
Backup processBackup(@RequestParam("fileData") MultipartFile fileData) throws Exception {
// Method taken from: http://spring.io/guides/gs/uploading-files/
if (!fileData.isEmpty()) {
try {
byte[] bytes = fileData.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File("backup-uploaded.json")));
stream.write(bytes);
stream.close();
} catch (Exception e) {
}
}
File f = new File("backup-uploaded.json");
BackupService.getInstance().restoreBackupData(new FileInputStream(f));
return BackupService.getInstance().getBackupData();
} | java | {
"resource": ""
} |
q8452 | Client.enableHost | train | public static void enableHost(String hostName) throws Exception {
Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", port);
com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);
impl.enableHost(hostName);
} | java | {
"resource": ""
} |
q8453 | Client.isAvailable | train | public static boolean isAvailable() throws Exception {
try {
Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", port);
com.groupon.odo.proxylib.hostsedit.rmi.Message impl = (com.groupon.odo.proxylib.hostsedit.rmi.Message) myRegistry.lookup(SERVICE_NAME);
return true;
} catch (Exception e) {
return false;
}
} | java | {
"resource": ""
} |
q8454 | FreeMarkerTag.getContextPath | train | protected String getContextPath(){
if(context != null) return context;
if(get("context_path") == null){
throw new ViewException("context_path missing - red alarm!");
}
return get("context_path").toString();
} | java | {
"resource": ""
} |
q8455 | FreeMarkerTag.process | train | protected void process(String text, Map params, Writer writer){
try{
Template t = new Template("temp", new StringReader(text), FreeMarkerTL.getEnvironment().getConfiguration());
t.process(params, writer);
}catch(Exception e){
throw new ViewException(e);
}
} | java | {
"resource": ""
} |
q8456 | FreeMarkerTag.getAllVariables | train | protected Map getAllVariables(){
try{
Iterator names = FreeMarkerTL.getEnvironment().getKnownVariableNames().iterator();
Map vars = new HashMap();
while (names.hasNext()) {
Object name =names.next();
vars.put(name, get(name.toString()));
}
return vars;
}catch(Exception e){
throw new ViewException(e);
}
} | java | {
"resource": ""
} |
q8457 | Sobel.apply | train | @Override
public ImageSource apply(ImageSource input) {
final int[][] pixelMatrix = new int[3][3];
int w = input.getWidth();
int h = input.getHeight();
int[][] output = new int[h][w];
for (int j = 1; j < h - 1; j++) {
for (int i = 1; i < w - 1; i++) {
pixelMatrix[0][0] = input.getR(i - 1, j - 1);
pixelMatrix[0][1] = input.getRGB(i - 1, j);
pixelMatrix[0][2] = input.getRGB(i - 1, j + 1);
pixelMatrix[1][0] = input.getRGB(i, j - 1);
pixelMatrix[1][2] = input.getRGB(i, j + 1);
pixelMatrix[2][0] = input.getRGB(i + 1, j - 1);
pixelMatrix[2][1] = input.getRGB(i + 1, j);
pixelMatrix[2][2] = input.getRGB(i + 1, j + 1);
int edge = (int) convolution(pixelMatrix);
int rgb = (edge << 16 | edge << 8 | edge);
output[j][i] = rgb;
}
}
MatrixSource source = new MatrixSource(output);
return source;
} | java | {
"resource": ""
} |
q8458 | EventStackImpl.popEvent | train | public <L extends Listener> void popEvent(Event<?, L> expected) {
synchronized (this.stack) {
final Event<?, ?> actual = this.stack.pop();
if (actual != expected) {
throw new IllegalStateException(String.format(
"Unbalanced pop: expected '%s' but encountered '%s'",
expected.getListenerClass(), actual));
}
}
} | java | {
"resource": ""
} |
q8459 | AbstractSynchronizedListenerSource.modify | train | protected void modify(Transaction t) {
try {
this.lock.writeLock().lock();
t.perform();
} finally {
this.lock.writeLock().unlock();
}
} | java | {
"resource": ""
} |
q8460 | AbstractSynchronizedListenerSource.read | train | protected <E> E read(Supplier<E> sup) {
try {
this.lock.readLock().lock();
return sup.get();
} finally {
this.lock.readLock().unlock();
}
} | java | {
"resource": ""
} |
q8461 | SubIIMInputStream.setOffsetAndLength | train | protected void setOffsetAndLength(long offset, int length) throws IOException {
this.offset = offset;
this.length = length;
this.position = 0;
if (subStream.position() != offset) {
subStream.seek(offset);
}
} | java | {
"resource": ""
} |
q8462 | Bessel.J0 | train | public static double J0(double x) {
double ax;
if ((ax = Math.abs(x)) < 8.0) {
double y = x * x;
double ans1 = 57568490574.0 + y * (-13362590354.0 + y * (651619640.7
+ y * (-11214424.18 + y * (77392.33017 + y * (-184.9052456)))));
double ans2 = 57568490411.0 + y * (1029532985.0 + y * (9494680.718
+ y * (59272.64853 + y * (267.8532712 + y * 1.0))));
return ans1 / ans2;
} else {
double z = 8.0 / ax;
double y = z * z;
double xx = ax - 0.785398164;
double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4
+ y * (-0.2073370639e-5 + y * 0.2093887211e-6)));
double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3
+ y * (-0.6911147651e-5 + y * (0.7621095161e-6
- y * 0.934935152e-7)));
return Math.sqrt(0.636619772 / ax) *
(Math.cos(xx) * ans1 - z * Math.sin(xx) * ans2);
}
} | java | {
"resource": ""
} |
q8463 | Bessel.J | train | public static double J(int n, double x) {
int j, m;
double ax, bj, bjm, bjp, sum, tox, ans;
boolean jsum;
double ACC = 40.0;
double BIGNO = 1.0e+10;
double BIGNI = 1.0e-10;
if (n == 0) return J0(x);
if (n == 1) return J(x);
ax = Math.abs(x);
if (ax == 0.0) return 0.0;
else if (ax > (double) n) {
tox = 2.0 / ax;
bjm = J0(ax);
bj = J(ax);
for (j = 1; j < n; j++) {
bjp = j * tox * bj - bjm;
bjm = bj;
bj = bjp;
}
ans = bj;
} else {
tox = 2.0 / ax;
m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2);
jsum = false;
bjp = ans = sum = 0.0;
bj = 1.0;
for (j = m; j > 0; j--) {
bjm = j * tox * bj - bjp;
bjp = bj;
bj = bjm;
if (Math.abs(bj) > BIGNO) {
bj *= BIGNI;
bjp *= BIGNI;
ans *= BIGNI;
sum *= BIGNI;
}
if (jsum) sum += bj;
jsum = !jsum;
if (j == n) ans = bjp;
}
sum = 2.0 * sum - bj;
ans /= sum;
}
return x < 0.0 && n % 2 == 1 ? -ans : ans;
} | java | {
"resource": ""
} |
q8464 | Bessel.Y0 | train | public static double Y0(double x) {
if (x < 8.0) {
double y = x * x;
double ans1 = -2957821389.0 + y * (7062834065.0 + y * (-512359803.6
+ y * (10879881.29 + y * (-86327.92757 + y * 228.4622733))));
double ans2 = 40076544269.0 + y * (745249964.8 + y * (7189466.438
+ y * (47447.26470 + y * (226.1030244 + y * 1.0))));
return (ans1 / ans2) + 0.636619772 * J0(x) * Math.log(x);
} else {
double z = 8.0 / x;
double y = z * z;
double xx = x - 0.785398164;
double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4
+ y * (-0.2073370639e-5 + y * 0.2093887211e-6)));
double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3
+ y * (-0.6911147651e-5 + y * (0.7621095161e-6
+ y * (-0.934945152e-7))));
return Math.sqrt(0.636619772 / x) *
(Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);
}
} | java | {
"resource": ""
} |
q8465 | Bessel.Y | train | public static double Y(double x) {
if (x < 8.0) {
double y = x * x;
double ans1 = x * (-0.4900604943e13 + y * (0.1275274390e13
+ y * (-0.5153438139e11 + y * (0.7349264551e9
+ y * (-0.4237922726e7 + y * 0.8511937935e4)))));
double ans2 = 0.2499580570e14 + y * (0.4244419664e12
+ y * (0.3733650367e10 + y * (0.2245904002e8
+ y * (0.1020426050e6 + y * (0.3549632885e3 + y)))));
return (ans1 / ans2) + 0.636619772 * (J(x) * Math.log(x) - 1.0 / x);
} else {
double z = 8.0 / x;
double y = z * z;
double xx = x - 2.356194491;
double ans1 = 1.0 + y * (0.183105e-2 + y * (-0.3516396496e-4
+ y * (0.2457520174e-5 + y * (-0.240337019e-6))));
double ans2 = 0.04687499995 + y * (-0.2002690873e-3
+ y * (0.8449199096e-5 + y * (-0.88228987e-6
+ y * 0.105787412e-6)));
return Math.sqrt(0.636619772 / x) *
(Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);
}
} | java | {
"resource": ""
} |
q8466 | Bessel.Y | train | public static double Y(int n, double x) {
double by, bym, byp, tox;
if (n == 0) return Y0(x);
if (n == 1) return Y(x);
tox = 2.0 / x;
by = Y(x);
bym = Y0(x);
for (int j = 1; j < n; j++) {
byp = j * tox * by - bym;
bym = by;
by = byp;
}
return by;
} | java | {
"resource": ""
} |
q8467 | Bessel.I0 | train | public static double I0(double x) {
double ans;
double ax = Math.abs(x);
if (ax < 3.75) {
double y = x / 3.75;
y = y * y;
ans = 1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492
+ y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2)))));
} else {
double y = 3.75 / ax;
ans = (Math.exp(ax) / Math.sqrt(ax)) * (0.39894228 + y * (0.1328592e-1
+ y * (0.225319e-2 + y * (-0.157565e-2 + y * (0.916281e-2
+ y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1
+ y * 0.392377e-2))))))));
}
return ans;
} | java | {
"resource": ""
} |
q8468 | Bessel.I | train | public static double I(int n, double x) {
if (n < 0)
throw new IllegalArgumentException("the variable n out of range.");
else if (n == 0)
return I0(x);
else if (n == 1)
return I(x);
if (x == 0.0)
return 0.0;
double ACC = 40.0;
double BIGNO = 1.0e+10;
double BIGNI = 1.0e-10;
double tox = 2.0 / Math.abs(x);
double bip = 0, ans = 0.0;
double bi = 1.0;
for (int j = 2 * (n + (int) Math.sqrt(ACC * n)); j > 0; j--) {
double bim = bip + j * tox * bi;
bip = bi;
bi = bim;
if (Math.abs(bi) > BIGNO) {
ans *= BIGNI;
bi *= BIGNI;
bip *= BIGNI;
}
if (j == n)
ans = bip;
}
ans *= I0(x) / bi;
return x < 0.0 && n % 2 == 1 ? -ans : ans;
} | java | {
"resource": ""
} |
q8469 | SobelNormalMap.apply | train | @Override
public ImageSource apply(ImageSource input) {
int w = input.getWidth();
int h = input.getHeight();
MatrixSource output = new MatrixSource(input);
Vector3 n = new Vector3(0, 0, 1);
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if (x < border || x == w - border || y < border || y == h - border) {
output.setRGB(x, y, VectorHelper.Z_NORMAL);
continue;
}
float s0 = input.getR(x - 1, y + 1);
float s1 = input.getR(x, y + 1);
float s2 = input.getR(x + 1, y + 1);
float s3 = input.getR(x - 1, y);
float s5 = input.getR(x + 1, y);
float s6 = input.getR(x - 1, y - 1);
float s7 = input.getR(x, y - 1);
float s8 = input.getR(x + 1, y - 1);
float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);
float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);
n.set(nx, ny, scale);
n.nor();
int rgb = VectorHelper.vectorToColor(n);
output.setRGB(x, y, rgb);
}
}
return new MatrixSource(output);
} | java | {
"resource": ""
} |
q8470 | RatpackCurrentTraceContext.wrap | train | @Deprecated
public static TraceContextHolder wrap(TraceContext traceContext) {
return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;
} | java | {
"resource": ""
} |
q8471 | Tools.Sinc | train | public static double Sinc(double x) {
return Math.sin(Math.PI * x) / (Math.PI * x);
} | java | {
"resource": ""
} |
q8472 | Tools.Mod | train | public static int Mod(int x, int m) {
if (m < 0) m = -m;
int r = x % m;
return r < 0 ? r + m : r;
} | java | {
"resource": ""
} |
q8473 | Tools.NextPowerOf2 | train | public static int NextPowerOf2(int x) {
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return ++x;
} | java | {
"resource": ""
} |
q8474 | Tools.Sum | train | public static float Sum(float[] data) {
float sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
return sum;
} | java | {
"resource": ""
} |
q8475 | Tools.TruncatedPower | train | public static double TruncatedPower(double value, double degree) {
double x = Math.pow(value, degree);
return (x > 0) ? x : 0.0;
} | java | {
"resource": ""
} |
q8476 | Tools.Unique | train | public static int[] Unique(int[] values) {
HashSet<Integer> lst = new HashSet<Integer>();
for (int i = 0; i < values.length; i++) {
lst.add(values[i]);
}
int[] v = new int[lst.size()];
Iterator<Integer> it = lst.iterator();
for (int i = 0; i < v.length; i++) {
v[i] = it.next();
}
return v;
} | java | {
"resource": ""
} |
q8477 | AlphaTrimmedMean.setT | train | public void setT(int t) {
this.t = Math.min((radius * 2 + 1) * (radius * 2 + 1) / 2, Math.max(0, t));
} | java | {
"resource": ""
} |
q8478 | TaylorSeries.Sin | train | public static double Sin(double x, int nTerms) {
if (nTerms < 2) return x;
if (nTerms == 2) {
return x - (x * x * x) / 6D;
} else {
double mult = x * x * x;
double fact = 6;
double sign = 1;
int factS = 5;
double result = x - mult / fact;
for (int i = 3; i <= nTerms; i++) {
mult *= x * x;
fact *= factS * (factS - 1);
factS += 2;
result += sign * (mult / fact);
sign *= -1;
}
return result;
}
} | java | {
"resource": ""
} |
q8479 | TaylorSeries.Sinh | train | public static double Sinh(double x, int nTerms) {
if (nTerms < 2) return x;
if (nTerms == 2) {
return x + (x * x * x) / 6D;
} else {
double mult = x * x * x;
double fact = 6;
int factS = 5;
double result = x + mult / fact;
for (int i = 3; i <= nTerms; i++) {
mult *= x * x;
fact *= factS * (factS - 1);
factS += 2;
result += mult / fact;
}
return result;
}
} | java | {
"resource": ""
} |
q8480 | TaylorSeries.Cosh | train | public static double Cosh(double x, int nTerms) {
if (nTerms < 2) return x;
if (nTerms == 2) {
return 1 + (x * x) / 2D;
} else {
double mult = x * x;
double fact = 2;
int factS = 4;
double result = 1 + mult / fact;
for (int i = 3; i <= nTerms; i++) {
mult *= x * x;
fact *= factS * (factS - 1);
factS += 2;
result += mult / fact;
}
return result;
}
} | java | {
"resource": ""
} |
q8481 | TaylorSeries.Exp | train | public static double Exp(double x, int nTerms) {
if (nTerms < 2) return 1 + x;
if (nTerms == 2) {
return 1 + x + (x * x) / 2;
} else {
double mult = x * x;
double fact = 2;
double result = 1 + x + mult / fact;
for (int i = 3; i <= nTerms; i++) {
mult *= x;
fact *= i;
result += mult / fact;
}
return result;
}
} | java | {
"resource": ""
} |
q8482 | LUDecomposition.getU | train | public double[][] getU() {
double[][] X = new double[n][n];
double[][] U = X;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i <= j) {
U[i][j] = LU[i][j];
} else {
U[i][j] = 0.0;
}
}
}
return X;
} | java | {
"resource": ""
} |
q8483 | LUDecomposition.determinant | train | public double determinant() {
if (m != n) {
throw new IllegalArgumentException("Matrix must be square.");
}
double d = (double) pivsign;
for (int j = 0; j < n; j++) {
d *= LU[j][j];
}
return d;
} | java | {
"resource": ""
} |
q8484 | ComplexNumber.Add | train | public static ComplexNumber Add(ComplexNumber z1, ComplexNumber z2) {
return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);
} | java | {
"resource": ""
} |
q8485 | ComplexNumber.Add | train | public static ComplexNumber Add(ComplexNumber z1, double scalar) {
return new ComplexNumber(z1.real + scalar, z1.imaginary);
} | java | {
"resource": ""
} |
q8486 | ComplexNumber.Subtract | train | public static ComplexNumber Subtract(ComplexNumber z1, ComplexNumber z2) {
return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);
} | java | {
"resource": ""
} |
q8487 | ComplexNumber.Subtract | train | public static ComplexNumber Subtract(ComplexNumber z1, double scalar) {
return new ComplexNumber(z1.real - scalar, z1.imaginary);
} | java | {
"resource": ""
} |
q8488 | ComplexNumber.Magnitude | train | public static double Magnitude(ComplexNumber z) {
return Math.sqrt(z.real * z.real + z.imaginary * z.imaginary);
} | java | {
"resource": ""
} |
q8489 | ComplexNumber.Multiply | train | public static ComplexNumber Multiply(ComplexNumber z1, ComplexNumber z2) {
double z1R = z1.real, z1I = z1.imaginary;
double z2R = z2.real, z2I = z2.imaginary;
return new ComplexNumber(z1R * z2R - z1I * z2I, z1R * z2I + z1I * z2R);
} | java | {
"resource": ""
} |
q8490 | ComplexNumber.Multiply | train | public static ComplexNumber Multiply(ComplexNumber z1, double scalar) {
return new ComplexNumber(z1.real * scalar, z1.imaginary * scalar);
} | java | {
"resource": ""
} |
q8491 | ComplexNumber.Divide | train | public static ComplexNumber Divide(ComplexNumber z1, ComplexNumber z2) {
ComplexNumber conj = ComplexNumber.Conjugate(z2);
double a = z1.real * conj.real + ((z1.imaginary * conj.imaginary) * -1);
double b = z1.real * conj.imaginary + (z1.imaginary * conj.real);
double c = z2.real * conj.real + ((z2.imaginary * conj.imaginary) * -1);
return new ComplexNumber(a / c, b / c);
} | java | {
"resource": ""
} |
q8492 | ComplexNumber.Pow | train | public static ComplexNumber Pow(ComplexNumber z1, double n) {
double norm = Math.pow(z1.getMagnitude(), n);
double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real)));
double common = n * angle;
double r = norm * Math.cos(Math.toRadians(common));
double i = norm * Math.sin(Math.toRadians(common));
return new ComplexNumber(r, i);
} | java | {
"resource": ""
} |
q8493 | ComplexNumber.Sin | train | public static ComplexNumber Sin(ComplexNumber z1) {
ComplexNumber result = new ComplexNumber();
if (z1.imaginary == 0.0) {
result.real = Math.sin(z1.real);
result.imaginary = 0.0;
} else {
result.real = Math.sin(z1.real) * Math.cosh(z1.imaginary);
result.imaginary = Math.cos(z1.real) * Math.sinh(z1.imaginary);
}
return result;
} | java | {
"resource": ""
} |
q8494 | ComplexNumber.Tan | train | public static ComplexNumber Tan(ComplexNumber z1) {
ComplexNumber result = new ComplexNumber();
if (z1.imaginary == 0.0) {
result.real = Math.tan(z1.real);
result.imaginary = 0.0;
} else {
double real2 = 2 * z1.real;
double imag2 = 2 * z1.imaginary;
double denom = Math.cos(real2) + Math.cosh(real2);
result.real = Math.sin(real2) / denom;
result.imaginary = Math.sinh(imag2) / denom;
}
return result;
} | java | {
"resource": ""
} |
q8495 | UniversalGenerator.srand | train | private void srand(int ijkl) {
u = new double[97];
int ij = ijkl / 30082;
int kl = ijkl % 30082;
// Handle the seed range errors
// First random number seed must be between 0 and 31328
// Second seed must have a value between 0 and 30081
if (ij < 0 || ij > 31328 || kl < 0 || kl > 30081) {
ij = ij % 31329;
kl = kl % 30082;
}
int i = ((ij / 177) % 177) + 2;
int j = (ij % 177) + 2;
int k = ((kl / 169) % 178) + 1;
int l = kl % 169;
int m;
double s, t;
for (int ii = 0; ii < 97; ii++) {
s = 0.0;
t = 0.5;
for (int jj = 0; jj < 24; jj++) {
m = (((i * j) % 179) * k) % 179;
i = j;
j = k;
k = m;
l = (53 * l + 1) % 169;
if (((l * m) % 64) >= 32) {
s += t;
}
t *= 0.5;
}
u[ii] = s;
}
c = 362436.0 / 16777216.0;
cd = 7654321.0 / 16777216.0;
cm = 16777213.0 / 16777216.0;
i97 = 96;
j97 = 32;
} | java | {
"resource": ""
} |
q8496 | IntPoint.DistanceTo | train | public float DistanceTo(IntPoint anotherPoint) {
float dx = this.x - anotherPoint.x;
float dy = this.y - anotherPoint.y;
return (float) Math.sqrt(dx * dx + dy * dy);
} | java | {
"resource": ""
} |
q8497 | HistogramStatistics.Entropy | train | public static double Entropy( int[] values ){
int n = values.length;
int total = 0;
double entropy = 0;
double p;
// calculate total amount of hits
for ( int i = 0; i < n; i++ )
{
total += values[i];
}
if ( total != 0 )
{
// for all values
for ( int i = 0; i < n; i++ )
{
// get item's probability
p = (double) values[i] / total;
// calculate entropy
if ( p != 0 )
entropy += ( -p * (Math.log10(p)/Math.log10(2)) );
}
}
return entropy;
} | java | {
"resource": ""
} |
q8498 | HistogramStatistics.GetRange | train | public static IntRange GetRange( int[] values, double percent ){
int total = 0, n = values.length;
// for all values
for ( int i = 0; i < n; i++ )
{
// accumalate total
total += values[i];
}
int min, max, hits;
int h = (int) ( total * ( percent + ( 1 - percent ) / 2 ) );
// get range min value
for ( min = 0, hits = total; min < n; min++ )
{
hits -= values[min];
if ( hits < h )
break;
}
// get range max value
for ( max = n - 1, hits = total; max >= 0; max-- )
{
hits -= values[max];
if ( hits < h )
break;
}
return new IntRange( min, max );
} | java | {
"resource": ""
} |
q8499 | HistogramStatistics.Median | train | public static int Median( int[] values ){
int total = 0, n = values.length;
// for all values
for ( int i = 0; i < n; i++ )
{
// accumalate total
total += values[i];
}
int halfTotal = total / 2;
int median = 0, v = 0;
// find median value
for ( ; median < n; median++ )
{
v += values[median];
if ( v >= halfTotal )
break;
}
return median;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.