How to test AuthenticationPrincipal and getting an ID Token in Spring Security? - spring-security

I have the following LogoutResource class that returns an ID Token.
package com.mycompany.myapp.web.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* REST controller for managing global OIDC logout.
*/
#RestController
public class LogoutResource {
private ClientRegistration registration;
public LogoutResource(ClientRegistrationRepository registrations) {
this.registration = registrations.findByRegistrationId("oidc");
}
/**
* {#code POST /api/logout} : logout the current user.
*
* #param request the {#link HttpServletRequest}.
* #param idToken the ID token.
* #return the {#link ResponseEntity} with status {#code 200 (OK)} and a body with a global logout URL and ID token.
*/
#PostMapping("/api/logout")
public ResponseEntity<?> logout(HttpServletRequest request,
#AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {
String logoutUrl = this.registration.getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
Map<String, String> logoutDetails = new HashMap<>();
logoutDetails.put("logoutUrl", logoutUrl);
logoutDetails.put("idToken", idToken.getTokenValue());
request.getSession().invalidate();
return ResponseEntity.ok().body(logoutDetails);
}
}
This works, but I'd like to test it. I tried the following:
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.config.Constants;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {#link LogoutResource} REST controller.
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = JhipsterApp.class)
public class LogoutResourceIT {
#Autowired
private ClientRegistrationRepository registrations;
#Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
private final static String ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
"p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
"Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
"oqqUrg";
private MockMvc restLogoutMockMvc;
#Before
public void before() {
LogoutResource logoutResource = new LogoutResource(registrations);
this.restLogoutMockMvc = MockMvcBuilders.standaloneSetup(logoutResource)
.setMessageConverters(jacksonMessageConverter).build();
}
#Test
public void getLogoutInformation() throws Exception {
Map<String, Object> claims = new HashMap<>();
claims.put("groups", "ROLE_USER");
claims.put("sub", 123);
OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
Instant.now().plusSeconds(60), claims);
String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
restLogoutMockMvc.perform(post("/api/logout")
.with(authentication(createMockOAuth2AuthenticationToken(idToken))))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.logoutUrl").value(logoutUrl));
}
private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(OidcIdToken idToken) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
OidcUser user = new DefaultOidcUser(authorities, idToken);
return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
}
However, this results in the following error:
Caused by: java.lang.IllegalArgumentException: tokenValue cannot be empty
at org.springframework.util.Assert.hasText(Assert.java:284)
at org.springframework.security.oauth2.core.AbstractOAuth2Token.<init>(AbstractOAuth2Token.java:55)
at org.springframework.security.oauth2.core.oidc.OidcIdToken.<init>(OidcIdToken.java:53)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)
Does anyone know of a way to mock AuthenticationPrincipal and have it return a preset ID token?

