_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q8200
ReleaseAction.doApi
train
@SuppressWarnings({"UnusedDeclaration"}) protected void doApi(StaplerRequest req, StaplerResponse resp) throws IOException, ServletException { try { log.log(Level.INFO, "Initiating Artifactory Release Staging using API"); // Enforce release permissions project.checkPermission(ArtifactoryPlugin.RELEASE); // In case a staging user plugin is configured, the init() method invoke it: init(); // Read the values provided by the staging user plugin and assign them to data members in this class. // Those values can be overriden by URL arguments sent with the API: readStagingPluginValues(); // Read values from the request and override the staging plugin values: overrideStagingPluginParams(req); // Schedule the release build: Queue.WaitingItem item = Jenkins.getInstance().getQueue().schedule( project, 0, new Action[]{this, new CauseAction(new Cause.UserIdCause())} ); if (item == null) { log.log(Level.SEVERE, "Failed to schedule a release build following a Release API invocation"); resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR); } else { String url = req.getContextPath() + '/' + item.getUrl(); JSONObject json = new JSONObject(); json.element("queueItem", item.getId()); json.element("releaseVersion", getReleaseVersion()); json.element("nextVersion", getNextVersion()); json.element("releaseBranch", getReleaseBranch()); // Must use getOutputStream as sendRedirect uses getOutputStream (and closes it) resp.getOutputStream().print(json.toString()); resp.sendRedirect(201, url); } } catch (Exception e) { log.log(Level.SEVERE, "Artifactory Release Staging API invocation failed: " + e.getMessage(), e); resp.setStatus(StaplerResponse.SC_INTERNAL_SERVER_ERROR); ErrorResponse errorResponse = new ErrorResponse(StaplerResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); resp.getWriter().write(mapper.writeValueAsString(errorResponse)); } }
java
{ "resource": "" }
q8201
ReleaseAction.calculateNextVersion
train
protected String calculateNextVersion(String fromVersion) { // first turn it to release version fromVersion = calculateReleaseVersion(fromVersion); String nextVersion; int lastDotIndex = fromVersion.lastIndexOf('.'); try { if (lastDotIndex != -1) { // probably a major minor version e.g., 2.1.1 String minorVersionToken = fromVersion.substring(lastDotIndex + 1); String nextMinorVersion; int lastDashIndex = minorVersionToken.lastIndexOf('-'); if (lastDashIndex != -1) { // probably a minor-buildNum e.g., 2.1.1-4 (should change to 2.1.1-5) String buildNumber = minorVersionToken.substring(lastDashIndex + 1); int nextBuildNumber = Integer.parseInt(buildNumber) + 1; nextMinorVersion = minorVersionToken.substring(0, lastDashIndex + 1) + nextBuildNumber; } else { nextMinorVersion = Integer.parseInt(minorVersionToken) + 1 + ""; } nextVersion = fromVersion.substring(0, lastDotIndex + 1) + nextMinorVersion; } else { // maybe it's just a major version; try to parse as an int int nextMajorVersion = Integer.parseInt(fromVersion) + 1; nextVersion = nextMajorVersion + ""; } } catch (NumberFormatException e) { return fromVersion; } return nextVersion + "-SNAPSHOT"; }
java
{ "resource": "" }
q8202
ReleaseAction.addVars
train
public void addVars(Map<String, String> env) { if (tagUrl != null) { env.put("RELEASE_SCM_TAG", tagUrl); env.put(RT_RELEASE_STAGING + "SCM_TAG", tagUrl); } if (releaseBranch != null) { env.put("RELEASE_SCM_BRANCH", releaseBranch); env.put(RT_RELEASE_STAGING + "SCM_BRANCH", releaseBranch); } if (releaseVersion != null) { env.put(RT_RELEASE_STAGING + "VERSION", releaseVersion); } if (nextVersion != null) { env.put(RT_RELEASE_STAGING + "NEXT_VERSION", nextVersion); } }
java
{ "resource": "" }
q8203
GradleInitScriptWriter.generateInitScript
train
public String generateInitScript(EnvVars env) throws IOException, InterruptedException { StringBuilder initScript = new StringBuilder(); InputStream templateStream = getClass().getResourceAsStream("/initscripttemplate.gradle"); String templateAsString = IOUtils.toString(templateStream, Charsets.UTF_8.name()); File extractorJar = PluginDependencyHelper.getExtractorJar(env); FilePath dependencyDir = PluginDependencyHelper.getActualDependencyDirectory(extractorJar, rootPath); String absoluteDependencyDirPath = dependencyDir.getRemote(); absoluteDependencyDirPath = absoluteDependencyDirPath.replace("\\", "/"); String str = templateAsString.replace("${pluginLibDir}", absoluteDependencyDirPath); initScript.append(str); return initScript.toString(); }
java
{ "resource": "" }
q8204
BinaryUtils.convertBytesToInt
train
public static int convertBytesToInt(byte[] bytes, int offset) { return (BITWISE_BYTE_TO_INT & bytes[offset + 3]) | ((BITWISE_BYTE_TO_INT & bytes[offset + 2]) << 8) | ((BITWISE_BYTE_TO_INT & bytes[offset + 1]) << 16) | ((BITWISE_BYTE_TO_INT & bytes[offset]) << 24); }
java
{ "resource": "" }
q8205
BinaryUtils.convertBytesToInts
train
public static int[] convertBytesToInts(byte[] bytes) { if (bytes.length % 4 != 0) { throw new IllegalArgumentException("Number of input bytes must be a multiple of 4."); } int[] ints = new int[bytes.length / 4]; for (int i = 0; i < ints.length; i++) { ints[i] = convertBytesToInt(bytes, i * 4); } return ints; }
java
{ "resource": "" }
q8206
BinaryUtils.convertBytesToLong
train
public static long convertBytesToLong(byte[] bytes, int offset) { long value = 0; for (int i = offset; i < offset + 8; i++) { byte b = bytes[i]; value <<= 8; value |= b; } return value; }
java
{ "resource": "" }
q8207
GaussianDistribution.getExpectedProbability
train
private double getExpectedProbability(double x) { double y = 1 / (standardDeviation * Math.sqrt(Math.PI * 2)); double z = -(Math.pow(x - mean, 2) / (2 * Math.pow(standardDeviation, 2))); return y * Math.exp(z); }
java
{ "resource": "" }
q8208
PermutationGenerator.reset
train
public final void reset() { for (int i = 0; i < permutationIndices.length; i++) { permutationIndices[i] = i; } remainingPermutations = totalPermutations; }
java
{ "resource": "" }
q8209
PermutationGenerator.nextPermutationAsArray
train
@SuppressWarnings("unchecked") public T[] nextPermutationAsArray() { T[] permutation = (T[]) Array.newInstance(elements.getClass().getComponentType(), permutationIndices.length); return nextPermutationAsArray(permutation); }
java
{ "resource": "" }
q8210
PermutationGenerator.nextPermutationAsList
train
public List<T> nextPermutationAsList() { List<T> permutation = new ArrayList<T>(elements.length); return nextPermutationAsList(permutation); }
java
{ "resource": "" }
q8211
JavaRNG.createLongSeed
train
private static long createLongSeed(byte[] seed) { if (seed == null || seed.length != SEED_SIZE_BYTES) { throw new IllegalArgumentException("Java RNG requires a 64-bit (8-byte) seed."); } return BinaryUtils.convertBytesToLong(seed, 0); }
java
{ "resource": "" }
q8212
SwingBackgroundTask.execute
train
public void execute() { Runnable task = new Runnable() { public void run() { final V result = performTask(); SwingUtilities.invokeLater(new Runnable() { public void run() { postProcessing(result); latch.countDown(); } }); } }; new Thread(task, "SwingBackgroundTask-" + id).start(); }
java
{ "resource": "" }
q8213
DataSet.addValue
train
public void addValue(double value) { if (dataSetSize == dataSet.length) { // Increase the capacity of the array. int newLength = (int) (GROWTH_RATE * dataSetSize); double[] newDataSet = new double[newLength]; System.arraycopy(dataSet, 0, newDataSet, 0, dataSetSize); dataSet = newDataSet; } dataSet[dataSetSize] = value; updateStatsWithNewValue(value); ++dataSetSize; }
java
{ "resource": "" }
q8214
DataSet.getMedian
train
public final double getMedian() { assertNotEmpty(); // Sort the data (take a copy to do this). double[] dataCopy = new double[getSize()]; System.arraycopy(dataSet, 0, dataCopy, 0, dataCopy.length); Arrays.sort(dataCopy); int midPoint = dataCopy.length / 2; if (dataCopy.length % 2 != 0) { return dataCopy[midPoint]; } else { return dataCopy[midPoint - 1] + (dataCopy[midPoint] - dataCopy[midPoint - 1]) / 2; } }
java
{ "resource": "" }
q8215
DataSet.sumSquaredDiffs
train
private double sumSquaredDiffs() { double mean = getArithmeticMean(); double squaredDiffs = 0; for (int i = 0; i < getSize(); i++) { double diff = mean - dataSet[i]; squaredDiffs += (diff * diff); } return squaredDiffs; }
java
{ "resource": "" }
q8216
BitString.getBit
train
public boolean getBit(int index) { assertValidIndex(index); int word = index / WORD_LENGTH; int offset = index % WORD_LENGTH; return (data[word] & (1 << offset)) != 0; }
java
{ "resource": "" }
q8217
BitString.setBit
train
public void setBit(int index, boolean set) { assertValidIndex(index); int word = index / WORD_LENGTH; int offset = index % WORD_LENGTH; if (set) { data[word] |= (1 << offset); } else // Unset the bit. { data[word] &= ~(1 << offset); } }
java
{ "resource": "" }
q8218
BitString.flipBit
train
public void flipBit(int index) { assertValidIndex(index); int word = index / WORD_LENGTH; int offset = index % WORD_LENGTH; data[word] ^= (1 << offset); }
java
{ "resource": "" }
q8219
BitString.swapSubstring
train
public void swapSubstring(BitString other, int start, int length) { assertValidIndex(start); other.assertValidIndex(start); int word = start / WORD_LENGTH; int partialWordSize = (WORD_LENGTH - start) % WORD_LENGTH; if (partialWordSize > 0) { swapBits(other, word, 0xFFFFFFFF << (WORD_LENGTH - partialWordSize)); ++word; } int remainingBits = length - partialWordSize; int stop = remainingBits / WORD_LENGTH; for (int i = word; i < stop; i++) { int temp = data[i]; data[i] = other.data[i]; other.data[i] = temp; } remainingBits %= WORD_LENGTH; if (remainingBits > 0) { swapBits(other, word, 0xFFFFFFFF >>> (WORD_LENGTH - remainingBits)); } }
java
{ "resource": "" }
q8220
Rational.compareTo
train
public int compareTo(Rational other) { if (denominator == other.getDenominator()) { return ((Long) numerator).compareTo(other.getNumerator()); } else { Long adjustedNumerator = numerator * other.getDenominator(); Long otherAdjustedNumerator = other.getNumerator() * denominator; return adjustedNumerator.compareTo(otherAdjustedNumerator); } }
java
{ "resource": "" }
q8221
DiehardInputGenerator.generateOutputFile
train
public static void generateOutputFile(Random rng, File outputFile) throws IOException { DataOutputStream dataOutput = null; try { dataOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); for (int i = 0; i < INT_COUNT; i++) { dataOutput.writeInt(rng.nextInt()); } dataOutput.flush(); } finally { if (dataOutput != null) { dataOutput.close(); } } }
java
{ "resource": "" }
q8222
Maths.raiseToPower
train
public static long raiseToPower(int value, int power) { if (power < 0) { throw new IllegalArgumentException("This method does not support negative powers."); } long result = 1; for (int i = 0; i < power; i++) { result *= value; } return result; }
java
{ "resource": "" }
q8223
Maths.restrictRange
train
public static int restrictRange(int value, int min, int max) { return Math.min((Math.max(value, min)), max); }
java
{ "resource": "" }
q8224
ProbabilityDistribution.doQuantization
train
protected static Map<Double, Double> doQuantization(double max, double min, double[] values) { double range = max - min; int noIntervals = 20; double intervalSize = range / noIntervals; int[] intervals = new int[noIntervals]; for (double value : values) { int interval = Math.min(noIntervals - 1, (int) Math.floor((value - min) / intervalSize)); assert interval >= 0 && interval < noIntervals : "Invalid interval: " + interval; ++intervals[interval]; } Map<Double, Double> discretisedValues = new HashMap<Double, Double>(); for (int i = 0; i < intervals.length; i++) { // Correct the value to take into account the size of the interval. double value = (1 / intervalSize) * (double) intervals[i]; discretisedValues.put(min + ((i + 0.5) * intervalSize), value); } return discretisedValues; }
java
{ "resource": "" }
q8225
CombinationGenerator.reset
train
public final void reset() { for (int i = 0; i < combinationIndices.length; i++) { combinationIndices[i] = i; } remainingCombinations = totalCombinations; }
java
{ "resource": "" }
q8226
CombinationGenerator.nextCombinationAsArray
train
@SuppressWarnings("unchecked") public T[] nextCombinationAsArray() { T[] combination = (T[]) Array.newInstance(elements.getClass().getComponentType(), combinationIndices.length); return nextCombinationAsArray(combination); }
java
{ "resource": "" }
q8227
AdjustableNumberGenerator.setValue
train
public void setValue(T value) { try { lock.writeLock().lock(); this.value = value; } finally { lock.writeLock().unlock(); } }
java
{ "resource": "" }
q8228
AcsURLEncoder.urlEncode
train
public static String urlEncode(String path) throws URISyntaxException { if (isNullOrEmpty(path)) return path; return UrlEscapers.urlFragmentEscaper().escape(path); }
java
{ "resource": "" }
q8229
AcsURLEncoder.encode
train
public static String encode(String value) throws UnsupportedEncodingException { if (isNullOrEmpty(value)) return value; return URLEncoder.encode(value, URL_ENCODING); }
java
{ "resource": "" }
q8230
HttpResponse.getResponse
train
public static HttpResponse getResponse(String urls, HttpRequest request, HttpMethod method, int connectTimeoutMillis, int readTimeoutMillis) throws IOException { OutputStream out = null; InputStream content = null; HttpResponse response = null; HttpURLConnection httpConn = request .getHttpConnection(urls, method.name()); httpConn.setConnectTimeout(connectTimeoutMillis); httpConn.setReadTimeout(readTimeoutMillis); try { httpConn.connect(); if (null != request.getPayload() && request.getPayload().length > 0) { out = httpConn.getOutputStream(); out.write(request.getPayload()); } content = httpConn.getInputStream(); response = new HttpResponse(); parseHttpConn(response, httpConn, content); return response; } catch (SocketTimeoutException e) { throw e; } catch (IOException e) { content = httpConn.getErrorStream(); response = new HttpResponse(); parseHttpConn(response, httpConn, content); return response; } finally { if (content != null) { content.close(); } httpConn.disconnect(); } }
java
{ "resource": "" }
q8231
Config.refreshCredentials
train
public void refreshCredentials() { if (this.credsProvider == null) return; try { AlibabaCloudCredentials creds = this.credsProvider.getCredentials(); this.accessKeyID = creds.getAccessKeyId(); this.accessKeySecret = creds.getAccessKeySecret(); if (creds instanceof BasicSessionCredentials) { this.securityToken = ((BasicSessionCredentials) creds).getSessionToken(); } } catch (Exception e) { e.printStackTrace(); } }
java
{ "resource": "" }
q8232
History.addExtraInfo
train
public void addExtraInfo(String key, Object value) { // Turn extraInfo into map Map<String, Object> infoMap = (HashMap<String, Object>)getMapFromJSON(extraInfo); // Add value infoMap.put(key, value); // Turn back into string extraInfo = getJSONFromMap(infoMap); }
java
{ "resource": "" }
q8233
History.getMapFromJSON
train
private Map<String, Object> getMapFromJSON(String json) { Map<String, Object> propMap = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); // Initialize string if empty if (json == null || json.length() == 0) { json = "{}"; } try { // Convert string propMap = mapper.readValue(json, new TypeReference<HashMap<String, Object>>(){}); } catch (Exception e) { ; } return propMap; }
java
{ "resource": "" }
q8234
History.getJSONFromMap
train
private String getJSONFromMap(Map<String, Object> propMap) { try { return new JSONObject(propMap).toString(); } catch (Exception e) { return "{}"; } }
java
{ "resource": "" }
q8235
ConfigurationInterceptor.preHandle
train
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String queryString = request.getQueryString() == null ? "" : request.getQueryString(); if (ConfigurationService.getInstance().isValid() || request.getServletPath().startsWith("/configuration") || request.getServletPath().startsWith("/resources") || queryString.contains("requestFromConfiguration=true")) { return true; } else { response.sendRedirect("configuration"); return false; } }
java
{ "resource": "" }
q8236
ServerMappingController.addRedirectToProfile
train
@RequestMapping(value = "api/edit/server", method = RequestMethod.POST) public @ResponseBody ServerRedirect addRedirectToProfile(Model model, @RequestParam(value = "profileId", required = false) Integer profileId, @RequestParam(value = "profileIdentifier", required = false) String profileIdentifier, @RequestParam(value = "srcUrl", required = true) String srcUrl, @RequestParam(value = "destUrl", required = true) String destUrl, @RequestParam(value = "clientUUID", required = true) String clientUUID, @RequestParam(value = "hostHeader", required = false) String hostHeader) throws Exception { if (profileId == null && profileIdentifier == null) { throw new Exception("profileId required"); } if (profileId == null) { profileId = ProfileService.getInstance().getIdFromName(profileIdentifier); } int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId(); int redirectId = ServerRedirectService.getInstance().addServerRedirectToProfile("", srcUrl, destUrl, hostHeader, profileId, clientId); return ServerRedirectService.getInstance().getRedirect(redirectId); }
java
{ "resource": "" }
q8237
ServerMappingController.getjqRedirects
train
@RequestMapping(value = "api/edit/server", method = RequestMethod.GET) public @ResponseBody HashMap<String, Object> getjqRedirects(Model model, @RequestParam(value = "profileId", required = false) Integer profileId, @RequestParam(value = "clientUUID", required = true) String clientUUID, @RequestParam(value = "profileIdentifier", required = false) String profileIdentifier) throws Exception { if (profileId == null && profileIdentifier == null) { throw new Exception("profileId required"); } if (profileId == null) { profileId = ProfileService.getInstance().getIdFromName(profileIdentifier); } int clientId = ClientService.getInstance().findClient(clientUUID, profileId).getId(); HashMap<String, Object> returnJson = Utils.getJQGridJSON(ServerRedirectService.getInstance().tableServers(clientId), "servers"); returnJson.put("hostEditor", Client.isAvailable()); return returnJson; }
java
{ "resource": "" }
q8238
ServerMappingController.getServerGroups
train
@RequestMapping(value = "api/servergroup", method = RequestMethod.GET) public @ResponseBody HashMap<String, Object> getServerGroups(Model model, @RequestParam(value = "profileId", required = false) Integer profileId, @RequestParam(value = "search", required = false) String search, @RequestParam(value = "profileIdentifier", required = false) String profileIdentifier) throws Exception { if (profileId == null && profileIdentifier == null) { throw new Exception("profileId required"); } if (profileId == null) { profileId = ProfileService.getInstance().getIdFromName(profileIdentifier); } List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId); if (search != null) { Iterator<ServerGroup> iterator = serverGroups.iterator(); while (iterator.hasNext()) { ServerGroup serverGroup = iterator.next(); if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) { iterator.remove(); } } } HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, "servergroups"); return returnJson; }
java
{ "resource": "" }
q8239
ServerMappingController.createServerGroup
train
@RequestMapping(value = "api/servergroup", method = RequestMethod.POST) public @ResponseBody ServerGroup createServerGroup(Model model, @RequestParam(value = "name") String name, @RequestParam(value = "profileId", required = false) Integer profileId, @RequestParam(value = "profileIdentifier", required = false) String profileIdentifier) throws Exception { if (profileId == null && profileIdentifier == null) { throw new Exception("profileId required"); } if (profileId == null) { profileId = ProfileService.getInstance().getIdFromName(profileIdentifier); } int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId); return ServerRedirectService.getInstance().getServerGroup(groupId, profileId); }
java
{ "resource": "" }
q8240
ServerMappingController.certPage
train
@RequestMapping(value = "/cert", method = {RequestMethod.GET, RequestMethod.HEAD}) public String certPage() throws Exception { return "cert"; }
java
{ "resource": "" }
q8241
HttpUtilities.mapUrlEncodedParameters
train
public static Map<String, String[]> mapUrlEncodedParameters(byte[] dataArray) throws Exception { Map<String, String[]> mapPostParameters = new HashMap<String, String[]>(); try { ByteArrayOutputStream byteout = new ByteArrayOutputStream(); for (int x = 0; x < dataArray.length; x++) { // split the data up by & to get the parts if (dataArray[x] == '&' || x == (dataArray.length - 1)) { if (x == (dataArray.length - 1)) { byteout.write(dataArray[x]); } // find '=' and split the data up into key value pairs int equalsPos = -1; ByteArrayOutputStream key = new ByteArrayOutputStream(); ByteArrayOutputStream value = new ByteArrayOutputStream(); byte[] byteArray = byteout.toByteArray(); for (int xx = 0; xx < byteArray.length; xx++) { if (byteArray[xx] == '=') { equalsPos = xx; } else { if (equalsPos == -1) { key.write(byteArray[xx]); } else { value.write(byteArray[xx]); } } } ArrayList<String> values = new ArrayList<String>(); if (mapPostParameters.containsKey(key.toString())) { values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(key.toString()))); mapPostParameters.remove(key.toString()); } values.add(value.toString()); /** * If equalsPos is not -1, then there was a '=' for the key * If value.size is 0, then there is no value so want to add in the '=' * Since it will not be added later like params with keys and valued */ if (equalsPos != -1 && value.size() == 0) { key.write((byte) '='); } mapPostParameters.put(key.toString(), values.toArray(new String[values.size()])); byteout = new ByteArrayOutputStream(); } else { byteout.write(dataArray[x]); } } } catch (Exception e) { throw new Exception("Could not parse request data: " + e.getMessage()); } return mapPostParameters; }
java
{ "resource": "" }
q8242
HttpUtilities.getURL
train
public static String getURL(String sourceURI) { String retval = sourceURI; int qPos = sourceURI.indexOf("?"); if (qPos != -1) { retval = retval.substring(0, qPos); } return retval; }
java
{ "resource": "" }
q8243
HttpUtilities.getHeaders
train
public static String getHeaders(HttpMethod method) { String headerString = ""; Header[] headers = method.getRequestHeaders(); for (Header header : headers) { String name = header.getName(); if (name.equals(Constants.ODO_PROXY_HEADER)) { // skip.. don't want to log this continue; } if (headerString.length() != 0) { headerString += "\n"; } headerString += header.getName() + ": " + header.getValue(); } return headerString; }
java
{ "resource": "" }
q8244
HttpUtilities.getHeaders
train
public static String getHeaders(HttpServletRequest request) { String headerString = ""; Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); if (name.equals(Constants.ODO_PROXY_HEADER)) { // skip.. don't want to log this continue; } if (headerString.length() != 0) { headerString += "\n"; } headerString += name + ": " + request.getHeader(name); } return headerString; }
java
{ "resource": "" }
q8245
HttpUtilities.getHeaders
train
public static String getHeaders(HttpServletResponse response) { String headerString = ""; Collection<String> headerNames = response.getHeaderNames(); for (String headerName : headerNames) { // there may be multiple headers per header name for (String headerValue : response.getHeaders(headerName)) { if (headerString.length() != 0) { headerString += "\n"; } headerString += headerName + ": " + headerValue; } } return headerString; }
java
{ "resource": "" }
q8246
HttpUtilities.getParameters
train
public static HashMap<String, String> getParameters(String query) { HashMap<String, String> params = new HashMap<String, String>(); if (query == null || query.length() == 0) { return params; } String[] splitQuery = query.split("&"); for (String splitItem : splitQuery) { String[] items = splitItem.split("="); if (items.length == 1) { params.put(items[0], ""); } else { params.put(items[0], items[1]); } } return params; }
java
{ "resource": "" }
q8247
EditService.getMethodsFromGroupIds
train
public List<Method> getMethodsFromGroupIds(int[] groupIds, String[] filters) throws Exception { ArrayList<Method> methods = new ArrayList<Method>(); for (int groupId : groupIds) { methods.addAll(getMethodsFromGroupId(groupId, filters)); } return methods; }
java
{ "resource": "" }
q8248
EditService.updateRepeatNumber
train
public void updateRepeatNumber(int newNum, int path_id, String client_uuid) throws Exception { updateRequestResponseTables("repeat_number", newNum, getProfileIdFromPathID(path_id), client_uuid, path_id); }
java
{ "resource": "" }
q8249
EditService.disableAll
train
public void disableAll(int profileId, String client_uuid) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants.CLIENT_PROFILE_ID + " = ?" + " AND " + Constants.CLIENT_CLIENT_UUID + " =? " ); statement.setInt(1, profileId); statement.setString(2, client_uuid); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8250
EditService.removePathnameFromProfile
train
public void removePathnameFromProfile(int path_id, int profileId) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants.ENABLED_OVERRIDES_PATH_ID + " = ?" ); statement.setInt(1, path_id); statement.executeUpdate(); statement.close(); statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setInt(1, path_id); statement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8251
EditService.getMethodsFromGroupId
train
public List<Method> getMethodsFromGroupId(int groupId, String[] filters) throws Exception { ArrayList<Method> methods = new ArrayList<Method>(); PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "SELECT * FROM " + Constants.DB_TABLE_OVERRIDE + " WHERE " + Constants.OVERRIDE_GROUP_ID + " = ?" ); statement.setInt(1, groupId); results = statement.executeQuery(); while (results.next()) { Method method = PathOverrideService.getInstance().getMethodForOverrideId(results.getInt("id")); if (method == null) { continue; } // decide whether or not to add this method based on the filters boolean add = true; if (filters != null) { add = false; for (String filter : filters) { if (method.getMethodType().endsWith(filter)) { add = true; break; } } } if (add && !methods.contains(method)) { methods.add(method); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } return methods; }
java
{ "resource": "" }
q8252
EditService.enableCustomResponse
train
public void enableCustomResponse(String custom, int path_id, String client_uuid) throws Exception { updateRequestResponseTables("custom_response", custom, getProfileIdFromPathID(path_id), client_uuid, path_id); }
java
{ "resource": "" }
q8253
EditService.updatePathTable
train
public static void updatePathTable(String columnName, Object newData, int path_id) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + columnName + " = ?" + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setObject(1, newData); statement.setInt(2, path_id); statement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8254
EditService.removeCustomOverride
train
public void removeCustomOverride(int path_id, String client_uuid) throws Exception { updateRequestResponseTables("custom_response", "", getProfileIdFromPathID(path_id), client_uuid, path_id); }
java
{ "resource": "" }
q8255
EditService.getProfileIdFromPathID
train
public static int getProfileIdFromPathID(int path_id) throws Exception { return (Integer) SQLService.getInstance().getFromTable(Constants.GENERIC_PROFILE_ID, Constants.GENERIC_ID, path_id, Constants.DB_TABLE_PATH); }
java
{ "resource": "" }
q8256
PathOverrideService.findAllGroups
train
public List<Group> findAllGroups() { ArrayList<Group> allGroups = new ArrayList<Group>(); PreparedStatement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_GROUPS + " ORDER BY " + Constants.GROUPS_GROUP_NAME); results = queryStatement.executeQuery(); while (results.next()) { Group group = new Group(); group.setId(results.getInt(Constants.GENERIC_ID)); group.setName(results.getString(Constants.GROUPS_GROUP_NAME)); allGroups.add(group); } } 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 allGroups; }
java
{ "resource": "" }
q8257
PathOverrideService.addPathnameToProfile
train
public int addPathnameToProfile(int id, String pathname, String actualPath) throws Exception { int pathOrder = getPathOrder(id).size() + 1; int pathId = -1; PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_PATH + "(" + Constants.PATH_PROFILE_PATHNAME + "," + Constants.PATH_PROFILE_ACTUAL_PATH + "," + Constants.PATH_PROFILE_GROUP_IDS + "," + Constants.PATH_PROFILE_PROFILE_ID + "," + Constants.PATH_PROFILE_PATH_ORDER + "," + Constants.PATH_PROFILE_CONTENT_TYPE + "," + Constants.PATH_PROFILE_REQUEST_TYPE + "," + Constants.PATH_PROFILE_GLOBAL + ")" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?);", PreparedStatement.RETURN_GENERATED_KEYS ); statement.setString(1, pathname); statement.setString(2, actualPath); statement.setString(3, ""); statement.setInt(4, id); statement.setInt(5, pathOrder); statement.setString(6, Constants.PATH_PROFILE_DEFAULT_CONTENT_TYPE); // should be set by UI/API statement.setInt(7, Constants.REQUEST_TYPE_GET); // should be set by UI/API statement.setBoolean(8, false); statement.executeUpdate(); // execute statement and get resultSet which will have the generated path ID as the first field results = statement.getGeneratedKeys(); if (results.next()) { pathId = results.getInt(1); } else { // something went wrong throw new Exception("Could not add path"); } } catch (SQLException e) { throw e; } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } // need to add to request response table for all clients for (Client client : ClientService.getInstance().findAllClients(id)) { this.addPathToRequestResponseTable(id, client.getUUID(), pathId); } return pathId; }
java
{ "resource": "" }
q8258
PathOverrideService.addPathToRequestResponseTable
train
public void addPathToRequestResponseTable(int profileId, String clientUUID, int pathId) throws Exception { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection .prepareStatement("INSERT INTO " + Constants.DB_TABLE_REQUEST_RESPONSE + "(" + Constants.REQUEST_RESPONSE_PATH_ID + "," + Constants.GENERIC_PROFILE_ID + "," + Constants.GENERIC_CLIENT_UUID + "," + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + "," + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + "," + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + "," + Constants.REQUEST_RESPONSE_CUSTOM_RESPONSE + "," + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + ")" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?);"); statement.setInt(1, pathId); statement.setInt(2, profileId); statement.setString(3, clientUUID); statement.setInt(4, -1); statement.setInt(5, 0); statement.setInt(6, 0); statement.setString(7, ""); statement.setString(8, ""); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8259
PathOverrideService.getPathOrder
train
public List<Integer> getPathOrder(int profileId) { ArrayList<Integer> pathOrder = new ArrayList<Integer>(); PreparedStatement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "SELECT * FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.GENERIC_PROFILE_ID + " = ? " + " ORDER BY " + Constants.PATH_PROFILE_PATH_ORDER + " ASC" ); queryStatement.setInt(1, profileId); results = queryStatement.executeQuery(); while (results.next()) { pathOrder.add(results.getInt(Constants.GENERIC_ID)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } logger.info("pathOrder = {}", pathOrder); return pathOrder; }
java
{ "resource": "" }
q8260
PathOverrideService.setGroupsForPath
train
public void setGroupsForPath(Integer[] groups, int pathId) { String newGroups = Arrays.toString(groups); newGroups = newGroups.substring(1, newGroups.length() - 1).replaceAll("\\s", ""); logger.info("adding groups={}, to pathId={}", newGroups, pathId); EditService.updatePathTable(Constants.PATH_PROFILE_GROUP_IDS, newGroups, pathId); }
java
{ "resource": "" }
q8261
PathOverrideService.intArrayContains
train
public static boolean intArrayContains(int[] array, int numToCheck) { for (int i = 0; i < array.length; i++) { if (array[i] == numToCheck) { return true; } } return false; }
java
{ "resource": "" }
q8262
PathOverrideService.getGroupIdFromName
train
public Integer getGroupIdFromName(String groupName) { return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName, Constants.DB_TABLE_GROUPS); }
java
{ "resource": "" }
q8263
PathOverrideService.createOverride
train
public void createOverride(int groupId, String methodName, String className) throws Exception { // first make sure this doesn't already exist for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) { if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) { // don't add if it already exists in the group return; } } try (Connection sqlConnection = sqlService.getConnection()) { PreparedStatement statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_OVERRIDE + "(" + Constants.OVERRIDE_METHOD_NAME + "," + Constants.OVERRIDE_CLASS_NAME + "," + Constants.OVERRIDE_GROUP_ID + ")" + " VALUES (?, ?, ?)" ); statement.setString(1, methodName); statement.setString(2, className); statement.setInt(3, groupId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } }
java
{ "resource": "" }
q8264
PathOverrideService.getGroupNameFromId
train
public String getGroupNameFromId(int groupId) { return (String) sqlService.getFromTable(Constants.GROUPS_GROUP_NAME, Constants.GENERIC_ID, groupId, Constants.DB_TABLE_GROUPS); }
java
{ "resource": "" }
q8265
PathOverrideService.updateGroupName
train
public void updateGroupName(String newGroupName, int id) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_GROUPS + " SET " + Constants.GROUPS_GROUP_NAME + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, newGroupName); statement.setInt(2, id); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8266
PathOverrideService.removeGroup
train
public void removeGroup(int groupId) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_GROUPS + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setInt(1, groupId); statement.executeUpdate(); statement.close(); statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_OVERRIDE + " WHERE " + Constants.OVERRIDE_GROUP_ID + " = ?" ); statement.setInt(1, groupId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } removeGroupIdFromTablePaths(groupId); }
java
{ "resource": "" }
q8267
PathOverrideService.removeGroupIdFromTablePaths
train
private void removeGroupIdFromTablePaths(int groupIdToRemove) { PreparedStatement queryStatement = null; PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_PATH); results = queryStatement.executeQuery(); // this is a hashamp from a pathId to the string of groups HashMap<Integer, String> idToGroups = new HashMap<Integer, String>(); while (results.next()) { int pathId = results.getInt(Constants.GENERIC_ID); String stringGroupIds = results.getString(Constants.PATH_PROFILE_GROUP_IDS); int[] groupIds = Utils.arrayFromStringOfIntegers(stringGroupIds); String newGroupIds = ""; for (int i = 0; i < groupIds.length; i++) { if (groupIds[i] != groupIdToRemove) { newGroupIds += (groupIds[i] + ","); } } idToGroups.put(pathId, newGroupIds); } // now i want to go though the hashmap and for each pathId, add // update the newGroupIds for (Map.Entry<Integer, String> entry : idToGroups.entrySet()) { Integer pathId = entry.getKey(); String newGroupIds = entry.getValue(); statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_GROUP_IDS + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, newGroupIds); statement.setInt(2, pathId); statement.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8268
PathOverrideService.removePath
train
public void removePath(int pathId) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { // remove any enabled overrides with this path statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants.ENABLED_OVERRIDES_PATH_ID + " = ?" ); statement.setInt(1, pathId); statement.executeUpdate(); statement.close(); // remove path statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setInt(1, pathId); statement.executeUpdate(); statement.close(); //remove path from responseRequest statement = sqlConnection.prepareStatement( "DELETE FROM " + Constants.DB_TABLE_REQUEST_RESPONSE + " WHERE " + Constants.REQUEST_RESPONSE_PATH_ID + " = ?" ); statement.setInt(1, pathId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8269
PathOverrideService.getMethodForOverrideId
train
public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) { com.groupon.odo.proxylib.models.Method method = null; // special case for IDs < 0 if (overrideId < 0) { method = new com.groupon.odo.proxylib.models.Method(); method.setId(overrideId); if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM || method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD || method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) { method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE); } else { method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE); } } else { // get method information from the database PreparedStatement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "SELECT * FROM " + Constants.DB_TABLE_OVERRIDE + " WHERE " + Constants.GENERIC_ID + " = ?" ); queryStatement.setInt(1, overrideId); results = queryStatement.executeQuery(); if (results.next()) { method = new com.groupon.odo.proxylib.models.Method(); method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME)); method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME)); } } catch (SQLException e) { e.printStackTrace(); return null; } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } // if method is still null then just return if (method == null) { return method; } // now get the rest of the data from the plugin manager // this gets all of the actual method data try { method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName()); method.setId(overrideId); } catch (Exception e) { // there was some problem.. return null return null; } } return method; }
java
{ "resource": "" }
q8270
PathOverrideService.updatePathOrder
train
public void updatePathOrder(int profileId, int[] pathOrder) { for (int i = 0; i < pathOrder.length; i++) { EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]); } }
java
{ "resource": "" }
q8271
PathOverrideService.getPathId
train
public int getPathId(String pathName, int profileId) { PreparedStatement queryStatement = null; ResultSet results = null; // first get the pathId for the pathName/profileId int pathId = -1; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "SELECT " + Constants.GENERIC_ID + " FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.PATH_PROFILE_PATHNAME + "= ? " + " AND " + Constants.GENERIC_PROFILE_ID + "= ?" ); queryStatement.setString(1, pathName); queryStatement.setInt(2, profileId); results = queryStatement.executeQuery(); if (results.next()) { pathId = results.getInt(Constants.GENERIC_ID); } } 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 pathId; }
java
{ "resource": "" }
q8272
PathOverrideService.getPathSelectString
train
private String getPathSelectString() { String queryString = "SELECT " + Constants.DB_TABLE_REQUEST_RESPONSE + "." + Constants.GENERIC_CLIENT_UUID + "," + Constants.DB_TABLE_PATH + "." + Constants.GENERIC_ID + "," + Constants.PATH_PROFILE_PATHNAME + "," + Constants.PATH_PROFILE_ACTUAL_PATH + "," + Constants.PATH_PROFILE_BODY_FILTER + "," + Constants.PATH_PROFILE_GROUP_IDS + "," + Constants.DB_TABLE_PATH + "." + Constants.PATH_PROFILE_PROFILE_ID + "," + Constants.PATH_PROFILE_PATH_ORDER + "," + Constants.REQUEST_RESPONSE_REPEAT_NUMBER + "," + Constants.REQUEST_RESPONSE_REQUEST_ENABLED + "," + Constants.REQUEST_RESPONSE_RESPONSE_ENABLED + "," + Constants.PATH_PROFILE_CONTENT_TYPE + "," + Constants.PATH_PROFILE_REQUEST_TYPE + "," + Constants.PATH_PROFILE_GLOBAL + " FROM " + Constants.DB_TABLE_PATH + " JOIN " + Constants.DB_TABLE_REQUEST_RESPONSE + " ON " + Constants.DB_TABLE_PATH + "." + Constants.GENERIC_ID + "=" + Constants.DB_TABLE_REQUEST_RESPONSE + "." + Constants.REQUEST_RESPONSE_PATH_ID + " AND " + Constants.DB_TABLE_REQUEST_RESPONSE + "." + Constants.GENERIC_CLIENT_UUID + " = ?"; return queryString; }
java
{ "resource": "" }
q8273
PathOverrideService.getEndpointOverrideFromResultSet
train
private EndpointOverride getEndpointOverrideFromResultSet(ResultSet results) throws Exception { EndpointOverride endpoint = new EndpointOverride(); endpoint.setPathId(results.getInt(Constants.GENERIC_ID)); endpoint.setPath(results.getString(Constants.PATH_PROFILE_ACTUAL_PATH)); endpoint.setBodyFilter(results.getString(Constants.PATH_PROFILE_BODY_FILTER)); endpoint.setPathName(results.getString(Constants.PATH_PROFILE_PATHNAME)); endpoint.setContentType(results.getString(Constants.PATH_PROFILE_CONTENT_TYPE)); endpoint.setRequestType(results.getInt(Constants.PATH_PROFILE_REQUEST_TYPE)); endpoint.setRepeatNumber(results.getInt(Constants.REQUEST_RESPONSE_REPEAT_NUMBER)); endpoint.setGroupIds(results.getString(Constants.PATH_PROFILE_GROUP_IDS)); endpoint.setRequestEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_REQUEST_ENABLED)); endpoint.setResponseEnabled(results.getBoolean(Constants.REQUEST_RESPONSE_RESPONSE_ENABLED)); endpoint.setClientUUID(results.getString(Constants.GENERIC_CLIENT_UUID)); endpoint.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID)); endpoint.setGlobal(results.getBoolean(Constants.PATH_PROFILE_GLOBAL)); return endpoint; }
java
{ "resource": "" }
q8274
PathOverrideService.getPath
train
public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception { EndpointOverride endpoint = null; PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { String queryString = this.getPathSelectString(); queryString += " AND " + Constants.DB_TABLE_PATH + "." + Constants.GENERIC_ID + "=" + pathId + ";"; statement = sqlConnection.prepareStatement(queryString); statement.setString(1, clientUUID); results = statement.executeQuery(); if (results.next()) { endpoint = this.getEndpointOverrideFromResultSet(results); endpoint.setFilters(filters); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } return endpoint; }
java
{ "resource": "" }
q8275
PathOverrideService.setName
train
public void setName(int pathId, String pathName) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_PATHNAME + " = ?" + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, pathName); statement.setInt(2, pathId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8276
PathOverrideService.setPath
train
public void setPath(int pathId, String path) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_ACTUAL_PATH + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, path); statement.setInt(2, pathId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8277
PathOverrideService.setBodyFilter
train
public void setBodyFilter(int pathId, String bodyFilter) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_BODY_FILTER + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, bodyFilter); statement.setInt(2, pathId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8278
PathOverrideService.setContentType
train
public void setContentType(int pathId, String contentType) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_CONTENT_TYPE + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setString(1, contentType); statement.setInt(2, pathId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8279
PathOverrideService.setRequestType
train
public void setRequestType(int pathId, Integer requestType) { if (requestType == null) { requestType = Constants.REQUEST_TYPE_GET; } PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_REQUEST_TYPE + " = ?" + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setInt(1, requestType); statement.setInt(2, pathId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8280
PathOverrideService.setGlobal
train
public void setGlobal(int pathId, Boolean global) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_PATH + " SET " + Constants.PATH_PROFILE_GLOBAL + " = ? " + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setBoolean(1, global); statement.setInt(2, pathId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8281
PathOverrideService.getPaths
train
public List<EndpointOverride> getPaths(int profileId, String clientUUID, String[] filters) throws Exception { ArrayList<EndpointOverride> properties = new ArrayList<EndpointOverride>(); PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { String queryString = this.getPathSelectString(); queryString += " AND " + Constants.DB_TABLE_PATH + "." + Constants.GENERIC_PROFILE_ID + "=? " + " ORDER BY " + Constants.PATH_PROFILE_PATH_ORDER + " ASC"; statement = sqlConnection.prepareStatement(queryString); statement.setString(1, clientUUID); statement.setInt(2, profileId); results = statement.executeQuery(); while (results.next()) { EndpointOverride endpoint = this.getEndpointOverrideFromResultSet(results); endpoint.setFilters(filters); properties.add(endpoint); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } return properties; }
java
{ "resource": "" }
q8282
PathOverrideService.setCustomRequest
train
public void setCustomRequest(int pathId, String customRequest, String clientUUID) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { int profileId = EditService.getProfileIdFromPathID(pathId); statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE + " SET " + Constants.REQUEST_RESPONSE_CUSTOM_REQUEST + "= ?" + " WHERE " + Constants.GENERIC_PROFILE_ID + "= ?" + " AND " + Constants.GENERIC_CLIENT_UUID + "= ?" + " AND " + Constants.REQUEST_RESPONSE_PATH_ID + "= ?" ); statement.setString(1, customRequest); statement.setInt(2, profileId); statement.setString(3, clientUUID); statement.setInt(4, pathId); statement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8283
PathOverrideService.clearResponseSettings
train
public void clearResponseSettings(int pathId, String clientUUID) throws Exception { logger.info("clearing response settings"); this.setResponseEnabled(pathId, false, clientUUID); OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_RESPONSE); EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_RESPONSE, pathId, clientUUID); }
java
{ "resource": "" }
q8284
PathOverrideService.clearRequestSettings
train
public void clearRequestSettings(int pathId, String clientUUID) throws Exception { this.setRequestEnabled(pathId, false, clientUUID); OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_REQUEST); EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_REQUEST, pathId, clientUUID); }
java
{ "resource": "" }
q8285
PathOverrideService.getSelectedPaths
train
public List<EndpointOverride> getSelectedPaths(int overrideType, Client client, Profile profile, String uri, Integer requestType, boolean pathTest) throws Exception { List<EndpointOverride> selectPaths = new ArrayList<EndpointOverride>(); // get the paths for the current active client profile // this returns paths in priority order List<EndpointOverride> paths = new ArrayList<EndpointOverride>(); if (client.getIsActive()) { paths = getPaths( profile.getId(), client.getUUID(), null); } boolean foundRealPath = false; logger.info("Checking uri: {}", uri); // it should now be ordered by priority, i updated tableOverrides to // return the paths in priority order for (EndpointOverride path : paths) { // first see if the request types match.. // and if the path request type is not ALL // if they do not then skip this path // If requestType is -1 we evaluate all(probably called by the path tester) if (requestType != -1 && path.getRequestType() != requestType && path.getRequestType() != Constants.REQUEST_TYPE_ALL) { continue; } // first see if we get a match try { Pattern pattern = Pattern.compile(path.getPath()); Matcher matcher = pattern.matcher(uri); // we won't select the path if there aren't any enabled endpoints in it // this works since the paths are returned in priority order if (matcher.find()) { // now see if this path has anything enabled in it // Only go into the if: // 1. There are enabled items in this path // 2. Caller was looking for ResponseOverride and Response is enabled OR looking for RequestOverride // 3. If pathTest is true then the rest of the conditions are not evaluated. The path tester ignores enabled states so everything is returned. // and request is enabled if (pathTest || (path.getEnabledEndpoints().size() > 0 && ((overrideType == Constants.OVERRIDE_TYPE_RESPONSE && path.getResponseEnabled()) || (overrideType == Constants.OVERRIDE_TYPE_REQUEST && path.getRequestEnabled())))) { // if we haven't already seen a non global path // or if this is a global path // then add it to the list if (!foundRealPath || path.getGlobal()) { selectPaths.add(path); } } // we set this no matter what if a path matched and it was not the global path // this stops us from adding further non global matches to the list if (!path.getGlobal()) { foundRealPath = true; } } } catch (PatternSyntaxException pse) { // nothing to do but keep iterating over the list // this indicates an invalid regex } } return selectPaths; }
java
{ "resource": "" }
q8286
ProfileService.isActive
train
public boolean isActive(int profileId) { boolean active = false; PreparedStatement queryStatement = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "SELECT " + Constants.CLIENT_IS_ACTIVE + " FROM " + Constants.DB_TABLE_CLIENT + " WHERE " + Constants.GENERIC_CLIENT_UUID + "= '-1' " + " AND " + Constants.GENERIC_PROFILE_ID + "= ? " ); queryStatement.setInt(1, profileId); logger.info(queryStatement.toString()); ResultSet results = queryStatement.executeQuery(); if (results.next()) { active = results.getBoolean(Constants.CLIENT_IS_ACTIVE); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } return active; }
java
{ "resource": "" }
q8287
ProfileService.findAllProfiles
train
public List<Profile> findAllProfiles() throws Exception { ArrayList<Profile> allProfiles = new ArrayList<>(); PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_PROFILE); results = statement.executeQuery(); while (results.next()) { allProfiles.add(this.getProfileFromResultSet(results)); } } catch (Exception e) { throw e; } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } return allProfiles; }
java
{ "resource": "" }
q8288
ProfileService.findProfile
train
public Profile findProfile(int profileId) throws Exception { Profile profile = null; PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "SELECT * FROM " + Constants.DB_TABLE_PROFILE + " WHERE " + Constants.GENERIC_ID + " = ?" ); statement.setInt(1, profileId); results = statement.executeQuery(); if (results.next()) { profile = this.getProfileFromResultSet(results); } } catch (Exception e) { throw e; } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } return profile; }
java
{ "resource": "" }
q8289
ProfileService.getProfileFromResultSet
train
private Profile getProfileFromResultSet(ResultSet result) throws Exception { Profile profile = new Profile(); profile.setId(result.getInt(Constants.GENERIC_ID)); Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME); String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length()); profile.setName(profileName); return profile; }
java
{ "resource": "" }
q8290
ProfileService.add
train
public Profile add(String profileName) throws Exception { Profile profile = new Profile(); int id = -1; PreparedStatement statement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { Clob clobProfileName = sqlService.toClob(profileName, sqlConnection); statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_PROFILE + "(" + Constants.PROFILE_PROFILE_NAME + ") " + " VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS ); statement.setClob(1, clobProfileName); statement.executeUpdate(); results = statement.getGeneratedKeys(); if (results.next()) { id = results.getInt(1); } else { // something went wrong throw new Exception("Could not add client"); } results.close(); statement.close(); statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_CLIENT + "(" + Constants.CLIENT_CLIENT_UUID + "," + Constants.CLIENT_IS_ACTIVE + "," + Constants.CLIENT_PROFILE_ID + ") " + " VALUES (?, ?, ?)"); statement.setString(1, Constants.PROFILE_CLIENT_DEFAULT_ID); statement.setBoolean(2, false); statement.setInt(3, id); statement.executeUpdate(); profile.setName(profileName); profile.setId(id); } catch (SQLException e) { throw e; } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (statement != null) { statement.close(); } } catch (Exception e) { } } return profile; }
java
{ "resource": "" }
q8291
ProfileService.remove
train
public void remove(int profileId) { PreparedStatement statement = null; try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement("DELETE FROM " + Constants.DB_TABLE_PROFILE + " WHERE " + Constants.GENERIC_ID + " = ?"); statement.setInt(1, profileId); statement.executeUpdate(); statement.close(); //also want to delete what is in the server redirect table statement = sqlConnection.prepareStatement("DELETE FROM " + Constants.DB_TABLE_SERVERS + " WHERE " + Constants.GENERIC_PROFILE_ID + " = ?"); statement.setInt(1, profileId); statement.executeUpdate(); statement.close(); //also want to delete the path_profile table statement = sqlConnection.prepareStatement("DELETE FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.GENERIC_PROFILE_ID + " = ?"); statement.setInt(1, profileId); statement.executeUpdate(); statement.close(); //and the enabled overrides table statement = sqlConnection.prepareStatement("DELETE FROM " + Constants.DB_TABLE_ENABLED_OVERRIDE + " WHERE " + Constants.GENERIC_PROFILE_ID + " = ?"); statement.setInt(1, profileId); statement.executeUpdate(); statement.close(); //and delete all the clients associated with this profile including the default client statement = sqlConnection.prepareStatement("DELETE FROM " + Constants.DB_TABLE_CLIENT + " WHERE " + Constants.GENERIC_PROFILE_ID + " = ?"); statement.setInt(1, profileId); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
{ "resource": "" }
q8292
ProfileService.getNamefromId
train
public String getNamefromId(int id) { return (String) sqlService.getFromTable( Constants.PROFILE_PROFILE_NAME, Constants.GENERIC_ID, id, Constants.DB_TABLE_PROFILE); }
java
{ "resource": "" }
q8293
ProfileService.getIdFromName
train
public Integer getIdFromName(String profileName) { PreparedStatement query = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { query = sqlConnection.prepareStatement("SELECT * FROM " + Constants.DB_TABLE_PROFILE + " WHERE " + Constants.PROFILE_PROFILE_NAME + " = ?"); query.setString(1, profileName); results = query.executeQuery(); if (results.next()) { Object toReturn = results.getObject(Constants.GENERIC_ID); query.close(); return (Integer) toReturn; } query.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (query != null) { query.close(); } } catch (Exception e) { } } return null; }
java
{ "resource": "" }
q8294
ControllerUtils.convertPathIdentifier
train
public static Integer convertPathIdentifier(String identifier, Integer profileId) throws Exception { Integer pathId = -1; try { pathId = Integer.parseInt(identifier); } catch (NumberFormatException ne) { // this is OK.. just means it's not a # if (profileId == null) throw new Exception("A profileId must be specified"); pathId = PathOverrideService.getInstance().getPathId(identifier, profileId); } return pathId; }
java
{ "resource": "" }
q8295
ControllerUtils.convertProfileIdentifier
train
public static Integer convertProfileIdentifier(String profileIdentifier) throws Exception { Integer profileId = -1; if (profileIdentifier == null) { throw new Exception("A profileIdentifier must be specified"); } else { try { profileId = Integer.parseInt(profileIdentifier); } catch (NumberFormatException ne) { // this is OK.. just means it's not a # // try to get it by name instead profileId = ProfileService.getInstance().getIdFromName(profileIdentifier); } } logger.info("Profile id is {}", profileId); return profileId; }
java
{ "resource": "" }
q8296
ControllerUtils.convertOverrideIdentifier
train
public static Integer convertOverrideIdentifier(String overrideIdentifier) throws Exception { Integer overrideId = -1; try { // there is an issue with parseInt where it does not parse negative values correctly boolean isNegative = false; if (overrideIdentifier.startsWith("-")) { isNegative = true; overrideIdentifier = overrideIdentifier.substring(1); } overrideId = Integer.parseInt(overrideIdentifier); if (isNegative) { overrideId = 0 - overrideId; } } catch (NumberFormatException ne) { // this is OK.. just means it's not a # // split into two parts String className = null; String methodName = null; int lastDot = overrideIdentifier.lastIndexOf("."); className = overrideIdentifier.substring(0, lastDot); methodName = overrideIdentifier.substring(lastDot + 1); overrideId = OverrideService.getInstance().getOverrideIdForMethod(className, methodName); } return overrideId; }
java
{ "resource": "" }
q8297
ControllerUtils.convertProfileAndPathIdentifier
train
public static Identifiers convertProfileAndPathIdentifier(String profileIdentifier, String pathIdentifier) throws Exception { Identifiers id = new Identifiers(); Integer profileId = null; try { profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier); } catch (Exception e) { // this is OK for this since it isn't always needed } Integer pathId = convertPathIdentifier(pathIdentifier, profileId); id.setProfileId(profileId); id.setPathId(pathId); return id; }
java
{ "resource": "" }
q8298
PathValueClient.getPathFromEndpoint
train
public JSONObject getPathFromEndpoint(String pathValue, String requestType) throws Exception { int type = getRequestTypeFromString(requestType); String url = BASE_PATH; JSONObject response = new JSONObject(doGet(url, null)); JSONArray paths = response.getJSONArray("paths"); for (int i = 0; i < paths.length(); i++) { JSONObject path = paths.getJSONObject(i); if (path.getString("path").equals(pathValue) && path.getInt("requestType") == type) { return path; } } return null; }
java
{ "resource": "" }
q8299
PathValueClient.setDefaultCustomResponse
train
public static boolean setDefaultCustomResponse(String pathValue, String requestType, String customData) { try { JSONObject profile = getDefaultProfile(); String profileName = profile.getString("name"); PathValueClient client = new PathValueClient(profileName, false); return client.setCustomResponse(pathValue, requestType, customData); } catch (Exception e) { e.printStackTrace(); } return false; }
java
{ "resource": "" }