Replacing Fragments correctly within ViewPager - replace

I'am trying to replace a fragment within a view, but don't succeed yet.
I have the following classes. First my PagerAdapter:
package com.example.tab1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class SectionsPagerAdapter extends FragmentPagerAdapter {
static final int NUM_ITEMS = 3;
private final FragmentManager mFragmentManager;
private Fragment mFragmentAtPos0;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager = fm;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
mFragmentAtPos0= new testFragment();
args.putInt(testFragment.ARG_SECTION_NUMBER, position + 1);
mFragmentAtPos0.setArguments(args);
return mFragmentAtPos0;
}
#Override
public int getItemPosition(Object object) {
return 0;
}
#Override
// liefert die Anzahl der Tabs
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
// return getString(R.string.title_section1).toUpperCase();
// return
// Resources.getSystem().getString(R.string.title_section1).toUpperCase();
return "Suche".toUpperCase();
case 1:
// return getString(R.string.title_section2).toUpperCase();
// return
// Resources.getSystem().getString(R.string.title_section2).toUpperCase();
return "Ergebnis".toUpperCase();
case 2:
// return
// Resources.getSystem().getString(R.string.title_section3).toUpperCase();
return "Optionen".toUpperCase();
}
return null;
}
}
Secondly my My DatePickerFragment:
package com.example.tab1;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class DatePickerFragment extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public static DatePickerFragment newInstance() {
DatePickerFragment f = new DatePickerFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Log.d("DEBUG", "onCreateView");
return inflater.inflate(R.layout.datepickerfrag, container, false);
}
}
And Finally my MainActivity, where I activate the change in the method onClickSearch, which is a method from an interface in my first Fragment, which is shown when the app is started.
package com.example.tab1;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener,testFragment.ButtonListenerS{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections
// of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab.
// We can also use ActionBar.Tab#select() to do this if we have a
// reference to the
// Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
actionBar.selectTab(actionBar.getTabAt(0));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/*
* Implementierung des "Suchbuttons" (non-Javadoc)
* Interaktion zwischen testFragment und MainActivity
*/
public void OnclickSearchS() {
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.pager,DatePickerFragment.newInstance());
ft.commit();
//mViewPager.setCurrentItem(1);
}
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the primary sections of the app.
*/
}
When the application is running, I push the button the first time and nothing happens, when i do this again secondly, I see an empty fragment and get an error afterwards:
07-30 21:20:17.800: W/dalvikvm(32553): threadid=1: thread exiting with uncaught exception (group=0x40c671f8)
07-30 21:20:17.805: E/AndroidRuntime(32553): FATAL EXCEPTION: main
07-30 21:20:17.805: E/AndroidRuntime(32553): java.lang.NullPointerException
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.support.v4.app.Fragment.setUserVisibleHint(Fragment.java:750)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.support.v4.view.ViewPager.populate(ViewPager.java:893)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.support.v4.view.ViewPager.populate(ViewPager.java:772)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1539)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:1663)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1631)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1963)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1690)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1963)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1690)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1963)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1690)
07-30 21:20:17.805: E/AndroidRuntime(32553): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2063)
07-30 21:20:17.805: E/AndroidRuntime(32553): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1399)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.app.Activity.dispatchTouchEvent(Activity.java:2364)
07-30 21:20:17.805: E/AndroidRuntime(32553): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2011)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.View.dispatchPointerEvent(View.java:5861)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3094)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2614)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewRootImpl.processInputEvents(ViewRootImpl.java:978)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:992)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2585)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.os.Handler.dispatchMessage(Handler.java:99)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.os.Looper.loop(Looper.java:137)
07-30 21:20:17.805: E/AndroidRuntime(32553): at android.app.ActivityThread.main(ActivityThread.java:4507)
07-30 21:20:17.805: E/AndroidRuntime(32553): at java.lang.reflect.Method.invokeNative(Native Method)
07-30 21:20:17.805: E/AndroidRuntime(32553): at java.lang.reflect.Method.invoke(Method.java:511)
07-30 21:20:17.805: E/AndroidRuntime(32553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
07-30 21:20:17.805: E/AndroidRuntime(32553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
07-30 21:20:17.805: E/AndroidRuntime(32553): at dalvik.system.NativeStart.main(Native Method)
I have no idea, what is going on wrong.

I came accross this exception when I was missing getItemId(int position) method re-implementation which returns different (unique) ID for default and replaced fragment. See https://stackoverflow.com/a/11974777/685292 for further explanation and example implementation.

Related

AWS Java SDK v2.10: QuickSightClient throws SdkClientException When Delete is Successful

quickSightClient.deleteUser(deleteUserRequest) throws a null pointer exception because it fails to marshall the 204 No Content response, which AWS Quicksight returns after successfully deleting a user.
My Questions:
Is there a better way to handle or avoid this problem than using a try/catch to swallow the error (see below)?
Should I report this as an bug in their GitHub project? I reported this GitHub Issue.
My Code:
private void deleteQuickSightUser() {
String awsAccountId = "..."
String roleName = "cc-embedding_quicksight_dashboard_role"
String email = "person#company.com"
String namespace = "default"
String roleArn = "arn:aws:iam::$awsAccountId:role/$roleName"
QuickSightClient quickSightClient = QuickSightClient.create()
User user = quickSightClient.listUsers(ListUsersRequest.builder()
.awsAccountId(awsAccountId)
.namespace(namespace)
.build()
).userList().find { it.email() == email }
if (user) {
log.error("found the $email user with username: $user.userName")
DeleteUserRequest deleteUserRequest = DeleteUserRequest.builder()
.awsAccountId(awsAccountId)
.namespace(namespace)
.userName(user.userName)
.build()
try {
/* *** THE FOLLOWING LINE THROWS THE EXCEPTION *** */
quickSightClient.deleteUser(deleteUserRequest)
} catch (SdkClientException e) {
log.error(e.message)
}
log.error("deleted user $user.email")
}
}
The Exception
2020-01-03 09:53:36.168 ERROR --- [nio-8080-exec-2] o.g.web.errors.GrailsExceptionResolver : NullPointerException occurred when processing request: [GET] /
Stacktrace follows:
java.lang.reflect.InvocationTargetException: null
at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsControllerClass.java:211)
at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrailsControllerClass.java:188)
at org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsInfoHandlerAdapter.groovy:90)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: software.amazon.awssdk.core.exception.SdkClientException: Unable to unmarshall response (null). Response Code: 204, Response Text: No Content
at software.amazon.awssdk.core.exception.SdkClientException$BuilderImpl.build(SdkClientException.java:97)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.handleSuccessResponse(HandleResponseStage.java:100)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.handleResponse(HandleResponseStage.java:70)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:58)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:41)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:73)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:77)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:39)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage$RetryExecutor.doExecute(RetryableStage.java:113)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage$RetryExecutor.execute(RetryableStage.java:86)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:62)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:57)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:37)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.executeWithTimer(ApiCallTimeoutTrackingStage.java:80)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:60)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:37)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:26)
at software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient$RequestExecutionBuilderImpl.execute(AmazonSyncHttpClient.java:240)
at software.amazon.awssdk.core.client.handler.BaseSyncClientHandler.invoke(BaseSyncClientHandler.java:96)
at software.amazon.awssdk.core.client.handler.BaseSyncClientHandler.execute(BaseSyncClientHandler.java:120)
at software.amazon.awssdk.core.client.handler.BaseSyncClientHandler.execute(BaseSyncClientHandler.java:73)
at software.amazon.awssdk.core.client.handler.SdkSyncClientHandler.execute(SdkSyncClientHandler.java:44)
at software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler.execute(AwsSyncClientHandler.java:55)
at software.amazon.awssdk.services.quicksight.DefaultQuickSightClient.deleteUser(DefaultQuickSightClient.java:1341)
at grails4test.ApplicationController.deleteUser(ApplicationController.groovy:85)
at grails4test.ApplicationController.doStuff(ApplicationController.groovy:44)
at grails4test.ApplicationController.index(ApplicationController.groovy:23)
... 13 common frames omitted
Caused by: java.lang.NullPointerException: null
at software.amazon.awssdk.core.io.SdkFilterInputStream.read(SdkFilterInputStream.java:66)
at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.ensureLoaded(ByteSourceJsonBootstrapper.java:522)
at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.detectEncoding(ByteSourceJsonBootstrapper.java:129)
at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.constructParser(ByteSourceJsonBootstrapper.java:246)
at com.fasterxml.jackson.core.JsonFactory._createParser(JsonFactory.java:1315)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:820)
at software.amazon.awssdk.protocols.json.internal.dom.JsonDomParser.parse(JsonDomParser.java:39)
at software.amazon.awssdk.protocols.json.internal.unmarshall.JsonProtocolUnmarshaller.unmarshall(JsonProtocolUnmarshaller.java:167)
at software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler.handle(JsonResponseHandler.java:79)
at software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler.handle(JsonResponseHandler.java:36)
at software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonResponseHandler.handle(AwsJsonResponseHandler.java:43)
at software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler$Crc32ValidationResponseHandler.handle(AwsSyncClientHandler.java:88)
at software.amazon.awssdk.core.client.handler.BaseClientHandler.lambda$interceptorCalling$2(BaseClientHandler.java:151)
at software.amazon.awssdk.core.client.handler.AttachHttpMetadataResponseHandler.handle(AttachHttpMetadataResponseHandler.java:40)
at software.amazon.awssdk.core.client.handler.AttachHttpMetadataResponseHandler.handle(AttachHttpMetadataResponseHandler.java:28)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.handleSuccessResponse(HandleResponseStage.java:89)
... 45 common frames omitted
I think you should use try/catch for now and report this as a bug. What does the stack trace look like?

