Syntax error on token "start" , identifier expected after this token [duplicate] - java

This question already has answers here:
Method calls inside a Java class return an "identifier expected after this token" error
(8 answers)
Closed 1 year ago.
I've been trying to create an agent thanks to Jade on Java with this code:
import jade.core.ProfileImpl;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
public class Agents {
jade.core.Runtime rt= jade.core.Runtime.instance();
ProfileImpl pMain= new ProfileImpl();
AgentContainer mc = rt.createMainContainer(pMain);
AgentController rma= mc.createNewAgent("rma", "jade.tools.rma.rma", null);
rma.start();
}
I keep getting the error "Syntax error on token "start" , identifier expected after this token" and I cannot understand why.

By not going into finding problems with your code, I suggest to use the code below to solve your error.
Initialization code for agent and adding to the container
package package.se.samplejade;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;
public class LaunchAgents {
private static final String AGENT_CLASS_STRING ="package.se.samplejade.SampleAgent";
private static final String AGENTNAME_STRING = "sampleAgent";
public static void main(String[] args) {
LaunchAgents LaunchAgents = new LaunchAgents();
LaunchAgents.initilizeAgent();
}
/**
* Creates a new agent and adds it to the container
*
* #param
* #return true or false
*/
public boolean initilizeAgent() {
AgentController agentcontroller = null;
Object[] initObjects = new Object[2];
initObjects[0] = new Object(); // add any object needed to initialize the agent
initObjects[1] = new Object();
try {
agentcontroller = Container.getController().createNewAgent(AGENTNAME_STRING, AGENT_CLASS_STRING,
initObjects);
agentcontroller.start();
return true;
} catch (StaleProxyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
The JADE container initialization
package.se.samplejade ;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.wrapper.ContainerController;
public final class Container {
// get a JADE runtime
private static jade.core.Runtime runtime = jade.core.Runtime.instance();
// Create a profile, where the launch arguments are stored
private static Profile profile2 = new ProfileImpl();
private static Profile profile = new ProfileImpl();
// create the Main-container
private static ContainerController mainContainer = null;
private static ContainerController containerController = null;
/**
* Returns the path of the container to the JADE agents
*/
public synchronized static ContainerController getController() {
// create the Main-container
if (mainContainer == null) {
profile.setParameter(Profile.CONTAINER_NAME, "Container");
profile.setParameter(Profile.GUI, "true");
mainContainer = runtime.createMainContainer(profile2);
containerController = runtime.createAgentContainer(profile);
}
return containerController;
}
}
The agents code
package.se.samplejade;
import jade.core.Agent;
public class SampleAgent extends Agent {
#Override
protected void setup() {
//Put your agent initialization code with the objects passed in the initialization
}
}

Related

How can i check the proxy settings done by 'System.setProperty' in Java?

i'm developing an Java application that will be used to launch some Test Automation scripts on dedicated environment.
It is required to set also the proxy when necessary.
I developed a class that will be used to configure the proxy settings once a properties read from external contains the flag 'ENABLE_PROXY' equals 'True'.
Following is my snippet code:
package proxy;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import org.apache.commons.lang3.exception.ExceptionUtils;
public class ProxyConfiguration {
private static String proxyHost;
private static String proxyPort; //80 if it isn't provided
private static String nonProxyHosts;
private static String protocolType;
public static boolean flagProxy;
//Set method used to read the flag Proxy
public static boolean isProxyEnabled(Properties myPropertiesFile) {
flagProxy = Boolean.parseBoolean(myPropertiesFile.getProperty("ENABLE_PROXY").toLowerCase());
return flagProxy;
}
public static String getProxyHost() {
return proxyHost;
}
//Set method used to read the Proxy host from properties
public static void setProxyHost(Properties myPropertiesFile) {
ProxyConfiguration.proxyHost = myPropertiesFile.getProperty("PROXY_HOST");
}
public static String getProxyPort() {
return proxyPort;
}
//Set method used to read the Proxy port from properties
public static void setProxyPort(Properties myPropertiesFile) {
ProxyConfiguration.proxyPort = myPropertiesFile.getProperty("PROXY_PORT");
}
public static String getNonProxyHosts() {
return nonProxyHosts.replace(",", "|");
}
//Set method used to read the exception from properties
public static void setNonProxyHosts(Properties myPropertiesFile) {
ProxyConfiguration.nonProxyHosts = myPropertiesFile.getProperty("PROXY_EXCEPTION");
}
public static String getProtocolType() {
return protocolType;
}
//Set method used to read the exception from properties
public static void setProtocolType(Properties myPropertiesFile) {
ProxyConfiguration.protocolType = myPropertiesFile.getProperty("PROTOCOL_TYPE");
}
//Method used to set the Proxy settings on system
public static void setProxyConfiguration(Properties myPropertiesFile) {
try {
ProxyConfiguration.setProtocolType(myPropertiesFile);
ProxyConfiguration.setProxyHost(myPropertiesFile);
ProxyConfiguration.setProxyPort(myPropertiesFile);
ProxyConfiguration.setNonProxyHosts(myPropertiesFile);
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty(ProxyConfiguration.getProtocolType() +".proxyHost", ProxyConfiguration.getProxyHost());
System.setProperty(ProxyConfiguration.getProtocolType() +".proxyPort", ProxyConfiguration.getProxyPort());
boolean exceptions = ProxyConfiguration.getNonProxyHosts().isEmpty();
if(!exceptions) {
System.setProperty(ProxyConfiguration.getProtocolType() +".nonProxyHosts", ProxyConfiguration.getNonProxyHosts());
}
try {
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();
//return true;
} catch (Exception e) {
//return false;
}
} catch (Exception e) {
System.err.println("Si è verificato un errore nella setProxyConfiguration: ");
String exc = ExceptionUtils.getStackTrace(e);
System.err.println(exc);
System.exit(-1);
}
}
}
How can i check if the proxy settings are set correctly?
I tried also to used the command prompt of my local machine and launch the follwing command:
netsh winhttp show proxy
but i receive:
Current WinHTTP proxy settings:
Direct access (no proxy server).
The properties read are:
PROTOCOL_TYPE=http
PROXY_HOST=webcache.mydomain.com (it is an example found on Java Networking)
PROXY_PORT=8080
PROXY_EXCEPTION=
Thanks for supporting!

Why have to initialize all variables again in Parameterized JUnitTest although they are intialize in #Before method or at class level

I have one parametrized Junit test in my class. If I initialize all objects used in this test in #Before method they are not accessible in this parametrized Junit test and it throws NUllPointer Exception, due to which I have to initialize all theses objects again in parametrized Junit test. Why is this behavior ?
This is my parametrized Junit test where I have initialize all objects again and even I need to mock them also again.
#ParameterizedTest
#CsvSource({"1,5550,true","1,0,false","0,5550,false"})
public void itemsAvailableValidatorTest(int kioskId, int siteNbr,Boolean expected) throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
ItemAvailableRequestValidator itemAvailableRequestValidator = new ItemAvailableRequestValidator();
context = Mockito.mock(ConstraintValidatorContext.class);
builder = Mockito.mock(ConstraintValidatorContext.ConstraintViolationBuilder.class);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()))
.thenReturn(builder);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()).addConstraintViolation())
.thenReturn(context);
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
ndcs.add("1234");
famIds.add(1234);
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
request.setKioskId(kioskId);
request.setQty(1);
request.setSiteNbr(siteNbr);
request.setRxFillId(null); // call the custom validator method and verify the response
assertEquals(expected, itemAvailableRequestValidator.isValid(request, context));
}
If I initialize the Following objects of this test in #Before method or at class level this test fails and throughs NullPointer Exception
ItemAvailableRequest request = new ItemAvailableRequest();
ItemAvailableRequestValidator itemAvailableRequestValidator = new ItemAvailableRequestValidator();
context = Mockito.mock(ConstraintValidatorContext.class);
builder = Mockito.mock(ConstraintValidatorContext.ConstraintViolationBuilder.class);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()))
.thenReturn(builder);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()).addConstraintViolation())
.thenReturn(context);
Why the objects initialized in Before method or at class level are not accessible in #parametrized JunitTest ? and why they need to be specifically initialized inside #paramterized Junit test curly brackets.
Here is the code for whole class
package com.walmart.rxkioskinventory.validator;
import com.walmart.rxkioskinventory.model.request.ItemAvailableRequest;
import com.walmart.rxkioskinventory.model.validator.ItemAvailableRequestValidator;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ItemAvailableRequestValidatorTest {
#InjectMocks
ItemAvailableRequestValidator itemAvailableRequestValidator;
private ItemAvailableRequest request;
private ConstraintValidatorContext context;
private ConstraintValidatorContext.ConstraintViolationBuilder builder;
/*
good request initializer
*/
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
// mock the context
context = Mockito.mock(ConstraintValidatorContext.class);
context = Mockito.mock(ConstraintValidatorContext.class);
builder = Mockito.mock(ConstraintValidatorContext.ConstraintViolationBuilder.class);
// context.buildConstraintViolationWithTemplate returns
// ConstraintValidatorContext.ConstraintViolationBuilder
// so we mock that too as you will be calling one of it's methods
builder = Mockito.mock(ConstraintValidatorContext.ConstraintViolationBuilder.class);
// when the context.buildConstraintViolationWithTemplate is called,
// the mock should return the builder.
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()))
.thenReturn(builder);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()).addConstraintViolation())
.thenReturn(context);
request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
ndcs.add("1234");
famIds.add(1234);
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
// error for binding the request
Errors errors = new BeanPropertyBindingResult(request, "request");
}
/*
test to verify the valid request with all valid request params
*/
#Test
public void itemsAvailableValidatorSuccessTest() throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
ndcs.add("1234");
famIds.add(1234);
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
request.setKioskId(1);
request.setQty(1);
request.setSiteNbr(5550);
request.setRxFillId(1);
// call the custom validator method and verify the response
assertEquals(true, itemAvailableRequestValidator.isValid(request, context));
}
/**
*Test to verify response when request is null
*/
#Test
public void itemsAvailableValidatorNullRequestTest() {
ItemAvailableRequest request = null;
// call the custom validator method and verify the response
assertEquals(false, itemAvailableRequestValidator.isValid(request, context));
}
/**
*Test to verify response when quantity is invalid.
*/
#Test
public void itemsAvailableValidatorInvalidQuantityTest() {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = null;
ndcs.add("1234");
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
request.setKioskId(1);
request.setQty(0.5);
request.setSiteNbr(5550);
request.setRxFillId(null);
// call the custom validator method and verify the response
assertEquals(false, itemAvailableRequestValidator.isValid(request, context));
}
/**
* Test to verify response when SiteNbr is invalid
* #param kioskId it depicts kiosk id
* #param siteNbr it depicts site nbr
* #throws Exception it throws exception
*/
#ParameterizedTest
#CsvSource({"1,5550,true","1,0,false","0,5550,false"})
public void itemsAvailableValidatorTest(int kioskId, int siteNbr,Boolean expected) throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
ItemAvailableRequestValidator itemAvailableRequestValidator = new ItemAvailableRequestValidator();
context = Mockito.mock(ConstraintValidatorContext.class);
builder = Mockito.mock(ConstraintValidatorContext.ConstraintViolationBuilder.class);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()))
.thenReturn(builder);
Mockito.when(context.buildConstraintViolationWithTemplate(Mockito.anyString()).addConstraintViolation())
.thenReturn(context);
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
ndcs.add("1234");
famIds.add(1234);
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
request.setKioskId(kioskId);
request.setQty(1);
request.setSiteNbr(siteNbr);
request.setRxFillId(null); // call the custom validator method and verify the response
assertEquals(expected, itemAvailableRequestValidator.isValid(request, context));
}
/*
test to verify that if rxFillId is 0 then request is not valid
*/
#Test
public void itemsAvailableValidatorFillIdZeroFailureTest() throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
ndcs.add("1234");
famIds.add(1234);
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
request.setKioskId(1);
request.setQty(1);
request.setSiteNbr(5550);
request.setRxFillId(0);
// call the custom validator method and verify the response
assertEquals(false, itemAvailableRequestValidator.isValid(request, context));
}
/*
test to verify the valid request with ndc null and required famId
*/
#Test
public void ItemsAvailableValidatorNullNdcSuccessTest() throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = null;
List<Integer> famIds = new ArrayList<>();
famIds.add(1234);
// set fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
request.setQty(1);
request.setSiteNbr(5550);
request.setKioskId(5550);
// call the custom validator method and verify the response
assertTrue(itemAvailableRequestValidator.isValid(request, context));
}
/*
test to verify the fail request with params to be null
*/
#Test
public void itemsAvailableValidatorNullFailureTest() throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = null;
List<Integer> famIds = null;
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
// call the custom validator method and verify the response
assertEquals(false, itemAvailableRequestValidator.isValid(request, context));
}
/*
test to verify the valid request with empty ndc and valid famId
*/
#Test
public void itemsAvailableValidatorEmptyNdcSuccessTest() throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
famIds.add(1234);
request.setQty(1);
request.setSiteNbr(5550);
request.setKioskId(5550);
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
// call the custom validator method and verify the response
assertTrue(itemAvailableRequestValidator.isValid(request, context));
}
/*
test to verify the fail request with all params to be empty
*/
#Test
public void ItemsAvailableValidatorEmptyFailureTest() throws Exception {
ItemAvailableRequest request = new ItemAvailableRequest();
// set ndc gpi and famId
List<String> ndcs = new ArrayList<>();
List<Integer> famIds = new ArrayList<>();
// set goodRequest fields
request.setNdc(ndcs);
request.setMdsFamId(famIds);
// call the custom validator method and verify the response
assertEquals(false, itemAvailableRequestValidator.isValid(request, context));
}
}
You are mixing JUnit 4 org.junit.Before;, org.junit.Test and JUnit 5 org.junit.jupiter.*. This is causing the problems that you have.
#ParameterizedTest is from JUnit 5. So I suggest to use #BeforeEach and #BeforeAll and org.junit.jupiter.api.Test for #Test. Basically, drop all JUnit imports that are NOT org.junit.jupiter.* including the org.junit.Assert.*.
Here is one example that works with JUnit 5 and it uses #BeforeAll, #ParameterizedTest, #MethodSource, and #Test
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ParameterizedExampleTest {
private final static String workgroup = "reporting";
private final static String region = "eu-central-1";
private final static String credentialsProviderArguments = "reporting";
private Values values;
private static Stream<Arguments> credentialProvidersWithCorrectArguments() {
String webTokenProvider = "com.amazonaws.auth.WebIdentityTokenCredentialsProvider";
String profileProvider = "com.amazonaws.auth.profile.ProfileCredentialsProvider";
return Stream.of(
Arguments.of(
webTokenProvider,
"jdbc:awsathena://AwsRegion=" + region + ";AwsCredentialsProviderClass=" + webTokenProvider + ";" +
"Workgroup=" + workgroup + ";LogLevel=6;"
),
Arguments.of(
profileProvider,
"jdbc:awsathena://AwsRegion=" + region + ";AwsCredentialsProviderClass=" + profileProvider + ";" +
"AwsCredentialsProviderArguments=" + credentialsProviderArguments + ";Workgroup=" + workgroup +
";LogLevel=6;"
)
);
}
#BeforeAll
public void setup() {
values = new Values();
values.setAthenaRegion(region);
values.setWorkgroup(workgroup);
values.setDebugEnabled(true);
values.setCredentialsProviderArguments(credentialsProviderArguments);
}
#ParameterizedTest
#MethodSource("credentialProvidersWithCorrectArguments")
void credentialsProviderHasCorrectCredentialsArguments(String credentialsProviderClass, String expected) {
values.setCredentialsProviderClass(credentialsProviderClass);
assertEquals(expected, values.getJdbcUrl());
}
#Test
void wrongProviderClassThrowsException() {
String credentialsProviderClass = "com.amazonaws.auth.WrongCredentialsProvider";
values.setCredentialsProviderClass(credentialsProviderClass);
try {
values.getJdbcUrl();
fail("An exception should be thrown to this method.");
} catch (Exception e) {
assertTrue(e.getMessage().contains("AWS credential class does not exist"));
}
}
}
Class being tested:
public class Values {
private String athenaRegion;
private String credentialsProviderClass;
private String credentialsProviderArguments;
private String jdbcDriverClass;
private String databaseSchema;
private String workgroup;
private boolean debugEnabled;
public String getJdbcUrl() {
String athenaJdbcUrl = "jdbc:awsathena://AwsRegion=" + athenaRegion +
";AwsCredentialsProviderClass=" + credentialsProviderClass +
(isProfileCredentialsProvider() ? ";AwsCredentialsProviderArguments=" + credentialsProviderArguments : "") +
";Workgroup=" + workgroup +
(debugEnabled ? ";LogLevel=6;" : ";");
LOG.debug("Athena connection URL: {}", athenaJdbcUrl);
return athenaJdbcUrl;
}
private boolean isProfileCredentialsProvider() {
try {
return (Class.forName(credentialsProviderClass).isAssignableFrom(ProfileCredentialsProvider.class));
} catch (ClassNotFoundException e) {
throw new Exception("AWS credential class does not exist", e);
}
}
// add GETTERS AND SETTERS ...
}