Answer provided by Joe Grandja from the Spring Security Team:
The AuthenticationPrincipalArgumentResolver is not getting registered in your test.
NOTE: It automatically gets registered when the "full" spring-web-mvc is enabled, e.g #EnableWebMvc
However, in your #Before, you have:
MockMvcBuilders.standaloneSetup() - this does not initialize the full web-mvc infrastructure - only a subset
Try this instead:
MockMvcBuilders.webAppContextSetup(this.context) - this will register AuthenticationPrincipalArgumentResolver and your test should resolve the OidcIdToken.
I changed my test to the following and now everything passes. Thanks Joe!
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {#link LogoutResource} REST controller.
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = JhipsterApp.class)
public class LogoutResourceIT {
#Autowired
private ClientRegistrationRepository registrations;
#Autowired
private WebApplicationContext context;
private final static String ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
"p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
"Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
"oqqUrg";
private MockMvc restLogoutMockMvc;
#Before
public void before() throws Exception {
Map<String, Object> claims = new HashMap<>();
claims.put("groups", "ROLE_USER");
claims.put("sub", 123);
OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
Instant.now().plusSeconds(60), claims);
SecurityContextHolder.getContext().setAuthentication(authenticationToken(idToken));
SecurityContextHolderAwareRequestFilter authInjector = new SecurityContextHolderAwareRequestFilter();
authInjector.afterPropertiesSet();
this.restLogoutMockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
#Test
public void getLogoutInformation() throws Exception {
String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
restLogoutMockMvc.perform(post("/api/logout"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.logoutUrl").value(logoutUrl))
.andExpect(jsonPath("$.idToken").value(ID_TOKEN));
}
private OAuth2AuthenticationToken authenticationToken(OidcIdToken idToken) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
OidcUser user = new DefaultOidcUser(authorities, idToken);
return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
}

Related

Appium parallel test threadlocal

I am trying to run parallel test through selenium grid.
I know I have to use "thread local" for parallel execution,
but I have a problem with my code.
Cannot invoke "io.appium.java_client.android.AndroidDriver.findElementByAccessibilityId(String)" because "driver" is null
can you please solve it
package appiumset;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
public class _2_Deviceinfo {
public ThreadLocal<AppiumDriver> driver = new ThreadLocal<>();
public void setDriver(AppiumDriver driver) {
this.driver.set(driver);
}
public AppiumDriver getDriver() {
return this.driver.get();
}
#Parameters({"device", "apppackage", "activity","version","appiumServer" , "systemPort", "platformName"})
#BeforeMethod
public synchronized void deviceSetUp(String device, String apppackage, String activity, String version, String appiumServer, String systemPort, String platformName) throws InterruptedException, MalformedURLException {
System.out.println("****************************************");
System.out.println("Setting up device and desired capabilities");
DesiredCapabilities cap = new DesiredCapabilities();
URL url = new URL(appiumServer);
setDriver(new AndroidDriver<>(url, cap));
cap.setCapability(MobileCapabilityType.DEVICE_NAME, device);
cap.setCapability(MobileCapabilityType.UDID, device);
cap.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, systemPort);
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120);
cap.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
//cap.setCapability(MobileCapabilityType., BrowserType.ANDROID);
cap.setCapability(MobileCapabilityType.PLATFORM_VERSION, version);
cap.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, apppackage);
cap.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, activity);
cap.setCapability("automationName", "UiAutomator2");
cap.setCapability("noReset","false");
cap.setCapability("FullReset","true");
cap.setCapability("APP_WAIT_ACTIVITY", "*");
cap.setCapability("autowebview","false");
}
#AfterMethod
public void closeDriver() {
getDriver().quit();
}
}
I can't find the driver (AppiumDriver)
package appiumset;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
public class _3_Onboarding extends _1_Appstart {
#Test
public void onboarding() throws MalformedURLException, InterruptedException {
System.out.println("_3_Onboarding Start");
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();
System.out.println("next-done");
}
}
call getdriver() method of your class _2_Deviceinfo to your test class.
Appiumdriver<?> driver = getDriver();
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();

how to check if an issue has been exalated in Jira Scriptrunner, [Static type checking] - The variable [eventTypeManager] is undeclared

I would like to write some code to check if an event has been exalated in scriptrunner, I am using the following code but it seems that I have a compilation error: I am getting the error stating that [Static type checking] - The variable [eventTypeManager] is undeclared. I am importing the appropriate packages though, how can I fix this problem
import com.atlassian.jira.event.issue.AbstractIssueEventListener
import com.atlassian.jira.event.issue.IssueEvent
import com.atlassian.jira.event.type.EventType
import com.atlassian.jira.event.type.EventTypeManager
import com.atlassian.jira.*
import com.atlassian.jira.component.pico.ComponentManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class DefaultAccountListener extends AbstractIssueEventListener {
private final Logger LOG = LoggerFactory.getLogger(DefaultAccountListener)
private static final String EXALATED_EVENT_TYPE = "com.exalate.api.domain.trigger.EXALATED"
private static final String EXALATE_UPDATED_EVENT_TYPE = "com.exalate.api.domain.trigger.UPDATED"
#Override
void customEvent(IssueEvent event) {
Issue issue = event.issue
EventType eventType = eventTypeManager.getEventType(event.getEventTypeId())
LOG.debug("Custom event caught for issue ${issue.key}: type [${eventType.type}], name [${eventType.name}], nameKey [${eventType.nameKey}]")
if (eventType.name.equalsIgnoreCase(EXALATED_EVENT_TYPE)) {
LOG.debug("EXALATED event caught for issue ${issue.key}")
}
}
}

OAUTH error="access_denied", error_description="Error requesting access token." when trying to access tokens

the code that i wrote:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
#EnableOAuth2Client
#Configuration
public class OAuth2SecurityConfig {
private static Logger logger = LoggerFactory.getLogger(OAuth2SecurityConfig.class);
#Value("${tokenUrl}")
private String tokenUrl;
#Value("${oauthClientId}")
private String oauthClientId;
#Value("${oauthClientPassword}")
private String oauthClientPassword;
#Value("${oauthGrantType}")
private String oauthGrantType;
#Bean
protected OAuth2ProtectedResourceDetails resourceDetails() {
logger.info("inside resourceDetails");
ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
resourceDetails.setAccessTokenUri(tokenUrl);
resourceDetails.setClientId(oauthClientId);
resourceDetails.setClientSecret(oauthClientPassword);
resourceDetails.setGrantType(oauthGrantType);
logger.info("resourceDetails: "+ resourceDetails.toString());
logger.info("resourceDetails: "+ resourceDetails.getAccessTokenUri());
return resourceDetails;
}
#Bean
public OAuth2RestOperations restTemplateToken() {
logger.info("inside restTemplateToken");
AccessTokenRequest request = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resourceDetails(), new DefaultOAuth2ClientContext(request));
}
}
The file where I am accessing the tokens I have given this line to fetch it after autowiring OAuth2RestOperations :
#Autowired
private OAuth2RestOperations restTemplateToken;
inside Method....
OAuth2AccessToken accessToken = restTemplateToken.getAccessToken();
When i execute it I am getting error like :
error="access_denied", error_description="Error requesting access token."
Not sure why it is failing. Please help.
Thanks.