Puzzling ClasscastException while using PowerMockito to perform unit test on CassandraClient using Vertx

I am running a unit test using PowerMockito to perform a query using Vert.x's CassandraClient and I see ClassCastException.
Similar code works when performing updates.
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(VertxUnitRunner.class)
#PowerMockIgnore("javax.management.*")
#PrepareForTest({ CassandraClient.class, ResultSet.class, Row.class })
class TestCassandraClient {
#Mock
private AsyncResult<List<Row>> asyncListRow;
#Mock
private List<Row> listRow;
#Test
public void testQueryKeyspaces(TestContext context) {
Mockito.when(asyncListRow.succeeded()).thenReturn(true);
Mockito.when(asyncListRow.result()).thenReturn(listRow);
Mockito.when(listRow.size()).thenReturn(0);
Mockito.doAnswer(new Answer<AsyncResult<List<Row>>>() {
#SuppressWarnings("unchecked")
#Override
public AsyncResult<List<Row>> answer(InvocationOnMock invocation) throws Throwable {
((Handler<AsyncResult<List<Row>>>) invocation.getArgument(1)).handle(asyncListRow);
return asyncListRow;
}
}).when(client).executeWithFullFetch(Mockito.anyString(), Mockito.any());
Async async = context.async(1);
try {
(new Operation()).queryAll(client, "SELECT * FROM system_schema.keyspaces")
.setHandler(ar -> {
if (ar.succeeded()) {
async.complete();
} else {
context.fail("Failed to perform operation");
}
});
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
context.verify(v -> {
Assert.fail(e.getMessage());
});
async.complete();
}
}
}
The method "queryAll" is as below:
Class Operation {
public Future<OperationResult> queryAll(#NonNull final CassandraClient client, #NonNull final String query) {
Objects.requireNonNull(client, "CassandraClient cannot be null");
Objects.requireNonNull(query, "Update query cannot be null");
Future<OperationResult> future = Future.future();
try {
client.executeWithFullFetch(query, rh -> {
OperationResult resultObj = new OperationResult();
if (rh.succeeded()) {
resultObj.setSuccess(true);
List<Row> rows = rh.result();
if (rows != null && rows.size() > 0) {
Row row = rows.get(0);
ColumnDefinitions colDefs = row.getColumnDefinitions();
resultObj.setColumnDefinitions(toJsonArray(colDefs));
}
resultObj.setData(toJsonArray(rows));
} else {
resultObj.setSuccess(false);
resultObj.setException(rh.cause().getMessage());
}
future.complete(resultObj);
});
} catch (Exception e) {
String msg = String.format("Problem invoking query: %s. Error: %s", query, e.getMessage());
LOGGER.error(msg, e);
OperationResult resultObj = new OperationResult();
resultObj.setSuccess(false);
resultObj.setException(msg);
future.complete(resultObj);
}
return future;
}
}
Note that I have added a mock instruction
to return zero rows
Mockito.when(listRow.size()).thenReturn(0);
So, In the first line you see the response is returning a list of zero rows, but next I see an error as below.
05:21:41.015 [vert.x-eventloop-thread-0] DEBUG c.b.t.p.c.api.beans.OperationResult - JSON representation: {"column-definitions":null,"rows":[],"success":true,"exception":null}
05:21:41.015 [vert.x-eventloop-thread-0] ERROR c.b.t.p.c.api.operation.Operation - Problem invoking query: SELECT * FROM system_schema.keyspaces. Error: io.vertx.core.AsyncResult$MockitoMock$1728182793 cannot be cast to io.vertx.cassandra.CassandraClient
java.lang.ClassCastException: io.vertx.core.AsyncResult$MockitoMock$1728182793 cannot be cast to io.vertx.cassandra.CassandraClient
at io.vertx.cassandra.CassandraClient$MockitoMock$873315432.executeWithFullFetch(Unknown Source)
at com.bmc.tso.persistence.client.api.operation.Operation.queryAll(Operation.java:195)
at com.bmc.tso.persistence.client.api.operation.KeyspaceOperationUnitTest.testQueryKeyspaces(KeyspaceOperationUnitTest.java:372)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at io.vertx.ext.unit.junit.VertxUnitRunner.invokeTestMethod(VertxUnitRunner.java:95)
at io.vertx.ext.unit.junit.VertxUnitRunner.lambda$invokeExplosively$0(VertxUnitRunner.java:114)
at io.vertx.ext.unit.impl.TestContextImpl.run(TestContextImpl.java:90)
at io.vertx.ext.unit.junit.VertxUnitRunner.lambda$invokeExplosively$1(VertxUnitRunner.java:127)
at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:320)
at io.vertx.core.impl.EventLoopContext.lambda$executeAsync$0(EventLoopContext.java:38)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:462)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:897)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
05:21:

