I need to create a class library which enables me to read different files (.dat-files with different data representations inside them) and create objects with their content (for every line one object).
I also have to create a unit test which starts the reading of the file, so I dont have to read to whole file first and save the content in an array. I want to use the factory pattern.
Here is my implementation of the class that implements the Iterator-Interface
package klassenbibliothek;
public class MyReader implements Iterator<Object>
{
BufferedReader reader;
MyReader(BufferedReader myReader)
{
reader = myReader;
}
#Override
public boolean hasNext() // aus Stackoverflow, von mir abgeändert
{
try {
return reader.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
throw new NoSuchElementException();
}
}
#Override
public String next()
{
//return SubstancesFileObjectCreator(reader.readLine());
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
// return null;
throw new NoSuchElementException();
}
}
}
My question is: why do I get this error message "finally block does not complete normally"? I am not returning something, I am just throwing an exception.
I want to use the methods hasNext() and next() in my unit test, so that the unit test can controll when it starts to read the file. The unit test is in a different package.
Here are my other classes:
class AbstractFileObjectCreator
package klassenbibliothek;
public abstract class AbstractFileObjectCreator
{
public abstract AbstractFileObject createFileObject(String line);
}
class SubstancesFileObjectCreator
package klassenbibliothek;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SubstancesFileObjectCreator extends AbstractFileObjectCreator
{
MyReader myReader;
public void makeReader() throws IOException
{
String dataFileName = "C:/temp/Substances.dat";
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
myReader = new MyReader(bReader);
}
#SuppressWarnings("null")
public AbstractFileObject createFileObject(String line)
{
AbstractFileObject mySubstance = null;
String lineValues[] = myReader.next().split("\t");
if(lineValues[0].equals("R"))
{
boolean dutyToDeclare_local;
boolean isUnwanted_local;
boolean isProhibited_local;
boolean isReach_local;
boolean isDeleted_local;
boolean isHidden_local;
String nodeidRaw = lineValues[1];
float nodeid = Float.parseFloat(nodeidRaw);
String casNrRaw = lineValues[2];
String euIndexCodeRaw = lineValues[3];
String einecsCodeRaw = lineValues[4];
String dutyToDeclareRaw = lineValues[5];
if(dutyToDeclareRaw.equals(1))
{
dutyToDeclare_local = true;
}
else
{
dutyToDeclare_local = false;
}
String isUnwantedRaw = lineValues[6];
if(isUnwantedRaw.equals("1"))
{
isUnwanted_local = true;
}
else
{
isUnwanted_local = false;
}
String isProhibitedRaw = lineValues[7];
if(isProhibitedRaw.equals("1"))
{
isProhibited_local = true;
}
else
{
isProhibited_local = false;
}
String isReachRaw = lineValues[8];
if(isReachRaw.equals("1"))
{
isReach_local = true;
}
else
{
isReach_local = false;
}
String isDeletedRaw = lineValues[9];
if(isDeletedRaw.equals("1"))
{
isDeleted_local = true;
}
else
{
isDeleted_local = false;
}
String isHiddenRaw = lineValues[10];
if(isHiddenRaw.equals("1"))
{
isHidden_local = true;
}
else
{
isHidden_local = false;
}
mySubstance = new Substance(nodeid, casNrRaw, euIndexCodeRaw, einecsCodeRaw, dutyToDeclare_local, isUnwanted_local, isProhibited_local, isReach_local, isDeleted_local, isHidden_local);
// und weiter...
}
else
{
String languageCode = lineValues[1];
String name = lineValues[2];
// Synonym-Objekt erzeugen und zu Substance-Objekt hinzufügen
Synonym newSynonym = new Synonym(languageCode, name);
mySubstance.addAppendix(newSynonym);
while(myReader.hasNext())
{
String lineValues_synonyms[] = myReader.next().split("\t");
String lineValuesZero = lineValues_synonyms[0];
if(lineValuesZero.equals("R"))
{
break; // nicht so gut glaube ich!!!
}
String languageCode_next = lineValues_synonyms[1];
String name_next = lineValues_synonyms[2];
Synonym newSynonym_next = new Synonym(languageCode_next, name_next);
mySubstance.addAppendix(newSynonym_next);
}
}
return mySubstance;
}
}
class AbstractFileObject
package klassenbibliothek;
public abstract class AbstractFileObject
{
boolean isDeleted;
public AbstractFileObject(boolean isDeleted)
{
this.isDeleted = isDeleted;
}
public boolean getIsDeleted()
{
return isDeleted;
}
public abstract void addAppendix(Object newAppendix);
}
class Substance
public class Substance extends AbstractFileObject
{
private float nodeid;
private String casNr;
private String euIndexCode;
private String einecsCode;
private boolean dutyToDeclare;
private boolean isUnwanted;
private boolean isProhibited;
private boolean isReach;
private boolean isDeleted;
private boolean isHidden;
private ArrayList<Synonym> synonymList;
public Substance(float nodeid, String casNr, String euIndexCode, String einecsCode,
boolean dutyToDeclare, boolean isUnwanted, boolean isProhibited, boolean isReach,
boolean isDeleted, boolean isHidden)
{
super(isDeleted);
this.nodeid = nodeid;
this.casNr = casNr;
this.euIndexCode = euIndexCode;
this.einecsCode = einecsCode;
this.dutyToDeclare = dutyToDeclare;
this.isUnwanted = isUnwanted;
this.isProhibited = isProhibited;
this.isReach = isReach;
//this.isDeleted = isDeleted;
this.isHidden = isHidden;
}
// getter and setter
}
class Synonym
package klassenbibliothek;
public class Synonym
{
private String languageCode;
private String name;
public Synonym(String languageCode, String name)
{
this.languageCode = languageCode;
this.name = name;
}
public String getLanguageCode()
{
return languageCode;
}
public String getName()
{
return name;
}
}
unit test
package klassenbibliothek.test;
import static org.junit.Assert.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class SubstancesTest {
#Test
public void test() {
//fail("Not yet implemented");
long startTimeNanos = System.nanoTime();
/*
* While... iterator over data file
*/
}
}
Am I using the factory pattern in the right way? I'm very confused.
A finally block always executes if there is a try-block before it. So yours always throws a NoSuchElementException().
finally
{
// return null;
throw new NoSuchElementException();
}
You should do something in it and not throw an Exception.
Finally blocks are for cleanup. They should not specifically throw exceptions like that. Move the exception throwing out of the finally block.
Remove the throw exception from the finally block and put it in catch block or some other place. Finally block is to release resources that you might be using in your program.
Related
I am trying to extend the Dynatrace App Mon plugin to be Jenkins pipeline compatible. I have taken the source code from Github dynatrace-dashboard-2.0.5 (source code from master branch of this repository and dynatrace github repository had some issue and wasn't working, so I ended up downloading the source code of release 2.0.5)
I wrote a class DynatraceAppMonBuildEnvStep which extends AbstractStepImpl and mimics the functionality of TABuildWrapper step. I am running into issue when Utils.updateBuildVariables(build, parameters); method is called in DynatraceAppMonBuildEnvStep class, which will eventually set the environment variables. I don't get any error/exception but it is not setting the environment variables which I need to inject in the mvn build command.
When I run bat 'set' in my pipeline script, it does not show below environment variable. I am able to see these env variables if I invoke the plugin via non pipeline.
dtMarker=testservice
dtPassword=password1
dtProfile=testprofile
dtServerUrl=https://<someurl>:8021
dtTestrunID=<test id>
dtUsername=<username>
dtVersionBuild=36
dtVersionMajor=testservice
The code flow is below: DynatraceAppMonBuildEnvStep -> Utils -> DynatraceVariablesAction -> DynatraceVariablesEnvironmentContributor -> buildEnvironmentFor (method).
DynatraceAppMonBuildEnvStep.java
package com.dynatrace.jenkins.steps;
import hudson.Extension;
import hudson.model.ParameterValue;
import hudson.model.PasswordParameterValue;
import hudson.model.Run;
import hudson.model.StringParameterValue;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import jenkins.model.GlobalConfiguration;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl;
import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl;
import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution;
import org.jenkinsci.plugins.workflow.steps.StepContextParameter;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.dynatrace.jenkins.dashboard.Messages;
import com.dynatrace.jenkins.dashboard.TABuildSetupStatusAction;
import com.dynatrace.jenkins.dashboard.TAGlobalConfiguration;
import com.dynatrace.jenkins.dashboard.utils.BuildVarKeys;
import com.dynatrace.jenkins.dashboard.utils.Utils;
import com.dynatrace.sdk.server.exceptions.ServerResponseException;
import com.dynatrace.sdk.server.sessions.Sessions;
import com.dynatrace.sdk.server.sessions.models.StartRecordingRequest;
import com.dynatrace.sdk.server.testautomation.TestAutomation;
import com.dynatrace.sdk.server.testautomation.models.FetchTestRunsRequest;
import com.sun.jersey.api.client.ClientHandlerException;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import java.io.PrintStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.net.ssl.SSLHandshakeException;
public final class DynatraceAppMonBuildEnvStep extends AbstractStepImpl {
/**
* The 1st arg is system profile name, the 2nd is build number
*/
private static final String RECORD_SESSION_NAME = "%s_Jenkins_build_%s";
public final String systemProfile;
// Test run attributes - no versionBuild attribute because it's taken from
// the build object
public final String versionMajor;
public final String versionMinor;
public final String versionRevision;
public final String versionMilestone;
public final String marker;
public final Boolean recordSession;
#DataBoundConstructor
public DynatraceAppMonBuildEnvStep(final String systemProfile, final String versionMajor, final String versionMinor,
final String versionRevision, final String versionMilestone, final String marker,
final Boolean recordSession) {
this.systemProfile = systemProfile;
this.versionMajor = versionMajor;
this.versionMinor = versionMinor;
this.versionRevision = versionRevision;
this.versionMilestone = versionMilestone;
this.marker = marker;
this.recordSession = recordSession;
}
private void setupBuildVariables(Run<?, ?> build, String serverUrl) {
final TAGlobalConfiguration globalConfig = GlobalConfiguration.all().get(TAGlobalConfiguration.class);
List<ParameterValue> parameters = new ArrayList<>(10);
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_SYSTEM_PROFILE, systemProfile));
if (StringUtils.isNotEmpty(versionMajor)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_VERSION_MAJOR, versionMajor));
}
if (StringUtils.isNotEmpty(versionMinor)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_VERSION_MINOR, versionMinor));
}
if (StringUtils.isNotEmpty(versionRevision)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_VERSION_REVISION, versionRevision));
}
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_VERSION_BUILD,
Integer.toString(build.getNumber())));
if (StringUtils.isNotEmpty(versionMilestone)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_VERSION_MILESTONE, versionMilestone));
}
if (StringUtils.isNotEmpty(marker)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_MARKER, marker));
}
if (StringUtils.isNotEmpty(serverUrl)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_GLOBAL_SERVER_URL, serverUrl));
}
if (StringUtils.isNotEmpty(globalConfig.username)) {
parameters.add(new StringParameterValue(BuildVarKeys.BUILD_VAR_KEY_GLOBAL_USERNAME, globalConfig.username));
}
if (StringUtils.isNotEmpty(globalConfig.password)) {
parameters
.add(new PasswordParameterValue(BuildVarKeys.BUILD_VAR_KEY_GLOBAL_PASSWORD, globalConfig.password));
}
System.out.println("first call to utlis.updateBuildVariables from step 1::::");
Utils.updateBuildVariables(build, parameters);
}
#Extension
public static final class DescriptorImpl extends AbstractStepDescriptorImpl {
public DescriptorImpl() {
super(Execution.class);
}
#Override
public String getFunctionName() {
return "dynatraceAppMonBuildEnvStep";
}
private static final boolean DEFAULT_RECORD_SESSION = false;
public static boolean getDefaultRecordSession() {
return DEFAULT_RECORD_SESSION;
}
#Nonnull
#Override
public String getDisplayName() {
return "Use Dynatrace AppMon to monitor tests";
}
public FormValidation doCheckSystemProfile(#QueryParameter final String systemProfile) {
if (StringUtils.isNotBlank(systemProfile)) {
return FormValidation.ok();
} else {
return FormValidation.error(Messages.RECORDER_VALIDATION_BLANK_SYSTEM_PROFILE());
}
}
public FormValidation doTestDynatraceConnection(#QueryParameter final String systemProfile) {
try {
final TestAutomation connection = new TestAutomation(Utils.createClient());
FetchTestRunsRequest request = new FetchTestRunsRequest(systemProfile);
// We set many constraints to ENSURE no or few testruns are
// returned as this is testing the connection only
request.setVersionBuildFilter("1024");
request.setVersionMajorFilter("1024");
request.setMaxBuilds(1);
try {
connection.fetchTestRuns(request);
} catch (ServerResponseException e) {
switch (e.getStatusCode()) {
case HTTP_UNAUTHORIZED:
return FormValidation.warning(Messages.RECORDER_VALIDATION_CONNECTION_UNAUTHORIZED());
case HTTP_FORBIDDEN:
return FormValidation.warning(Messages.RECORDER_VALIDATION_CONNECTION_FORBIDDEN());
case HTTP_NOT_FOUND:
return FormValidation.warning(Messages.RECORDER_VALIDATION_CONNECTION_NOT_FOUND());
default:
return FormValidation
.warning(Messages.RECORDER_VALIDATION_CONNECTION_OTHER_CODE(e.getStatusCode()));
}
}
return FormValidation.ok(Messages.RECORDER_VALIDATION_CONNECTION_OK());
} catch (Exception e) {
e.printStackTrace();
if (e.getCause() instanceof ClientHandlerException
&& e.getCause().getCause() instanceof SSLHandshakeException) {
return FormValidation.warning(Messages.RECORDER_VALIDATION_CONNECTION_CERT_EXCEPTION(e.toString()));
}
return FormValidation.warning(Messages.RECORDER_VALIDATION_CONNECTION_UNKNOWN(e.toString()));
}
}
}
public static final class Execution extends AbstractSynchronousNonBlockingStepExecution<Boolean> {
#Inject
private transient DynatraceAppMonBuildEnvStep step;
// public final Boolean recordSession = step.recordSession;
// public final Boolean recordSession = false;
#StepContextParameter
private transient TaskListener listener;
#StepContextParameter
private transient Run<?, ?> build;
#Override
protected Boolean run() throws Exception {
Boolean result = true;
final TAGlobalConfiguration globalConfig = GlobalConfiguration.all().get(TAGlobalConfiguration.class);
final Sessions sessions = new Sessions(Utils.createClient());
final PrintStream logger = listener.getLogger();
// logger.println("host is:"+globalConfig.host);
try {
String serverUrl = new URI(globalConfig.protocol, null, globalConfig.host, globalConfig.port, null,
null, null).toString();
if (step.recordSession) {
logger.println("Starting session recording via Dynatrace Server REST interface...");
StartRecordingRequest request = new StartRecordingRequest(step.systemProfile);
request.setPresentableName(
String.format(RECORD_SESSION_NAME, step.systemProfile, build.getNumber()));
final String sessionNameOut = sessions.startRecording(request);
logger.println("Dynatrace session " + sessionNameOut + " has been started");
}
step.setupBuildVariables(build, serverUrl);
} catch (Exception e) {
e.printStackTrace();
build.addAction(new TABuildSetupStatusAction(true));
logger.println(
"ERROR: Dynatrace AppMon Plugin - build set up failed (see the stacktrace to get more information):\n"
+ e.toString());
}
// final PrintStream logger = listener.getLogger();
/*
* logger.println("Dynatrace AppMon Plugin - build tear down...");
* try { if (recordSession) { final String storedSessionName =
* storeSession(logger); Utils.updateBuildVariable(build,
* BuildVarKeys.BUILD_VAR_KEY_STORED_SESSION_NAME,
* storedSessionName); } } catch (Exception e) {
* e.printStackTrace(); logger.
* println("ERROR: Dynatrace AppMon Plugin - build tear down failed (see the stacktrace to get more information):\n"
* + e.toString()); }
*/
return result;
}
private static final long serialVersionUID = 1L;
/**
* #return stored session name
*/
/*
* private String storeSession(final PrintStream logger) throws
* ServerResponseException, ServerConnectionException { logger.
* println("Storing session via Dynatrace Server REST interface...");
* String sessionName = sessions.stopRecording(step.systemProfile);
* logger.println("Dynatrace session " + sessionName +
* " has been stored"); return sessionName; }
*/
}
}
**Utils.java**
package com.dynatrace.jenkins.dashboard.utils;
import com.dynatrace.jenkins.dashboard.TABuildSetupStatusAction;
import com.dynatrace.jenkins.dashboard.TAGlobalConfiguration;
import com.dynatrace.jenkins.dashboard.model_2_0_0.*;
import com.dynatrace.sdk.server.BasicServerConfiguration;
import com.dynatrace.sdk.server.DynatraceClient;
import com.dynatrace.sdk.server.testautomation.models.TestRuns;
import hudson.model.AbstractBuild;
import hudson.model.ParameterValue;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.StringParameterValue;
import jenkins.model.GlobalConfiguration;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.*;
/**
* Created by krzysztof.necel on 2016-01-25.
*/
public final class Utils {
public static final String TEST_MEASURE_UNIT_DEFAULT = "num";
public static final String DYNATRACE_ICON_24_X_24_FILEPATH = "/plugin/dynatrace-dashboard/images/dynatrace_icon_24x24.png";
public static final String DYNATRACE_ICON_48_X_48_FILEPATH = "/plugin/dynatrace-dashboard/images/dynatrace_icon_48x48.png";
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#.##");
private static final String FORMAT_DOUBLE_NULL_VALUE = "N/A";
private Utils() {
}
public static DynatraceClient createClient() {
final TAGlobalConfiguration globalConfig = GlobalConfiguration.all().get(TAGlobalConfiguration.class);
BasicServerConfiguration config = new BasicServerConfiguration(globalConfig.username,
globalConfig.password,
globalConfig.protocol.startsWith("https"),
globalConfig.host,
globalConfig.port,
globalConfig.validateCerts,
//connection timeout, 0 stands for infinite
0);
return new DynatraceClient(config);
}
public static TAReportDetails convertTestRuns(TestRuns sdkTestRuns) {
ArrayList<TestRun> testRuns = new ArrayList<>();
if (sdkTestRuns != null) {
for (com.dynatrace.sdk.server.testautomation.models.TestRun tr : sdkTestRuns.getTestRuns()) {
testRuns.add(convertTestRun(tr));
}
}
return new TAReportDetails(testRuns);
}
public static TestRun convertTestRun(com.dynatrace.sdk.server.testautomation.models.TestRun sdkTestRun) {
List<TestResult> testResults = new ArrayList<>();
for (com.dynatrace.sdk.server.testautomation.models.TestResult sdkResult : sdkTestRun.getTestResults()) {
testResults.add(convertTestResult(sdkResult));
}
Map<TestStatus, Integer> testRunSummary = new EnumMap<>(TestStatus.class);
testRunSummary.put(TestStatus.FAILED, sdkTestRun.getFailedCount());
testRunSummary.put(TestStatus.DEGRADED, sdkTestRun.getDegradedCount());
testRunSummary.put(TestStatus.VOLATILE, sdkTestRun.getVolatileCount());
testRunSummary.put(TestStatus.IMPROVED, sdkTestRun.getImprovedCount());
testRunSummary.put(TestStatus.PASSED, sdkTestRun.getPassedCount());
return new TestRun(testResults, testRunSummary, sdkTestRun.getId(), convertTestCategory(sdkTestRun.getCategory()));
}
public static TestResult convertTestResult(com.dynatrace.sdk.server.testautomation.models.TestResult sdkTestResult) {
Set<TestMeasure> measures = new HashSet<>();
for (com.dynatrace.sdk.server.testautomation.models.TestMeasure sdkMeasure : sdkTestResult.getMeasures()) {
measures.add(convertTestMeasure(sdkMeasure));
}
return new TestResult(new Date(sdkTestResult.getExecutionTime()), sdkTestResult.getName(), sdkTestResult.getPackageName(), sdkTestResult.getPlatform(), convertTestStatus(sdkTestResult.getStatus()), measures);
}
public static TestMeasure convertTestMeasure(com.dynatrace.sdk.server.testautomation.models.TestMeasure sdkTestMeasure) {
String unit = sdkTestMeasure.getUnit() != null ? sdkTestMeasure.getUnit() : TEST_MEASURE_UNIT_DEFAULT;
return new TestMeasure(sdkTestMeasure.getName(),
sdkTestMeasure.getMetricGroup(),
sdkTestMeasure.getExpectedMin(),
sdkTestMeasure.getExpectedMax(),
sdkTestMeasure.getValue(),
unit,
sdkTestMeasure.getViolationPercentage());
}
public static TestCategory convertTestCategory(com.dynatrace.sdk.server.testautomation.models.TestCategory sdkTestCategory) {
switch (sdkTestCategory) {
case UNIT:
return TestCategory.UNIT;
case UI_DRIVEN:
return TestCategory.UI_DRIVEN;
case WEB_API:
return TestCategory.WEB_API;
case PERFORMANCE:
return TestCategory.PERFORMANCE;
}
throw new IllegalArgumentException("Could not convert TestCategory");
}
public static TestStatus convertTestStatus(com.dynatrace.sdk.server.testautomation.models.TestStatus sdkTestStatus) {
return TestStatus.valueOf(sdkTestStatus.name());
}
public static Map<TestStatus, Integer> createReportAggregatedSummary(TAReportDetails reportDetails) {
// just sum all the reports for test runs
final Map<TestStatus, Integer> summary = new EnumMap<>(TestStatus.class);
for (TestRun testRun : reportDetails.getTestRuns()) {
Map<TestStatus, Integer> testRunSummary = testRun.getSummary();
for (Map.Entry<TestStatus, Integer> entry : testRunSummary.entrySet()) {
Integer value = summary.get(entry.getKey());
summary.put(entry.getKey(), value == null ? entry.getValue() : entry.getValue() + value);
}
}
return summary;
}
public static String formatDouble(Double d) {
return d == null ? FORMAT_DOUBLE_NULL_VALUE : DECIMAL_FORMAT.format(d);
}
public static String formatDoublePercentage(Double d) {
return d == null ? FORMAT_DOUBLE_NULL_VALUE : DECIMAL_FORMAT.format(d * 100);
}
public static boolean isValidBuild(AbstractBuild build, PrintStream logger, String message) {
if (build.getResult() == Result.ABORTED) {
logger.println("Build has been aborted - " + message);
return false;
}
TABuildSetupStatusAction setupStatusAction = build.getAction(TABuildSetupStatusAction.class);
if (setupStatusAction != null && setupStatusAction.isSetupFailed()) {
logger.println("Failed to set up environment for Dynatrace AppMon Plugin - " + message);
return false;
}
return true;
}
public static boolean isValidBuild(Run build, PrintStream logger, String message) {
if (build.getResult() == Result.ABORTED) {
logger.println("Build has been aborted - " + message);
return false;
}
TABuildSetupStatusAction setupStatusAction = build.getAction(TABuildSetupStatusAction.class);
if (setupStatusAction != null && setupStatusAction.isSetupFailed()) {
logger.println("Failed to set up environment for Dynatrace AppMon Plugin - " + message);
return false;
}
return true;
}
public static void updateBuildVariables(AbstractBuild<?, ?> build, List<ParameterValue> parameters) {
DynatraceVariablesAction existingAction = build.getAction(DynatraceVariablesAction.class);
if (existingAction == null) {
build.addAction(new DynatraceVariablesAction(parameters));
} else {
build.replaceAction(existingAction.createUpdated(parameters));
}
}
public static void updateBuildVariables(Run<?, ?> build, List<ParameterValue> parameters) {
DynatraceVariablesAction existingAction = build.getAction(DynatraceVariablesAction.class);
if (existingAction == null) {
build.addAction(new DynatraceVariablesAction(parameters));
} else {
build.replaceAction(existingAction.createUpdated(parameters));
}
}
public static void updateBuildVariable(AbstractBuild<?, ?> build, String key, String value) {
updateBuildVariables(build, Collections.<ParameterValue>singletonList(new StringParameterValue(key, value)));
}
public static void updateBuildVariable(Run<?, ?> build, String key, String value) {
updateBuildVariables(build, Collections.<ParameterValue>singletonList(new StringParameterValue(key, value)));
}
}
**DynatraceVariablesAction.java**
package com.dynatrace.jenkins.dashboard.utils;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.*;
import javax.annotation.Nonnull;
import java.util.*;
public class DynatraceVariablesAction extends ParametersAction {
private List<ParameterValue> parameters = new ArrayList<>();
public DynatraceVariablesAction(Collection<? extends ParameterValue> parameters) {
this.parameters.addAll(parameters);
}
#Override
public List<ParameterValue> getParameters() {
return Collections.unmodifiableList(parameters);
}
#Override
public ParameterValue getParameter(String name) {
for (ParameterValue p : parameters) {
if (p == null) continue;
if (p.getName().equals(name))
return p;
}
return null;
}
#Nonnull
#Override
public DynatraceVariablesAction createUpdated(Collection<? extends ParameterValue> overrides) {
List<ParameterValue> newParams = new ArrayList<>(overrides);
outer:
for (ParameterValue value : this.parameters) {
for (ParameterValue newParam : newParams) {
if (newParam.getName().equals(value.getName())) {
continue outer;
}
}
newParams.add(value);
}
return new DynatraceVariablesAction(newParams);
}
#Extension
public static final class DynatraceBuildVariablesContributor extends BuildVariableContributor {
#Override
public void buildVariablesFor(AbstractBuild r, Map<String, String> variables) {
DynatraceVariablesAction a = r.getAction(DynatraceVariablesAction.class);
if (a == null) {
return;
}
for (ParameterValue spv : a.getParameters()) {
variables.put(spv.getName(), String.valueOf(spv.getValue()));
}
}
}
#Extension
public static final class DynatraceVariablesEnvironmentContributor extends EnvironmentContributor {
#Override
public void buildEnvironmentFor(Run r, EnvVars vars, TaskListener listener) {
DynatraceVariablesAction a = r.getAction(DynatraceVariablesAction.class);
if (a == null) {
return;
}
for (ParameterValue spv : a.getParameters()) {
vars.put(spv.getName(), String.valueOf(spv.getValue()));
}
}
}
}
I also tried to set the environment variables by extending InvisibleAction class instead of ParametersAction, as performance-signature-dynatrace-plugin is doing but that didn't seem to work as well. Dynatrace performance signature plugin is setting the environment variables in a bit different way. See these two links:
[https://github.com/jenkinsci/performance-signature-dynatrace-plugin/blob/master/dynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/PerfSigEnvInvisAction.java][1]
[https://github.com/jenkinsci/performance-signature-dynatrace-plugin/blob/master/dynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/PerfSigEnvContributor.java][2]
[1]: https://github.com/jenkinsci/performance-signature-dynatrace-plugin/blob/master/dynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/PerfSigEnvInvisAction.java
[2]: https://github.com/jenkinsci/performance-signature-dynatrace-plugin/blob/master/dynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/PerfSigEnvContributor.java
Any help would be highly appreciated. I hope I was able to describe the problem. Please feel free to comment if my issue/question is not clear.
Thanks.
I need to get the line numbers a specific method is invoked in a .class file.
I took a look at How can I find all the methods that call a given method in Java? It returns the methods that call a method but I need the line numbers in the caller methods, as well.
I solved it by manipulating the code on that link a little
import java.io.InputStream;
import org.objectweb.asm.*;
import org.objectweb.asm.commons.*;
public class App{
public static void main( String[] args ) {
try {
Test test = new Test();
test.findCallers();
}catch (Exception e){
e.printStackTrace();
}
}
}
class Test {
private String targetClass;
private Method targetMethod;
private AppClassVisitor cv;
class AppMethodVisitor extends MethodVisitor {
boolean callsTarget;
int line;
public AppMethodVisitor() {
super(Opcodes.ASM5);
}
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (owner.equals("Fibonacci") && name.equals("join") && desc.equals("()V")) {
callsTarget = true;
System.out.println("Function join called on " + this.line);
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
public void visitCode() {
callsTarget = false;
}
public void visitLineNumber(int line, Label start) {
this.line = line;
}
public void visitEnd() {
if (callsTarget){
System.out.println(cv.className + cv.methodName + cv.methodDesc + line);
}
}
}
class AppClassVisitor extends ClassVisitor {
private AppMethodVisitor mv = new AppMethodVisitor();
public String className;
public String methodName;
public String methodDesc;
public AppClassVisitor() {
super(Opcodes.ASM5);
}
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
className = name;
}
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
methodName = name;
methodDesc = desc;
return mv;
}
}
public void findCallers() throws Exception {
InputStream stream = App.class.getResourceAsStream("Fibonacci.class");
ClassReader reader = new ClassReader(stream);
cv = new AppClassVisitor();
reader.accept(cv, 0);
stream.close();
}
}
Fibonacci.java content:
public class Fibonacci extends Thread{
int n;
int result;
public Fibonacci(int n){
this.n = n;
}
public void run(){
if((n == 0) || (n == 1)){
result = 1;
}else{
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
f1.start();
f2.start();
try{
f1.join();
f2.join();
}catch(InterruptedException e){
e.printStackTrace();
}
result = f1.getResult() + f2.getResult();
}
}
public int getResult(){
return result;
}
public static void main(String[] args) {
Fibonacci f1 = new Fibonacci(5);
f1.start();
try{
f1.join();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Answer is " + f1.getResult());
}
}
I'm trying to run this java code:
public class Lector{
public static void main(String[] args) {
int numVentaint;
try{
List<Guardar> guardar = new ArrayList<Guardar>();
CsvReader ventas_import = new CsvReader("C:\\Users\\Karen Jaure\\Downloads\\Kubii-Sushi-Ventas.csv"); // ac· se agrega la ruta de csv
ventas_import.readHeaders();
while (ventas_import.readRecord()){
String numVenta= ventas_import.get(0);
String fechaVenta= ventas_import.get(1);
String horaVenta= ventas_import.get(2);
String nombreProducto = ventas_import.get(4);
String montoTotal= ventas_import.get(7);
String codProducto= ventas_import.get(3);
String precioUnitarioProducto= ventas_import.get(5);
String cantidadUnidades = ventas_import.get(6);
guardar.add(new Guardar(numVenta, fechaVenta, horaVenta, codProducto, nombreProducto, precioUnitarioProducto, cantidadUnidades));
}
ventas_import.close();
for(Guardar us:guardar){
System.out.println(us.getNumVenta());
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I want to show only "numVenta" attribute of "Guardar" class but when I run it, the system out print method doesn't filter the attribute given by the "Guardar" class method ".getNumVenta()".
I just can't find the error! Help will be very appreciated.
UPDATED
Here is the "Guardar" class:
public class Guardar {
private String numVenta;
private String fechaVenta;
private String horaVenta;
private String codProducto;
private String nomProducto;
private String precioUnitario;
private String cantidadUnidades;
public Guardar(String numVenta, String fechaVenta, String horaVenta, String codProducto, String nomProducto, String precioUnitario, String cantidadUnidades) {
this.numVenta = numVenta;
this.fechaVenta = fechaVenta;
this.horaVenta = horaVenta;
this.codProducto = codProducto;
this.nomProducto = nomProducto;
this.precioUnitario = precioUnitario;
this.cantidadUnidades = cantidadUnidades;
}
public String getNumVenta() {
return numVenta;
}
public void setNumVenta(String numVenta) {
this.numVenta = numVenta;
}
public String getFechaVenta() {
return fechaVenta;
}
public void setFechaVenta(String fechaVenta) {
this.fechaVenta = fechaVenta;
}
public String getHoraVenta() {
return horaVenta;
}
public void setHoraVenta(String horaVenta) {
this.horaVenta = horaVenta;
}
public String getCodProducto() {
return codProducto;
}
public void setCodProducto(String codProducto) {
this.codProducto = codProducto;
}
public String getNomProducto() {
return nomProducto;
}
public void setNomProducto(String nomProducto) {
this.nomProducto = nomProducto;
}
public String getPrecioUnitario() {
return precioUnitario;
}
public void setPrecioUnitario(String precioUnitario) {
this.precioUnitario = precioUnitario;
}
public String getCantidadUnidades() {
return cantidadUnidades;
}
public void setCantidadUnidades(String cantidadUnidades) {
this.cantidadUnidades = cantidadUnidades;
}
}
My goal: save one ArrayList to a .dat file, after read this file and in the end print this array.
To save the ArrayList, "equipas" is one ArrayList< Equipa>, I use this function:
saveMyFile("Equipas.dat", (Object) equipas);
To read:
public static ArrayList<Equipa> readMyFile(String s){
ArrayList<Equipa> novo = new ArrayList<Equipa>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(s));
novo = (ArrayList<Equipa>) ois.readObject();
ois.close();
}
catch(IOException er) { System.out.println(er.getMessage()); }
catch(ClassNotFoundException er) { System.out.println(er.getMessage()); }
return novo;}
In this read function, I have one Compilation Warning: "…uses unchecked or unsafe operations. Recompile with - Xlint:unchecked for details."
To save:
public static void saveMyFile(String s, Object o)
{
try {
ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(s));
oos.writeObject(o);
oos.flush();
oos.close();
}
catch(IOException e) { System.out.println(e.getMessage()); }
}
Finally, I want to print the ArrayList's info:
ArrayList<Equipa> cena = new ArrayList<Equipa>();
cena=(ArrayList<Equipa>) readMyFile("Equipas.dat");
for(Equipa e:cena)
e.toString();
Error when I try to run:
" writing aborted; java.io.NotSerializableException: Equipa"
Equipa havs the Serializable:
import java.util.*;
import java.io.*;
public class Equipa implements Serializable
{
private String nome;
private Carro carro;
private ArrayList<Piloto> pilotos;
private double tempoDecorrido;
private int pontos;
private boolean desistiu;
private int voltaDesistencia;
private Piloto piloto;
/**
* Constructor for objects of class Equipa
*/
public Equipa()
{
this.nome = "NA";
this.carro = null;
this.pilotos = new ArrayList<Piloto>();
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
this.piloto = null;
}
public Equipa(String nome, Carro carro, ArrayList<Piloto> pilotos)
{
this.nome = nome;
this.carro = carro;
//this.pilotos = new ArrayList<Piloto>(pilotos);
this.pilotos = pilotos;
this.tempoDecorrido = 0;
this.pontos = 0;
this.desistiu = false;
this.voltaDesistencia = 0;
//this.piloto = pilotos.get(0);
}
public Equipa (Equipa e)
{
this.nome = e.getNome();
this.carro = e.getCarro();
this.pilotos = e.getPilotos();
this.tempoDecorrido = e.getTempoDecorrido();
this.pontos = e.getPontos();
this.desistiu = e.getDesistiu();
this.voltaDesistencia = e.getVoltaDesistencia();
//this.piloto = e.getPiloto();
}
/** Getters */
public String getNome()
{
return this.nome;
}
public Carro getCarro()
{
return this.carro;
}
public ArrayList<Piloto> getPilotos()
{
return new ArrayList<Piloto>(this.pilotos);
}
public double getTempoDecorrido()
{
return this.tempoDecorrido;
}
public int getPontos()
{
return this.pontos;
}
public boolean getDesistiu()
{
return this.desistiu;
}
public int getVoltaDesistencia()
{
return this.voltaDesistencia;
}
public Piloto getPiloto()
{
return this.piloto;
}
/** Setters */
public void setNome(String nome)
{
this.nome = nome;
}
public void setCarro(Carro carro)
{
this.carro = carro;
}
public void setPilotos(ArrayList<Piloto> pilotos)
{
this.pilotos = new ArrayList<Piloto>(pilotos);
}
public void setTempoDecorrido(double tempoDecorrido)
{
this.tempoDecorrido = tempoDecorrido;
}
public void setPontos(int pontos)
{
this.pontos = pontos;
}
public void setDesistiu(boolean desistiu)
{
this.desistiu = desistiu;
}
public void setVoltaDesistencia(int voltaDesistencia)
{
this.voltaDesistencia = voltaDesistencia;
}
public void setPiloto(Piloto piloto)
{
this.piloto = piloto;
}
/** Outros Métodos */
public Equipa clone()
{
return new Equipa(this);
}
public boolean equals(Equipa e)
{
if(this.nome == e.getNome())
return true;
else
return false;
}
public String getStringPilotos()
{
String s = new String();
for(Piloto p: this.pilotos)
s = (s + ", " + p.getNome());
return s;
}
public String toString()
{
return new String("Nome da equipa: " + nome + "; Categoria do carro: " + carro.getClass().getName() + "; Marca e modelo: " + carro.getMarca() + " " + carro.getModelo() + "; Pilotos: " + getStringPilotos())+"\n";
}
Implementing Serializable means that serialization is permitted, but not necessarily that it is possible. For it to work, everything referenced by Equipa must also be either primitive or Serializable (and so on, recursively). Is this the case?
Warning in the read function is the result of generics in java. You won't be able to suppress it, unless you use #SuppressWarnings("unchecked") to ignore it.
If you are sure you are reading an ArrayList<Equipa>, you can ignore it without any problem.
With the Equipa code, I can try to point to the Serializable problem: make sure that Carro and Piloto classes are also Serializables. You can add the code of theses classes if you are not sure.
The only type-safer way would be do a custom serialization, using writeObject(OutputStream) and readObjectInputStream say on a class ArrayListOfEquipa maybe using Equipa[] (ArrayList.toArray()).
Not really attractive, if the warning would be the only reason.
Is there any module in Java equivalent to python's shelve module? I need this to achieve dictionary like taxonomic data access. Dictionary-like taxonomic data access is a powerful way to save Python objects in a persistently easy access database format. I need something for the same purpose but in Java.
I also needed this, so I wrote one. A bit late, but maybe it'll help.
It doesn't implement the close() method, but just use sync() since it only hold the file open when actually writing it.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
public class Shelf extends HashMap<String, Object> {
private static final long serialVersionUID = 7127639025670585367L;
private final File file;
public static Shelf open(File file) {
Shelf shelf = null;
try {
if (file.exists()) {
final FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
shelf = (Shelf) ois.readObject();
ois.close();
fis.close();
} else {
shelf = new Shelf(file);
shelf.sync();
}
} catch (Exception e) {
// TODO: handle errors
}
return shelf;
}
// Shelf objects can only be created or opened by the Shelf.open method
private Shelf(File file) {
this.file = file;
sync();
}
public void sync() {
try {
final FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this);
oos.close();
fos.close();
} catch (Exception e) {
// TODO: handle errors
}
}
// Simple Test Case
public static void main(String[] args) {
Shelf shelf = Shelf.open(new File("test.obj"));
if (shelf.containsKey("test")) {
System.out.println(shelf.get("test"));
} else {
System.out.println("Creating test string. Run the program again.");
shelf.put("test", "Hello Shelf!");
shelf.sync();
}
}
}
You could use a serialisation library like Jackson which serialises POJOs to JSON.
An example from the tutorial:
Jackson's org.codehaus.jackson.map.ObjectMapper "just works" for
mapping JSON data into plain old Java objects ("POJOs"). For example,
given JSON data
{
"name" : { "first" : "Joe", "last" : "Sixpack" },
"gender" : "MALE",
"verified" : false,
"userImage" : "Rm9vYmFyIQ=="
}
It takes two lines of Java to turn it into a User instance:
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);
Where the User class looks something like this (from an entry on Tatu's blog):
public class User {
public enum Gender { MALE, FEMALE };
public static class Name {
private String _first, _last;
public String getFirst() { return _first; }
public String getLast() { return _last; }
public void setFirst(String s) { _first = s; }
public void setLast(String s) { _last = s; }
}
private Gender _gender;
private Name _name;
private boolean _isVerified;
private byte[] _userImage;
public Name getName() { return _name; }
public boolean isVerified() { return _isVerified; }
public Gender getGender() { return _gender; }
public byte[] getUserImage() { return _userImage; }
public void setName(Name n) { _name = n; }
public void setVerified(boolean b) { _isVerified = b; }
public void setGender(Gender g) { _gender = g; }
public void setUserImage(byte[] b) { _userImage = b; }
}