Cannot invoke "io.appium.java_client.android.AndroidDriver.manage()" because "this.driver" is null

I am new to Appium and just getting started, I would like to call methods from other classes by creating an object. but when I call methods it show "this.driver" is null. how to call methods from other class by creating object?? is it possible?? Noted that: I already use 'extends class', so I didn't use it in multiple classes.
//Here, I call methods from other classes......
import java.net.MalformedURLException;
import java.time.Duration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
//import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static java.time.Duration.ofSeconds;
import io.appium.java_client.touch.LongPressOptions;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
#Test(priority = 11)
public void IncompleteTask() {
String ser="Update For Testing";
Searching(ser);
AllMethods scr=new AllMethods(driver);
scr.Scroll();
//Scroll();
Point point1=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getCenter();
Point point2=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getLocation();
Swipping(point1,point2);
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_reAssign").click();
//driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/noButton").click();
String mass=driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/tvMessage").getText();
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
String mText="Are you sure you want to undo this Task?";
if(mass.contains(mText))
{
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
}
System.out.println("IncompleteTask Executed!");
driver.quit();
}
//Here is my allMethods class
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.support.PageFactory;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import java.io.IOException;
import java.lang.NullPointerException;
public class AllMethods {
public AndroidDriver<AndroidElement> driver;
public AllMethods(AndroidDriver driver)
{
PageFactory.initElements(driver, this);
}
public void searching(String ser) {
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_search").click();
driver.findElementById("android:id/search_src_text").sendKeys(ser);
driver.hideKeyboard();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void Scroll() throws NullPointerException
{
for(int i=0; i<3; i++)
{
Dimension dimension=driver.manage().window().getSize();
int start_x=(int) (dimension.width*0.5);
int start_y=(int) (dimension.height*0.2);
int end_x=(int) (dimension.width*0.5);
int end_y=(int) (dimension.height*0.8);
TouchAction tcD=new TouchAction(driver);
tcD.press(PointOption.point(start_x,
start_y)).waitAction(WaitOptions.waitOptions(Duration.ofSeconds(2)))
.moveTo(PointOption.point(end_x, end_y)).release().perform();
}
}
}
The methods in AllMethods class are referring to the driver which is not yet initialized. i.e they are referring to this driver :
public AndroidDriver<AndroidElement> driver;
You will need to add this.driver=driver inside AllMethods constructor, this will set the driver with the reference of the driver that is passed in the constructor.

Error:(73, 5) error: illegal start of expression

anyone can help me?
I'm amateur in android programming.
that's my code:
package com.example.aleta.dbapp;
/**
* Created by aleta on 24/07/2017.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class ForSpinner{
Connection connect;
PreparedStatement stmt;
ResultSet rs;
string srvr,dbn;
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.spinners);
srvr="DESKTOP-F27TAGV\\ALETAYEB_DB";
db="shop_db";
spinnerstate=(Spinner)
findViewById(R.id.spinnerstate);
connect=CONN;
String query="select Title from ostan";
connect=CONN;
stmt=connect.prepareStatement(query);
rs=stmt.executeQuery();
ArrayList<String> data=new ArrayList<String>();
while (rs.next()){
String id=rs.getString("ostan");
data.add(id);
}
String[] array=data.toArray(new String[0]);
ArrayAdapter NoCoreAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,data);
spinnerstate.setAdapter(NoCoreAdapter);
spinnerstate.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id){
String name=spinnerstate.getSelectedItem().toString();
Toast.makeText(ForSpinner.this,name,Toast.LENGTH_SHORT()).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
#SuppressLint("NewApi")
private Connection CONN(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy((policy));
Connection conn=null;
String ConnURL=null;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL="jdbc:jtds:sqlserver://" + srvr + ";"
+ "databaseName=" + dbn + ";Integrated security=true;";
conn=DriverManager.getConnection(ConnURL);
return conn;
}
}
}
but an error occurred :
Error:(73, 28) error: ';' expected
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 2.572 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console
how i can solve that?

Resources