Zuul not throwing expected exception

I am throwing a ZuulRuntimeException and written a test case to validate it but it is throwing a different one.
Code:
public String extractCdsid(String accessToken) {
ObjectMapper objectMapper = new ObjectMapper();
String cdsid = "";
try {
String payload = JwtHelper.decode(accessToken).getClaims();
cdsid = objectMapper.readTree(payload).get("upn").textValue();
} catch (NullPointerException e) {
ZuulException ex = new ZuulException(
"Token does not contain upn. Please send a valid that contains upn(cdsid)", 401, "");
throw new ZuulRuntimeException(ex);
} }
Testcase:
#Test(expected = ZuulRuntimeException.class)
public void getPrincipalHeader_withAuthorizationHeaderNotContainUpn_returnsException(){
// mock
MockHttpServletRequest req = new MockHttpServletRequest();
req.addHeader("Authorization", "sendingtokenthatdoesnotcontainupn");
// run
tokenParser.getPrincipalHeader(req);
}
I am getting
java.lang.Exception: Unexpected exception, expected<com.netflix.zuul.exception.ZuulException> but was<java.lang.IllegalStateException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.IllegalStateException: CounterFactory not initialized
at com.netflix.zuul.monitoring.CounterFactory.instance(CounterFactory.java:42)
at com.netflix.zuul.exception.ZuulException.incrementCounter(ZuulException.java:73)
at com.netflix.zuul.exception.ZuulException.<init>(ZuulException.java:54)
at com.cv.vadr.vadrgateway.util.TokenParser.extractCdsid(TokenParser.java:51)
at com.cv.vadr.vadrgateway.util.TokenParser.getPrincipalHeader(TokenParser.java:32)
at com.cv.vadr.vadrgateway.util.TokenParserTest.getPrincipalHeader_withAuthorizationHeaderNotContainUpn_returnsException(TokenParserTest.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 16 more
I see the correct exception being thrown with message when I hit the service through postman
I had the same problem and for me adding
#Before
public void setUp() {
CounterFactory.initialize(new EmptyCounterFactory());
}
worked. Thanks to that I get rid of the java.lang.IllegalStateException: CounterFactory not initialized

Exception when setting Items in an ObservableList JavaFX

each time, when I want to set the Items of the table I have declared i receive a exception. I don't know what I'm doing wrong.
The error code:
Okt 09, 2014 11:06:10 AM application.Main start
SCHWERWIEGEND: null
javafx.fxml.LoadException:
/D:/Users/muellerl/workspace/Hydaba/bin/application/table_ui.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at application.Main.start(Main.java:17)
at com.sun.javafx.application.LauncherImpl$8.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$7.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$6$1.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl$6$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at controller.main_controller.initialize(main_controller.java:49)
... 20 more
So when I remove einheitenTable.setItems(einheitendata); I don't receive the error. He finds the source "table_ui.fxml". So i think it's a Problem of the TableView.
Here is the other code I have written. Hope you can help me with this issue. The error in line 49 belongs to the main_controller.java.
main.java:
package application;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
public class Main extends Application {
#Override
public void start(Stage Stage) {
try {
Parent root = FXMLLoader.load(getClass().getResource(
"/application/table_ui.fxml"));
Scene scene = new Scene(root);
Stage.setTitle("Hydaba-Client");
Stage.setScene(scene);
Stage.show();
} catch (Exception e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
}
}
public static void main(String[] args) {
launch(args);
}
}
einheiten_table.java:
package table;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class einheiten_table {
private final SimpleIntegerProperty rBleinr;
private final SimpleStringProperty rEinheit;
private final SimpleStringProperty rLiteeinheit;
private final SimpleStringProperty rEinheitengruppe;
private final SimpleStringProperty rBasiseinheit;
private final SimpleIntegerProperty rUmrechnungsfaktor;
public einheiten_table (int sBleinr, String sEinheit, String sLiteeinheit, String sEinheitengruppe,String sBasiseinheit, int sUmrechnungsfaktor) {
this.rBleinr = new SimpleIntegerProperty(sBleinr);
System.out.println(sBleinr);
this.rEinheit = new SimpleStringProperty(sEinheit);
System.out.println(sEinheit);
this.rLiteeinheit = new SimpleStringProperty(sLiteeinheit);
System.out.println(sLiteeinheit);
this.rEinheitengruppe = new SimpleStringProperty(sEinheitengruppe);
System.out.println(sEinheitengruppe);
this.rBasiseinheit = new SimpleStringProperty(sBasiseinheit);
System.out.println(sBasiseinheit);
this.rUmrechnungsfaktor = new SimpleIntegerProperty(sUmrechnungsfaktor);
System.out.println(sUmrechnungsfaktor);
}
/** rBleinr **/
public Integer get_rBleinr() {
return rBleinr.get();
}
public void set_rBleinr(Integer set) {
rBleinr.set(set);
}
/** rEinheit **/
public String get_rEinheit() {
return rEinheit.get();
}
public void set_rEinheit(String set) {
rEinheit.set(set);
}
/** rLiteeinheit **/
public String get_rLiteeinheit() {
return rLiteeinheit.get();
}
public void set_rLiteeinheit(String set) {
rLiteeinheit.set(set);
}
/** rEinheitengruppe **/
public String get_rEinheitengruppe() {
return rEinheitengruppe.get();
}
public void set_rEinheitengruppe(String set) {
rEinheitengruppe.set(set);
}
/** rBasiseinheit **/
public String get_rBasiseinheit() {
return rBasiseinheit.get();
}
public void set_rBasiseinheit(String set) {
rBasiseinheit.set(set);
}
/** rUmrechnungsfaktor **/
public Integer get_rUmrechnungsfaktor() {
return rUmrechnungsfaktor.get();
}
public void set_rUmrechnungsfaktor(Integer set) {
rUmrechnungsfaktor.set(set);
}
}
main_controller.java:
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import table.einheiten_table;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
public class main_controller implements Initializable {
#FXML
TableView<einheiten_table> einheitenTable;
#FXML
TableColumn<einheiten_table, Integer> Bleinr_col;
#FXML
TableColumn<einheiten_table, String> Einheit_col;
#FXML
TableColumn<einheiten_table, String> Liteeinheit_col;
#FXML
TableColumn<einheiten_table, String> Einheitengruppe_col;
#FXML
TableColumn<einheiten_table, String> Basiseinheit_col;
#FXML
TableColumn<einheiten_table, Integer> Umrechnungsfaktor_col;
final ObservableList<einheiten_table> einheitendata = FXCollections.observableArrayList(
new einheiten_table(9, "Stelle 1", "Stelle 2", "Stelle 3", "Stelle 4", 10)
);
#Override
public void initialize(URL location, ResourceBundle resources) {
Bleinr_col.setCellValueFactory(new PropertyValueFactory<einheiten_table, Integer>("rBleinr"));
Einheit_col.setCellValueFactory(new PropertyValueFactory<einheiten_table, String>("rEinheit"));
Liteeinheit_col.setCellValueFactory(new PropertyValueFactory<einheiten_table, String>("rLiteeinheit"));
Einheitengruppe_col.setCellValueFactory(new PropertyValueFactory<einheiten_table, String>("rEinheitengruppe"));
Basiseinheit_col.setCellValueFactory(new PropertyValueFactory<einheiten_table, String>("rBasiseinheit"));
Umrechnungsfaktor_col.setCellValueFactory(new PropertyValueFactory<einheiten_table, Integer>("rUmrechnungsfaktor"));
// System.out.println(einheitendata.size());
einheitenTable.setItems(einheitendata);
}
}
My first guess is the name of TableView do not match in FXML file and Controller class. Currently you have defined it as
#FXML
TableView<einheiten_table> einheitenTable;
and again I guess it should be
#FXML
private TableView<einheiten_table> Einheiten_table;
according to your naming approach :)
Please check the fx:id in FXML file.

