code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public void pushDryRun() throws Exception {
if (releaseAction.isCreateVcsTag()) {
if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {
throw new Exception(String.format("Tag with name '%s' already exists", releaseAction.getTagUrl()));
}
}
String testTagName = releaseAction.getTagUrl() + "_test";
try {
scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);
} catch (Exception e) {
throw new Exception(String.format("Failed while attempting push dry-run: %s", e.getMessage()), e);
} finally {
if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {
scmManager.deleteLocalTag(testTagName);
}
}
} | java |
public synchronized static void registerImagOnAgents(Launcher launcher, final String imageTag,
final String host, final String targetRepo, final ArrayListMultimap<String, String> artifactsProps,
final int buildInfoId) throws IOException, InterruptedException {
// Master
final String imageId = getImageIdFromAgent(launcher, imageTag, host);
registerImage(imageId, imageTag, targetRepo, artifactsProps, buildInfoId);
// Agents
List<Node> nodes = Jenkins.getInstance().getNodes();
for (Node node : nodes) {
if (node == null || node.getChannel() == null) {
continue;
}
try {
node.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {
public Boolean call() throws IOException {
registerImage(imageId, imageTag, targetRepo, artifactsProps, buildInfoId);
return true;
}
});
} catch (Exception e) {
launcher.getListener().getLogger().println("Could not register docker image " + imageTag +
" on Jenkins node '" + node.getDisplayName() + "' due to: " + e.getMessage() +
" This could be because this node is now offline."
);
}
}
} | java |
private static void registerImage(String imageId, String imageTag, String targetRepo,
ArrayListMultimap<String, String> artifactsProps, int buildInfoId) throws IOException {
DockerImage image = new DockerImage(imageId, imageTag, targetRepo, buildInfoId, artifactsProps);
images.add(image);
} | java |
public static List<DockerImage> getImagesByBuildId(int buildInfoId) {
List<DockerImage> list = new ArrayList<DockerImage>();
Iterator<DockerImage> it = images.iterator();
while (it.hasNext()) {
DockerImage image = it.next();
if (image.getBuildInfoId() == buildInfoId && image.hasManifest()) {
list.add(image);
}
}
return list;
} | java |
public static List<DockerImage> getAndDiscardImagesByBuildId(int buildInfoId) {
List<DockerImage> list = new ArrayList<DockerImage>();
synchronized(images) {
Iterator<DockerImage> it = images.iterator();
while (it.hasNext()) {
DockerImage image = it.next();
if (image.getBuildInfoId() == buildInfoId) {
if (image.hasManifest()) {
list.add(image);
}
it.remove();
} else // Remove old images from the cache, for which build-info hasn't been published to Artifactory:
if (image.isExpired()) {
it.remove();
}
}
}
return list;
} | java |
public static List<DockerImage> getDockerImagesFromAgents(final int buildInfoId, TaskListener listener) throws IOException, InterruptedException {
List<DockerImage> dockerImages = new ArrayList<DockerImage>();
// Collect images from the master:
dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));
// Collect images from all the agents:
List<Node> nodes = Jenkins.getInstance().getNodes();
for (Node node : nodes) {
if (node == null || node.getChannel() == null) {
continue;
}
try {
List<DockerImage> partialDockerImages = node.getChannel().call(new MasterToSlaveCallable<List<DockerImage>, IOException>() {
public List<DockerImage> call() throws IOException {
List<DockerImage> dockerImages = new ArrayList<DockerImage>();
dockerImages.addAll(getAndDiscardImagesByBuildId(buildInfoId));
return dockerImages;
}
});
dockerImages.addAll(partialDockerImages);
} catch (Exception e) {
listener.getLogger().println("Could not collect docker images from Jenkins node '" + node.getDisplayName() + "' due to: " + e.getMessage());
}
}
return dockerImages;
} | java |
public static boolean pushImage(Launcher launcher, final JenkinsBuildInfoLog log, final String imageTag, final String username, final String password, final String host)
throws IOException, InterruptedException {
return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {
public Boolean call() throws IOException {
String message = "Pushing image: " + imageTag;
if (StringUtils.isNotEmpty(host)) {
message += " using docker daemon host: " + host;
}
log.info(message);
DockerUtils.pushImage(imageTag, username, password, host);
return true;
}
});
} | java |
public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)
throws IOException, InterruptedException {
return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {
public Boolean call() throws IOException {
DockerUtils.pullImage(imageTag, username, password, host);
return true;
}
});
} | java |
public static boolean updateImageParentOnAgents(final JenkinsBuildInfoLog log, final String imageTag, final String host, final int buildInfoId) throws IOException, InterruptedException {
boolean parentUpdated = updateImageParent(log, imageTag, host, buildInfoId);
List<Node> nodes = Jenkins.getInstance().getNodes();
for (Node node : nodes) {
if (node == null || node.getChannel() == null) {
continue;
}
boolean parentNodeUpdated = node.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {
public Boolean call() throws IOException {
return updateImageParent(log, imageTag, host, buildInfoId);
}
});
parentUpdated = parentUpdated ? parentUpdated : parentNodeUpdated;
}
return parentUpdated;
} | java |
public static String getImageIdFromAgent(Launcher launcher, final String imageTag, final String host) throws IOException, InterruptedException {
return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {
public String call() throws IOException {
return DockerUtils.getImageIdFromTag(imageTag, host);
}
});
} | java |
public static String getParentIdFromAgent(Launcher launcher, final String imageID, final String host) throws IOException, InterruptedException {
return launcher.getChannel().call(new MasterToSlaveCallable<String, IOException>() {
public String call() throws IOException {
return DockerUtils.getParentId(imageID, host);
}
});
} | java |
@Override
protected void initBuilderSpecific() throws Exception {
reset();
FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);
FilePath gradlePropertiesPath = new FilePath(workspace, "gradle.properties");
if (releaseProps == null) {
releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());
}
if (nextIntegProps == null) {
nextIntegProps =
PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());
}
} | java |
public FilePath getModuleRoot(Map<String, String> globalEnv) throws IOException, InterruptedException {
FilePath someWorkspace = project.getSomeWorkspace();
if (someWorkspace == null) {
throw new IllegalStateException("Couldn't find workspace");
}
Map<String, String> workspaceEnv = Maps.newHashMap();
workspaceEnv.put("WORKSPACE", someWorkspace.getRemote());
for (Builder builder : getBuilders()) {
if (builder instanceof Gradle) {
Gradle gradleBuilder = (Gradle) builder;
String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();
if (rootBuildScriptDir != null && rootBuildScriptDir.trim().length() != 0) {
String rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptDir.trim(), workspaceEnv);
rootBuildScriptNormalized = Util.replaceMacro(rootBuildScriptNormalized, globalEnv);
return new FilePath(someWorkspace, rootBuildScriptNormalized);
} else {
return someWorkspace;
}
}
}
throw new IllegalArgumentException("Couldn't find Gradle builder in the current builders list");
} | java |
private String extractNumericVersion(Collection<String> versionStrings) {
if (versionStrings == null) {
return "";
}
for (String value : versionStrings) {
String releaseValue = calculateReleaseVersion(value);
if (!releaseValue.equals(value)) {
return releaseValue;
}
}
return "";
} | java |
@SuppressWarnings("UnusedDeclaration")
public void init() throws Exception {
initBuilderSpecific();
resetFields();
if (!UserPluginInfo.NO_PLUGIN_KEY.equals(getSelectedStagingPluginName())) {
PluginSettings selectedStagingPluginSettings = getSelectedStagingPlugin();
try {
stagingStrategy = getArtifactoryServer().getStagingStrategy(selectedStagingPluginSettings, Util.rawEncode(project.getName()), project);
} catch (Exception e) {
log.log(Level.WARNING, "Failed to obtain staging strategy: " + e.getMessage(), e);
strategyRequestFailed = true;
strategyRequestErrorMessage = "Failed to obtain staging strategy '" +
selectedStagingPluginSettings.getPluginName() + "': " + e.getMessage() +
".\nPlease review the log for further information.";
stagingStrategy = null;
}
strategyPluginExists = (stagingStrategy != null) && !stagingStrategy.isEmpty();
}
prepareDefaultVersioning();
prepareDefaultGlobalModule();
prepareDefaultModules();
prepareDefaultVcsSettings();
prepareDefaultPromotionConfig();
} | java |
@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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
public final void reset()
{
for (int i = 0; i < permutationIndices.length; i++)
{
permutationIndices[i] = i;
}
remainingPermutations = totalPermutations;
} | java |
@SuppressWarnings("unchecked")
public T[] nextPermutationAsArray()
{
T[] permutation = (T[]) Array.newInstance(elements.getClass().getComponentType(),
permutationIndices.length);
return nextPermutationAsArray(permutation);
} | java |
public List<T> nextPermutationAsList()
{
List<T> permutation = new ArrayList<T>(elements.length);
return nextPermutationAsList(permutation);
} | java |
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 |
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 |
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 |
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 |
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 |
public boolean getBit(int index)
{
assertValidIndex(index);
int word = index / WORD_LENGTH;
int offset = index % WORD_LENGTH;
return (data[word] & (1 << offset)) != 0;
} | java |
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 |
public void flipBit(int index)
{
assertValidIndex(index);
int word = index / WORD_LENGTH;
int offset = index % WORD_LENGTH;
data[word] ^= (1 << offset);
} | java |
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 |
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 |
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 |
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 |
public static int restrictRange(int value, int min, int max)
{
return Math.min((Math.max(value, min)), max);
} | java |
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 |
public final void reset()
{
for (int i = 0; i < combinationIndices.length; i++)
{
combinationIndices[i] = i;
}
remainingCombinations = totalCombinations;
} | java |
@SuppressWarnings("unchecked")
public T[] nextCombinationAsArray()
{
T[] combination = (T[]) Array.newInstance(elements.getClass().getComponentType(),
combinationIndices.length);
return nextCombinationAsArray(combination);
} | java |
public void setValue(T value)
{
try
{
lock.writeLock().lock();
this.value = value;
}
finally
{
lock.writeLock().unlock();
}
} | java |
public static String urlEncode(String path) throws URISyntaxException {
if (isNullOrEmpty(path)) return path;
return UrlEscapers.urlFragmentEscaper().escape(path);
} | java |
public static String encode(String value) throws UnsupportedEncodingException {
if (isNullOrEmpty(value)) return value;
return URLEncoder.encode(value, URL_ENCODING);
} | java |
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 |
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 |
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 |
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 |
private String getJSONFromMap(Map<String, Object> propMap) {
try {
return new JSONObject(propMap).toString();
} catch (Exception e) {
return "{}";
}
} | java |
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 |
@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 |
@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 |
@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 |
@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 |
@RequestMapping(value = "/cert", method = {RequestMethod.GET, RequestMethod.HEAD})
public String certPage() throws Exception {
return "cert";
} | java |
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 |
public static String getURL(String sourceURI) {
String retval = sourceURI;
int qPos = sourceURI.indexOf("?");
if (qPos != -1) {
retval = retval.substring(0, qPos);
}
return retval;
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
public void removeCustomOverride(int path_id, String client_uuid) throws Exception {
updateRequestResponseTables("custom_response", "", getProfileIdFromPathID(path_id), client_uuid, path_id);
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
public Integer getGroupIdFromName(String groupName) {
return (Integer) sqlService.getFromTable(Constants.GENERIC_ID, Constants.GROUPS_GROUP_NAME, groupName,
Constants.DB_TABLE_GROUPS);
} | java |
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 |
public String getGroupNameFromId(int groupId) {
return (String) sqlService.getFromTable(Constants.GROUPS_GROUP_NAME, Constants.GENERIC_ID, groupId,
Constants.DB_TABLE_GROUPS);
} | java |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.