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?
Related
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();
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.
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");
}
}
I am having an issue when mocking URL and HttpURLConnection class.
TestNG is being used as the testing framework because of a limitation that we have.
The test class looks like the following
package com.ericsson.msran.test.stability.environmentmanager.service.batc.restore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.entity.ContentType;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.ericsson.msran.test.stability.environmentmanager.service.Service;
import com.ericsson.msran.test.stability.environmentmanager.service.ServiceException;
import com.ericsson.msran.test.stability.environmentmanager.service.batc.BatCConfig;
import com.ericsson.msran.test.stability.environmentmanager.service.batc.BatCServiceException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
#PowerMockIgnore({ "org.apache.logging.log4j.*" })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ BatCConfig.class, Service.class })
public class RestoreSnapshotServiceTest extends PowerMockTestCase {
HttpURLConnection httpURLConnection;
URL mockedURL;
#BeforeClass
public void setUp() throws MalformedURLException, IOException {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(BatCConfig.class);
}
#Test
public void testRestoreSnapshot() throws Exception {
String jsonResponse = "{\"apiVersion\":\"0.1.0\",\"method\":\"restoreCampaignSnapshot\",\"params\":{\"campaignSnapshotId\":3,\"campaignName\":\"testCampaign3\"},\"data\":{\"newCampaignId\":607}}";
JsonObject response = new JsonParser().parse(jsonResponse).getAsJsonObject();
Mockito.when(BatCConfig.getBatCServiceUrl()).thenReturn(new URL("https://lte-iov.rnd.ki.sw.ericsson.se/batc/"));
mockedURL = PowerMockito.mock(URL.class);
httpURLConnection = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.whenNew(URL.class).withArguments("https://lte-iov.rnd.ki.sw.ericsson.se/batc/restoreCampaignSnapshot").thenReturn(mockedURL);
Mockito.when(mockedURL.openConnection()).thenReturn(httpURLConnection);
Mockito.when(httpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_GATEWAY);
Mockito.when(httpURLConnection.getContentType()).thenReturn(ContentType.APPLICATION_JSON.getMimeType());
Mockito.doNothing().when(httpURLConnection).connect();
Mockito.when(httpURLConnection.getOutputStream()).thenReturn(null);
Mockito.when(httpURLConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonResponse.getBytes()));
String name = RestoreSnapshotService.restoreSnapshot(3, "testCampaign4");
Assert.assertEquals(name, "testCampaign4");
}
}
When I test the real class (Service) in this case, the mock is not being used but instead the real object. Any help is appreciated!
The sample code under test looks like the following
protected static JsonObject callEndpoint(URL url, ServiceRequestMethod requestMethod, JsonObject requestBody)
throws ServiceException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(REQUEST_PROP_KEY, REQUEST_PROP_VAL);
connection.setConnectTimeout(REQUEST_TIMEOUT_MILLIS);
connection.setReadTimeout(REQUEST_TIMEOUT_MILLIS);
connection.setRequestMethod(requestMethod.name());
if (requestMethod == ServiceRequestMethod.POST) {
connection.setDoOutput(true);
}
connection.connect();
if (requestMethod == ServiceRequestMethod.POST) {
final OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();
}
final int status = connection.getResponseCode();
final String contentType = connection.getContentType();
log("Recieved response with status={} and ContentType={}", status, contentType);
if (HttpURLConnection.HTTP_OK == status && RESPONSE_TYPE_JSON.equals(contentType)) {
return mapResponse(connection.getInputStream());
} else {
throw new ServiceException("Response from service NOK, status=" + status);
}
} catch (IOException e) {
throw new ServiceException("Could not connect to service", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
I downloaded the Jester example code in Mahout, and tries to run it on jester dataset to see the evaluation results. the running is done successfully, but the console only has the results:
log4j:WARN No appenders could be found for logger (org.apache.mahout.cf.taste.impl.model.file.FileDataModel).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
I expect to see the evaluation score range from 0 to 10. any one can help me found out how to get the score?
I am using mahout-core-0.6.jar and the following is the code:
JesterDataModel.java:
package Jester;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import org.apache.mahout.cf.taste.example.grouplens.GroupLensDataModel;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.GenericDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericPreference;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.Preference;
import org.apache.mahout.common.iterator.FileLineIterator;
//import org.apache.mahout.cf.taste.impl.common.FileLineIterable;
public final class JesterDataModel extends FileDataModel {
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private long userBeingRead;
public JesterDataModel() throws IOException {
this(GroupLensDataModel.readResourceToTempFile("\\jester-data-1.csv"));
}
public JesterDataModel(File ratingsFile) throws IOException {
super(ratingsFile);
}
#Override
public void reload() {
userBeingRead = 0;
super.reload();
}
#Override
protected DataModel buildModel() throws IOException {
FastByIDMap<Collection<Preference>> data = new FastByIDMap<Collection<Preference>> ();
FileLineIterator iterator = new FileLineIterator(getDataFile(), false);
FastByIDMap<FastByIDMap<Long>> timestamps = new FastByIDMap<FastByIDMap<Long>>();
processFile(iterator, data, timestamps, false);
return new GenericDataModel(GenericDataModel.toDataMap(data, true));
}
#Override
protected void processLine(String line,
FastByIDMap<?> rawData,
FastByIDMap<FastByIDMap<Long>> timestamps,
boolean fromPriorData) {
FastByIDMap<Collection<Preference>> data = (FastByIDMap<Collection<Preference>>) rawData;
String[] jokePrefs = COMMA_PATTERN.split(line);
int count = Integer.parseInt(jokePrefs[0]);
Collection<Preference> prefs = Lists.newArrayListWithCapacity(count);
for (int itemID = 1; itemID < jokePrefs.length; itemID++) { // yes skip first one, just a count
String jokePref = jokePrefs[itemID];
if (!"99".equals(jokePref)) {
float jokePrefValue = Float.parseFloat(jokePref);
prefs.add(new GenericPreference(userBeingRead, itemID, jokePrefValue));
}
}
data.put(userBeingRead, prefs);
userBeingRead++;
}
}
JesterRecommenderEvaluatorRunner.java
package Jester;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.eval.RecommenderEvaluator;
import org.apache.mahout.cf.taste.impl.eval.AverageAbsoluteDifferenceRecommenderEvaluator;
import org.apache.mahout.cf.taste.model.DataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
public final class JesterRecommenderEvaluatorRunner {
private static final Logger log = LoggerFactory.getLogger(JesterRecommenderEvaluatorRunner.class);
private JesterRecommenderEvaluatorRunner() {
// do nothing
}
public static void main(String... args) throws IOException, TasteException {
RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
DataModel model = new JesterDataModel();
double evaluation = evaluator.evaluate(new JesterRecommenderBuilder(),
null,
model,
0.9,
1.0);
log.info(String.valueOf(evaluation));
}
}
Mahout 0.7 is old, and 0.6 is very old. Use at least 0.7, or better, later from SVN.
I think the problem is exactly what you identified: you don't have any slf4j bindings in your classpath. If you use the ".job" files in Mahout you will have all dependencies packages. Then you will actually see output.