What's about "ClassCastExceptionclass org.apache.avro.mapred.AvroKey"?

I am programming MapR with Avro, and a real beginner against Avro. The input and output are both avro format with specific schema.
Here is my mapper and reducer using mapreduce API of MR1:
public class UserClassifyMapReduce extends Configured implements Tool {
private final static Logger logger = LoggerFactory.getLogger(UserClassifyMapReduce.class);
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new UserClassifyMapReduce(), args);
System.exit(res);
}
#Override
public int run(String[] args) throws Exception {
if (args.length < 2) {
logger.error("Usage: UserClassify <intputfile> <outputfolder>");
System.exit(-1);
}
Configuration conf = new Configuration();
Job job = new Job(getConf());
job.setJobName("UserClassify");
AvroJob.setInputKeySchema(job, NetflowRecord.getClassSchema());
AvroJob.setOutputKeySchema(job, NetflowRecord.getClassSchema());
FileInputFormat.setInputPaths(job, new Path(args[0]));
Path outPath = new Path(args[1]);
FileOutputFormat.setOutputPath(job, outPath);
outPath.getFileSystem(conf).delete(outPath, true);
job.setJarByClass(DataSerializeMapReduce.class);
job.setMapperClass(MyAvroMap.class);
job.setReducerClass(MyAvroReduce.class);
job.setInputFormatClass(AvroKeyInputFormat.class);
job.setOutputFormatClass(AvroKeyOutputFormat.class);
job.setMapOutputKeyClass(AvroKey.class);
job.setMapOutputValueClass(AvroValue.class);
job.setOutputKeyClass(AvroKey.class);
job.setOutputValueClass(NullWritable.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static class MyAvroMap extends Mapper<AvroKey<NetflowRecord>, NullWritable,
AvroKey<CharSequence>, AvroValue<NetflowRecord>>{
#Override
protected void map(AvroKey<NetflowRecord> key, NullWritable value, Context context)
throws IOException, InterruptedException{
CharSequence devMac = key.datum().getDevMacAddr();
context.write(new AvroKey<CharSequence>(devMac), new AvroValue<NetflowRecord>(key.datum()));
}
}
public static class MyAvroReduce extends Reducer<AvroKey<CharSequence>, AvroValue<NetflowRecord>,
AvroKey<NetflowRecord>, NullWritable>{
#Override
protected void reduce(AvroKey<CharSequence> key, Iterable<AvroValue<NetflowRecord>> values, Context context)
throws IOException, InterruptedException{
(...code)
}
}
}
The CastError throws messages like
java.lang.Exception: java.lang.ClassCastException: class org.apache.avro.mapred.AvroKey
at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:354)
Caused by: java.lang.ClassCastException: class org.apache.avro.mapred.AvroKey
at java.lang.Class.asSubclass(Class.java:3116)
at org.apache.hadoop.mapred.JobConf.getOutputKeyComparator(JobConf.java:795)
at org.apache.hadoop.mapred.MapTask$MapOutputBuffer.<init>(MapTask.java:964)
at org.apache.hadoop.mapred.MapTask$NewOutputCollector.<init>(MapTask.java:673)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:756)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:364)
at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:223)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
A very simple program. Do u have any idea about this problem. Thanks alot.
Jamin
You appear to be lacking a schema for the mapper output key AvroKey<CharSequence>. Adding the corresponding schema should be sufficient:
AvroJob.setMapOutputKeySchema(job, Schema.create(Schema.Type.STRING));