I have a problem with the java SSHClient class, specifically the Expect method does not return data as espected, what could be happening?

I have used the SSHClient class of java to connect to a Juniper router, when entering the console in the putty console it returns the result without problem, but when doing it from the Java code it does not save what is returned by the command, or does not print it, Could you tell me what to do?
I share the ssh class that I am using to guide you in case you encounter any problems:
package com.mycompany;
import static net.sf.expectit.matcher.Matchers.contains;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Shell;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;
public class sshj {
/**
* Launch Commands to Provisioning
*
* #param host
* #param port
* #param user
* #param password
* #param commands
* #param splitBy
* #return result
*/
public static String launchCommands(String host, Integer port, String user, String password, String commands,
String commandsSplitBy, String expectSplitBy, Integer timeoutInSeconds) {
String result = "";
StringBuilder wholeBuffer = new StringBuilder();
SSHClient mSSSHClient = new SSHClient();
mSSSHClient.addHostKeyVerifier(new PromiscuousVerifier());
Session mSession = null;
Shell mShell = null;
Expect mExpect = null;
String[] splitCommands = commands.split(commandsSplitBy);
try {
mSSSHClient.connect(host, port);
mSSSHClient.authPassword(user, password);
mSession = mSSSHClient.startSession();
mShell = mSession.startShell();
mExpect = new ExpectBuilder()
.withOutput(mShell.getOutputStream())
.withInputs(mShell.getInputStream())
.withEchoInput(wholeBuffer)
.withEchoOutput(wholeBuffer)
// .withEchoInput(System.out)
// .withEchoOutput(System.err)
.withExceptionOnFailure()
.withTimeout(timeoutInSeconds, TimeUnit.SECONDS).build();
// When expectSplitBy is equals to ""
if ("".equalsIgnoreCase(expectSplitBy)) {
for (String commandExpect : splitCommands) {
mExpect.sendLine(commandExpect);
}
} else { // When expectSplitBy is not equals to ""
for (String commandExpect : splitCommands) {
String[] commandExpectSplit = commandExpect.split(expectSplitBy);
mExpect.sendLine(commandExpectSplit[0]);
mExpect.expect(contains(commandExpectSplit[1]));
}
}
mShell.close();
mSession.close();
mSSSHClient.disconnect();
result = wholeBuffer.toString();
} catch (IOException e) {
result = wholeBuffer.toString().concat(" The Exception is> ").concat(e.toString());
e.printStackTrace();
try {
mExpect.sendLine("exit");
mShell.close();
mSession.close();
mSSSHClient.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return result;
}
}
I found the problem, is that the command sent contains some strange characters at the beginning that look like a blank space, and I could eliminate them and the functionality of the class is executed without problem.
I tagged mule because it's where I'm working with this class, which I know is from a third party, that's why I shared all the code so you could do tests. I am very sorry if you do not find my question clear.

How to create the version and get the details of any version of specific project using JIRA REST CLIENT JAVA in groovy?

I am trying to create the version in JIRA for specific project.Below is my code.I am able to connect the JIRA successfully through JIRA REST CLIENT JAVA java libraries but now want to achieve the get the information of any version,createversion few more actions.
import com.atlassian.jira.rest.client.api.JiraRestClient
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
//import com.atlassian.jira.rest.client.api.domain.User
import com.atlassian.jira.rest.client.api.domain.Version
//import com.atlassian.jira.rest.client.api.domain.input.VersionInput
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
class Jira {
private static final String JIRA_URL = "https://jira.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDE"
private static final String JIRA_ADMIN_PASSWORD = "xxxxxx"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
// client.withCloseable {
// it.projectClient.getProject("ABCD").claim().versions.each { println it }
// }
// Invoke the JRJC Client
//Promise<User> promise = client.getUserClient().getUser(JIRA_ADMIN_USERNAME)
//User user = promise.claim()
Promise<Version> promise = client.getVersionRestClient().getVersion(1234)
//Version version = promise.claim()
// Print the result
System.out.println(String.format("Your user's email address is: %s\r\n", user.getEmailAddress()))
}
}
I am able to do some task like to get the email address of any userid.I am trying this in groovy
package com.temp.jira
import com.atlassian.jira.rest.client.api.JiraRestClient
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
import com.atlassian.jira.rest.client.api.domain.BasicProject
import com.atlassian.jira.rest.client.api.domain.Issue
import com.atlassian.jira.rest.client.api.domain.SearchResult
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
/**
* Created on 7/21/2017.
*/
class Test {
private static final String JIRA_URL = "https://jira.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDEF"
private static final String JIRA_ADMIN_PASSWORD = "*****"
private static final String JIRA_PROJECT = "ABCD"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
for (BasicProject project : client.getProjectClient().getProject(JIRA_PROJECT).claim()) {
System.out.println(project.getKey() + ": " + project.getName())
}
Promise<SearchResult> searchJqlPromise = client.getSearchClient().searchJql("project = $JIRA_PROJECT AND status in (Closed, Completed, Resolved) ORDER BY assignee, resolutiondate");
for (Issue issue : searchJqlPromise.claim().getIssues()) {
System.out.println(issue.getId())
}
// Done
System.out.println("Example complete. Now exiting.")
System.exit(0)
}
}
Stick to the jira rest client api, since you have a typed access provided from the creator o fJira.
Excerpt from my working Groovy code:
/**
* Retrieves the latest unreleased version for the given project.
* #param projectId Given project
* #return latest unreleased version
*/
private Version getVersion(String projectId)
{
def project = restClient.projectClient.getProject(projectId).claim()
def unreleasedVersions = project
.getVersions()
.findAll { version ->
version.released == false
}
if (unreleasedVersions.size() != 1) {
throw new RuntimeException('There are zero or more unreleased versions.')
}
unreleasedVersions.get(0)
}
/**
* Creates a new, undeployed version for the given project.
* #param projectId Given project
*/
private void createVersion(String projectId)
{
def versionInputBuilder = new VersionInputBuilder(projectId)
versionInputBuilder.released = false
versionInputBuilder.name = incrementVersion(capturedVersion.name)
versionInputBuilder.description = 'Bugfixing'
versionInputBuilder.startDate = DateTime.now()
def promise = restClient.versionRestClient.createVersion(versionInputBuilder.build())
trackCompletion(promise)
}
What I don't have in my code is get a certain version, but your commented code should work when you change the data type of the version to string.
I created the script in below way and able to create,update and delete the version
import com.atlassian.jira.rest.client.api.JiraRestClient
import com.atlassian.jira.rest.client.api.VersionRestClient
import com.atlassian.jira.rest.client.api.domain.Version
import com.atlassian.jira.rest.client.api.domain.input.VersionInput
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
import org.codehaus.jettison.json.JSONException
import org.joda.time.DateTime
import java.util.concurrent.ExecutionException
class VersionClient {
private static final String JIRA_URL = "https://jira.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDEF"
private static final String JIRA_ADMIN_PASSWORD = "******"
private static final String JIRA_PROJECT = "TEST"
static void main(String[] args)
throws URISyntaxException, InterruptedException, ExecutionException, JSONException {
// Initialize REST Client
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
final URI uri = new URI("$JIRA_URL")
final JiraRestClient jiraRestClient = factory.createWithBasicHttpAuthentication(uri, "$JIRA_ADMIN_USERNAME", "$JIRA_ADMIN_PASSWORD")
// Get specific client instances
VersionRestClient versionClient = jiraRestClient.getVersionRestClient()
// Create Version
VersionInput versionInput = new VersionInput("$JIRA_PROJECT", "TEST 1.2.8", "Test Version", new DateTime(), false, false)
Promise<Version> version = versionClient.createVersion(versionInput)
Version versionObj = version.get()
System.out.println("Created Version:" + versionObj.getName())
// Invoke the JRJC Client
Promise<Version> promise = versionClient.getVersion(versionObj.getSelf())
Version versionid = promise.claim()
// Print the result
System.out.println(String.format("Version id is: %s\r\n", versionid.getId() + " and URI:" + versionid.getSelf()))
// Release Version using Update
versionClient.updateVersion(versionid.getSelf(),new VersionInput("$JIRA_PROJECT", "TEST 1.2.8", "Test Version", new DateTime(), false, true))
// Delete the Version
versionClient.removeVersion(versionid.getSelf(), null, null).claim()
System.out.println("Deleted Version")
}
}

Simple URI and local path use in MediaPlayer-javaFX

I have the following code to display the spectrum of audio.But it uses URI.But how to use simple paths like C:/abc/asas.wav ...or something?Any idea?
It gives me Exception when i use local paths:
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.access$000(Unknown Source)
at com.sun.javafx.application.LauncherImpl$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
Code:
package chartaudiobar;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.media.AudioSpectrumListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
public class ChartAudioBar extends Application {
private XYChart.Data<String, Number>[] series1Data;
private AudioSpectrumListener audioSpectrumListener;
private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");
private static MediaPlayer audioMediaPlayer;
private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().add(createChart());
audioSpectrumListener = new AudioSpectrumListener() {
#Override public void spectrumDataUpdate(double timestamp, double duration,
float[] magnitudes, float[] phases) {
for (int i = 0; i < series1Data.length; i++) {
series1Data[i].setYValue(magnitudes[i] + 60);
}
}
};
}
public void play() {
this.startAudio();
}
#Override public void stop() {
this.stopAudio();
}
protected BarChart<String, Number> createChart() {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis(0,50,10);
final BarChart<String,Number> bc = new BarChart<String,Number>(xAxis,yAxis);
bc.setId("barAudioDemo");
bc.setLegendVisible(false);
bc.setAnimated(false);
bc.setBarGap(0);
bc.setCategoryGap(1);
bc.setVerticalGridLinesVisible(false);
// setup chart
bc.setTitle("Live Audio Spectrum Data");
xAxis.setLabel("Frequency Bands");
yAxis.setLabel("Magnitudes");
yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis,null,"dB"));
// add starting data
XYChart.Series<String,Number> series1 = new XYChart.Series<String,Number>();
series1.setName("Data Series 1");
//noinspection unchecked
series1Data = new XYChart.Data[128];
String[] categories = new String[128];
for (int i=0; i<series1Data.length; i++) {
categories[i] = Integer.toString(i+1);
series1Data[i] = new XYChart.Data<String,Number>(categories[i],50);
series1.getData().add(series1Data[i]);
}
bc.getData().add(series1);
return bc;
}
private void startAudio() {
if (PLAY_AUDIO) {
getAudioMediaPlayer().setAudioSpectrumListener(audioSpectrumListener);
getAudioMediaPlayer().play();
}
}
private void stopAudio() {
if (getAudioMediaPlayer().getAudioSpectrumListener() == audioSpectrumListener) {
getAudioMediaPlayer().pause();
}
}
private static MediaPlayer getAudioMediaPlayer() {
if (audioMediaPlayer == null) {
Media audioMedia = new Media(AUDIO_URI);
audioMediaPlayer = new MediaPlayer(audioMedia);
}
return audioMediaPlayer;
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) { launch(args); }
}
So how to use local paths here?
I had the same problem, i used this:
File file = new File("C:\\abc\\asas.wav");
audio = new Media(file.toURI().toURL().toString());
audioMediaPlayer = new MediaPlayer(audio);
You can convert path to URI by adding protocol
C:/abc/asas.wav will be file:/C:/abc/asas.wav in Your example
It’s 4 years after Jyoti Shaw posted this question, how to use a local music file in class ChartAudioBar. Wafu has the answer on his webpage https://osu.ppy.sh/forum/p/4629060 Look about halfway down on the page, under his heading “Frequency spectrum” and click on “Code” to see the source code.
Wafu’s solution is similar to that of Sam de Meyer in his answer above.
//We don't need this line, because we need to use a local music file.
//private static final String AUDIO_URI = System.getProperty("demo.audio.url","http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv");
private static MediaPlayer audioMediaPlayer;
//We don't need this as well as it's equally useless as previous thing.
//private static final boolean PLAY_AUDIO = Boolean.parseBoolean(System.getProperty("demo.play.audio","true"));
//We anyway need output of the default chart, so let's say we'll put it to file data.txt, hence the 'import java.io.File' needs to be added to imports.
private static File filedata = new File("data.txt");
// *****************************************************************************
private static MediaPlayer getAudioMediaPlayer() {
if (audioMediaPlayer == null) {
//We need code below, but I commented it anyway to show the difference, we need a local file, so this won't work.
//Media audioMedia = new Media(AUDIO_URI);
//So we create a local file, for example mp3.mp3 in current folder, it can be anything you want.
//File audiofile = new File("mp3.mp3");
File audiofile = new File("C:/music/SummerMix.mp3");
//Now we need to make audioMedia as it was previously - So it needs to be URI, which .toURI() ensures easily, but as well as that, it needs a string URI, so .toString() will ensure this.
Media audioMedia = new Media(audiofile.toURI().toString());
audioMediaPlayer = new MediaPlayer(audioMedia);
}
return audioMediaPlayer;
}

Categories

Resources