I'm trying to consume wsdl client that can be found on this link https://tim-erp.com/ERPX_WEB/awws/ErpX.awws?wsdl
My java code looks like this
public class SoapServicesImpl extends WebServiceGatewaySupport implements SoapServices {
#Override
public String doAuth(AuthDto authDto){
AuthStrct authStrct = new AuthStrct();
authStrct.setFirmaNaziv(authDto.getNazivFirme());
authStrct.setGodina(authDto.getGodina());
authStrct.setPassword(authDto.getPassword());
authStrct.setUsername(authDto.getUsername());
return callService(new ObjectFactory().createAuthStrct(authStrct));
}
#SuppressWarnings("unchecked")
public <T> T callService(JAXBElement<?> jaxbRequest) {
jaxbRequest.getValue();
JAXBElement<T> jaxbResponse;
try {
jaxbResponse = (JAXBElement<T>) getWebServiceTemplate().marshalSendAndReceive(jaxbRequest);
} catch (WebServiceException e) {
e.printStackTrace();
throw e;
}
return jaxbResponse.getValue();
}
}
package-info looks like this
#javax.xml.bind.annotation.XmlSchema(namespace = "urn:ErpX")
package rs.sweetchoice.commonservice.generated;
Generated ObjectFactory snippet:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See https://javaee.github.io/jaxb-v2/
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.09.05 at 01:28:42 PM CEST
//
package rs.sweetchoice.commonservice.generated;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the rs.sweetchoice.commonservice.generated package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
#XmlRegistry
public class ObjectFactory {
private final static QName _WSID_QNAME = new QName("urn:ErpX", "WSID");
private final static QName _AUTH_QNAME = new QName("urn:ErpX", "authStrct");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: rs.sweetchoice.commonservice.generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {#link AutoCompleteStrct }
*
*/
public AutoCompleteStrct createAutoCompleteStrct() {
return new AutoCompleteStrct();
}
/**
* Create an instance of {#link KorpaStrct }
*
*/
public KorpaStrct createKorpaStrct() {
return new KorpaStrct();
}
/**
* Create an instance of {#link CmbStrct }
*
*/
public CmbStrct createCmbStrct() {
return new CmbStrct();
}
/**
* Create an instance of {#link AuthStrct }
*
*/
#XmlElementDecl(namespace = "urn:ErpX", name = "authStrct")
public JAXBElement<AuthStrct> createAuthStrct(AuthStrct value) {
return new JAXBElement<>(_AUTH_QNAME, AuthStrct.class, null, value);
}
/**
* Create an instance of {#link FilterStrct }
*
*/
public FilterStrct createFilterStrct() {
return new FilterStrct();
}
/**
* Create an instance of {#link ProfakStavStrct }
*
*/
public ProfakStavStrct createProfakStavStrct() {
return new ProfakStavStrct();
}
/**
* Create an instance of {#link ProfakStrct }
*
*/
public ProfakStrct createProfakStrct() {
return new ProfakStrct();
}
/**
* Create an instance of {#link RacunStavStrct }
*
*/
public RacunStavStrct createRacunStavStrct() {
return new RacunStavStrct();
}
/**
* Create an instance of {#link RacunStrct }
*
*/
public RacunStrct createRacunStrct() {
return new RacunStrct();
}
/**
* Create an instance of {#link UplKomitStrct }
*
*/
public UplKomitStrct createUplKomitStrct() {
return new UplKomitStrct();
}
/**
* Create an instance of {#link UplListaStavStrct }
*
*/
public UplListaStavStrct createUplListaStavStrct() {
return new UplListaStavStrct();
}
/**
* Create an instance of {#link UplListaStrct }
*
*/
public UplListaStrct createUplListaStrct() {
return new UplListaStrct();
}
/**
* Create an instance of {#link WsGetRoba }
*
*/
public WsGetRoba createWsGetRoba() {
return new WsGetRoba();
}
/**
* Create an instance of {#link WsGetKomit }
*
*/
public WsGetKomit createWsGetKomit() {
return new WsGetKomit();
}
/**
* Create an instance of {#link WsGetGrpRoba }
*
*/
public WsGetGrpRoba createWsGetGrpRoba() {
return new WsGetGrpRoba();
}
/**
* Create an instance of {#link WsGetGrpKomit }
*
*/
public WsGetGrpKomit createWsGetGrpKomit() {
return new WsGetGrpKomit();
}
/**
* Create an instance of {#link WsGetManuf }
*
*/
public WsGetManuf createWsGetManuf() {
return new WsGetManuf();
}
/**
* Create an instance of {#link WsUplProfak }
*
*/
public WsUplProfak createWsUplProfak() {
return new WsUplProfak();
}
/**
* Create an instance of {#link WsGetMagacin }
*
*/
public WsGetMagacin createWsGetMagacin() {
return new WsGetMagacin();
}
/**
* Create an instance of {#link WsGetAkcijskeCene }
*
*/
public WsGetAkcijskeCene createWsGetAkcijskeCene() {
return new WsGetAkcijskeCene();
}
/**
* Create an instance of {#link WsUplKomit }
*
*/
public WsUplKomit createWsUplKomit() {
return new WsUplKomit();
}
/**
* Create an instance of {#link WsUplKomitResponse }
*
*/
public WsUplKomitResponse createWsUplKomitResponse() {
return new WsUplKomitResponse();
}
/**
* Create an instance of {#link WsUplRacun }
*
*/
public WsUplRacun createWsUplRacun() {
return new WsUplRacun();
}
/**
* Create an instance of {#link JAXBElement }{#code <}{#link byte[]}{#code >}
*
* #param value
* Java instance representing xml element's value.
* #return
* the new instance of {#link JAXBElement }{#code <}{#link byte[]}{#code >}
*/
#XmlElementDecl(namespace = "urn:ErpX", name = "WSID")
#XmlJavaTypeAdapter(HexBinaryAdapter.class)
public JAXBElement<byte[]> createWSID(byte[] value) {
return new JAXBElement<byte[]>(_WSID_QNAME, byte[].class, null, ((byte[]) value));
}
}
And i get error
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault"). Expected elements are <{urn:ErpX}WSID>,<{urn:ErpX}authStrct>
Using java 11 and spring boot 2.3.3.
EDIT this is my config class
#Configuration
public class WsConfig {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("rs.sweetchoice.commonservice.generated");
return marshaller;
}
#Bean
public SoapServicesImpl soapServicesImpl(Jaxb2Marshaller marshaller) {
SoapServicesImpl client = new SoapServicesImpl();
client.setDefaultUri("https://tim-erp.com/ERPX_WEB/awws/ErpX.awws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
Try to setCheckConnectionForFault to false on WebServiceTemplate. For example, replace the method:
public <T> T callService(JAXBElement<?> jaxbRequest) {
jaxbRequest.getValue();
JAXBElement<T> jaxbResponse;
try {
WebServiceTemplate webServiceTemplate = getWebServiceTemplate();
webServiceTemplate.setCheckConnectionForFault(false);
jaxbResponse = (JAXBElement<T>) webServiceTemplate.marshalSendAndReceive(jaxbRequest);
} catch (WebServiceException e) {
e.printStackTrace();
throw e;
}
return jaxbResponse.getValue();
}
Related
The expiration time of a JWT can be set by configuring micronaut.security.token.jwt.generator.access-token-expiration.
Is it possible to have a custom value for individually issued JWT tokens? Searching the documentation I haven't found any useful information except you can replace the BearerTokenRenderer and return a custom response.
public AccessRefreshToken render(Integer expiresIn, String accessToken, #Nullable String refreshToken) {
return new AccessRefreshToken(accessToken, refreshToken, BEARER_TOKEN_TYPE, ***customValue**);
}
Will returning a different value for expires_in work in this case?
According to micronaut documentation - pt 9.3.5
You can replace ClaimGenerator with your own:
ClaimGenerator
Which has a method with parameter Integer expiration
You can replace classes by using #Replaces annotation like described here:
https://micronaut-projects.github.io/micronaut-core/latest/guide/#replaces
I hope that solves your issue
The solution is to extend the JwTClaimsSetGenerator
#Replaces(JWTClaimsSetGenerator.class)
#Singleton
public class CustomClaimsGenerator extends JWTClaimsSetGenerator {
private static final Logger LOG = LoggerFactory.getLogger(CustomClaimsGenerator.class);
private static final String ROLES_KEY = "rolesKey";
private final TokenConfiguration tokenConfiguration;
private final JwtIdGenerator jwtIdGenerator;
private final ClaimsAudienceProvider claimsAudienceProvider;
private final String appName;
/**
* #param tokenConfiguration Token Configuration
* #param jwtIdGenerator Generator which creates unique JWT ID
* #param claimsAudienceProvider Provider which identifies the recipients that the JWT is intended for.
* #param applicationConfiguration The application configuration
*/
public CustomClaimsGenerator(TokenConfiguration tokenConfiguration,#Nullable JwtIdGenerator jwtIdGenerator, #Nullable ClaimsAudienceProvider claimsAudienceProvider, ApplicationConfiguration applicationConfiguration) {
super(tokenConfiguration, jwtIdGenerator, claimsAudienceProvider, applicationConfiguration);
this.tokenConfiguration = tokenConfiguration;
this.jwtIdGenerator = jwtIdGenerator;
this.claimsAudienceProvider = claimsAudienceProvider;
this.appName = applicationConfiguration != null ? applicationConfiguration.getName().orElse(Environment.MICRONAUT) : Environment.MICRONAUT;
}
/**
* #param authentication Authenticated user's representation.
* #param expiration expiration time in seconds
* #return The authentication claims
*/
#Override
public Map<String, Object> generateClaims(Authentication authentication, #Nullable Integer expiration) {
expiration = 1000; //works with this value
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
populateIat(builder);
populateExp(builder, 15);
populateJti(builder);
populateIss(builder);
populateAud(builder);
populateNbf(builder);
populateWithAuthentication(builder, authentication);
if (LOG.isDebugEnabled()) {
LOG.debug("Generated claim set: {}", builder.build().toJSONObject());
}
return builder.build().getClaims();
}
/**
* Populates iss claim.
*
* #param builder The Claims Builder
* #see iss (Issuer) Claim
*/
protected void populateIss(JWTClaimsSet.Builder builder) {
if (appName != null) {
builder.issuer(appName); // iss
}
}
/**
* Populates sub claim.
*
* #param builder The Claims Builder
* #param authentication Authenticated user's representation.
* #see sub (Subject) Claim
*/
protected void populateSub(JWTClaimsSet.Builder builder, Authentication authentication) {
builder.subject(authentication.getName()); // sub
}
/**
* Populates aud claim.
*
* #param builder The Claims Builder
* #see aud (Audience) Claim
*/
protected void populateAud(JWTClaimsSet.Builder builder) {
if (claimsAudienceProvider != null) {
builder.audience(claimsAudienceProvider.audience()); // aud
}
}
/**
* Populates exp claim.
*
* #param builder The Claims Builder
* #param expiration expiration time in seconds
* #see exp (ExpirationTime) Claim
*/
protected void populateExp(JWTClaimsSet.Builder builder, #Nullable Integer expiration) {
if (expiration != null) {
LOG.debug("Setting expiration to {}", expiration);
System.out.print(Date.from(Instant.now().plus(expiration, ChronoUnit.SECONDS)));
builder.expirationTime(Date.from(Instant.now().plus(expiration, ChronoUnit.SECONDS))); // exp
}
}
/**
* Populates nbf claim.
*
* #param builder The Claims Builder
* #see nbf (Not Before) Claim
*/
protected void populateNbf(JWTClaimsSet.Builder builder) {
builder.notBeforeTime(new Date()); // nbf
}
/**
* Populates iat claim.
*
* #param builder The Claims Builder
* #see iat (Issued At) Claim
*/
protected void populateIat(JWTClaimsSet.Builder builder) {
builder.issueTime(new Date()); // iat
}
/**
* Populates jti claim.
*
* #param builder The Claims Builder
* #see jti (JWT ID) Claim
*/
protected void populateJti(JWTClaimsSet.Builder builder) {
if (jwtIdGenerator != null) {
builder.jwtID(jwtIdGenerator.generateJtiClaim()); // jti
}
}
/**
* Populates Claims with Authentication object.
*
* #param builder the Claims Builder
* #param authentication Authenticated user's representation.
*/
protected void populateWithAuthentication(JWTClaimsSet.Builder builder, Authentication authentication) {
populateSub(builder, authentication);
authentication.getAttributes().forEach(builder::claim);
String rolesKey = tokenConfiguration.getRolesName();
if (!rolesKey.equalsIgnoreCase(TokenConfiguration.DEFAULT_ROLES_NAME)) {
builder.claim(ROLES_KEY, rolesKey);
}
builder.claim(rolesKey, authentication.getRoles());
}
/**
* #param oldClaims The old claims to use as a base in the new token generation.
* #param expiration expiration time in seconds
* #return Instance of {#link JWTClaimsSet}
*/
#Override
public Map<String, Object> generateClaimsSet(Map<String, ?> oldClaims, Integer expiration) {
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
List<String> excludedClaims = Arrays.asList(JwtClaims.EXPIRATION_TIME, JwtClaims.ISSUED_AT, JwtClaims.NOT_BEFORE);
for (String k : oldClaims.keySet()
.stream()
.filter(p -> !excludedClaims.contains(p))
.collect(Collectors.toList())) {
builder.claim(k, oldClaims.get(k));
}
populateExp(builder, expiration);
populateIat(builder);
populateNbf(builder);
return builder.build().getClaims();
}
}
I have these classes:
My problem is that for each class I am having to manually register the node.
/**
* Contains the encoder for messages from the server.
*
* #since 18/08/2018
*/
public abstract class MessageEncoder<T> {
/**
* Register this encoder to a message.
*/
public abstract void register();
/**
* Get the encoded message to send to the client.
*
* #param message The message.
* #return the {#link GamePacket} ready to be sent.
*/
public abstract GamePacket encode(T message);
}
Where < T > is always someClass extends Message.
And here is how a message encoder looks like:
public final class ComponentMessageEncoder extends MessageEncoder<ComponentTextMessage> {
#Override
public void register() {
GameConstants.RELEASE.register(ComponentTextMessage.class, this);
}
#Override
public GamePacket encode(ComponentTextMessage message) {
// TODO Auto-generated method stub
return null;
}
}
As you can see the items in the register method, I have to manually type that for every encoder I make.
Is there a shortcut for this that I can just put in MessageEncoder abstract class instead?
I could not find anything that works here
Edit:
Where register sig. is:
/**
* The encoders.
*/
private final Map<Class<? extends Message>, MessageEncoder<?>> encoders = new HashMap<>();
/**
* Register a encoder to a message.
*
* #param message The message.
* #param encoder The encoder.
*/
public void register(Class<? extends Message> message, MessageEncoder<?> encoder) {
encoders.put(message, encoder);
}
You can do slightly better with:
public abstract class MessageEncoder<T extends Message> {
protected MessageEncoder(Class<? extends T> messageClass) {
GameConstants.RELEASE.register(messageClass, this);
}
/**
* Get the encoded message to send to the client.
*
* #param message The message.
* #return the {#link GamePacket} ready to be sent.
*/
public abstract GamePacket encode(T message);
}
Now subclasses would do:
public final class ComponentMessageEncoder extends MessageEncoder<ComponentTextMessage> {
ComponentMessageEncoder() {
super(ComponentTextMessage.class);
}
// etc as before
}
This cuts down slightly on the repetition, and it allows the compiler to stop you from getting it wrong, so it's something of a win.
I developed some app and it's working fine without any problem. No problem on debug. I created some custom class with the ShareActionProvider class methods for check to user actions from ActionShareProvider menu. When I want to generate APK from Android Studio it gives me this error;
Error:(87) Error: This class should provide a default constructor (a public constructor with no arguments) (com.esmobileinc.vetmapp.ShareActionProvider) [Instantiatable]
There is the ShareActionProvider class;
public class ShareActionProvider extends ActionProvider {
public void setOnShareListener(OnShareListener listener) {
mOnShareListener = listener;
setActivityChooserPolicyIfNeeded();
}
/**
* Listener for the event of selecting a share target.
*/
public interface OnShareTargetSelectedListener {
/**
* Called when a share target has been selected. The client can
* decide whether to perform some action before the sharing is
* actually performed.
* <p>
* <strong>Note:</strong> Modifying the intent is not permitted and
* any changes to the latter will be ignored.
* </p>
* <p>
* <strong>Note:</strong> You should <strong>not</strong> handle the
* intent here. This callback aims to notify the client that a
* sharing is being performed, so the client can update the UI
* if necessary.
* </p>
*
* #param source The source of the notification.
* #param intent The intent for launching the chosen share target.
* #return The return result is ignored. Always return false for consistency.
*/
public boolean onShareTargetSelected(ShareActionProvider source, Intent intent);
}
private OnShareListener mOnShareListener; //also need to add getter and setter
public interface OnShareListener {
/**
* Called when a share target has been selected. The client can
* decide whether to perform some action before the sharing is
* actually performed OR handle the action itself.
*
* #param source The source of the notification.
* #param intent The intent for launching the chosen share target.
* #return Return true if you have handled the intent.
*/
public boolean willHandleShareTarget(ShareActionProvider source, Intent intent);
}
/**
* The default for the maximal number of activities shown in the sub-menu.
*/
private static final int DEFAULT_INITIAL_ACTIVITY_COUNT = 4;
/**
* The the maximum number activities shown in the sub-menu.
*/
private int mMaxShownActivityCount = DEFAULT_INITIAL_ACTIVITY_COUNT;
/**
* Listener for handling menu item clicks.
*/
private final ShareMenuItemOnMenuItemClickListener mOnMenuItemClickListener =
new ShareMenuItemOnMenuItemClickListener();
/**
* The default name for storing share history.
*/
public static final String DEFAULT_SHARE_HISTORY_FILE_NAME = "share_history.xml";
/**
* Context for accessing resources.
*/
private final Context mContext;
/**
* The name of the file with share history data.
*/
private String mShareHistoryFileName = DEFAULT_SHARE_HISTORY_FILE_NAME;
private OnShareTargetSelectedListener mOnShareTargetSelectedListener;
private OnChooseActivityListener mOnChooseActivityListener;
/**
* Creates a new instance.
*
* #param context Context for accessing resources.
*/
public ShareActionProvider(Context context) {
super(context);
mContext = context;
}
/**
* Sets a listener to be notified when a share target has been selected.
* The listener can optionally decide to handle the selection and
* not rely on the default behavior which is to launch the activity.
* <p>
* <strong>Note:</strong> If you choose the backing share history file
* you will still be notified in this callback.
* </p>
* #param listener The listener.
*/
public void setOnShareTargetSelectedListener(OnShareTargetSelectedListener listener) {
mOnShareTargetSelectedListener = listener;
setActivityChooserPolicyIfNeeded();
}
/**
* {#inheritDoc}
*/
#Override
public View onCreateActionView() {
// Create the view and set its data model.
ActivityChooserView activityChooserView = new ActivityChooserView(mContext);
if (!activityChooserView.isInEditMode()) {
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
activityChooserView.setActivityChooserModel(dataModel);
}
// Lookup and set the expand action icon.
TypedValue outTypedValue = new TypedValue();
mContext.getTheme().resolveAttribute(R.attr.actionModeShareDrawable, outTypedValue, true);
Drawable drawable = TintManager.getDrawable(mContext, outTypedValue.resourceId);
activityChooserView.setExpandActivityOverflowButtonDrawable(drawable);
activityChooserView.setProvider(this);
// Set content description.
activityChooserView.setDefaultActionButtonContentDescription(
R.string.abc_shareactionprovider_share_with_application);
activityChooserView.setExpandActivityOverflowButtonContentDescription(
R.string.abc_shareactionprovider_share_with);
return activityChooserView;
}
/**
* {#inheritDoc}
*/
#Override
public boolean hasSubMenu() {
return true;
}
/**
* {#inheritDoc}
*/
#Override
public void onPrepareSubMenu(SubMenu subMenu) {
// Clear since the order of items may change.
subMenu.clear();
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
PackageManager packageManager = mContext.getPackageManager();
final int expandedActivityCount = dataModel.getActivityCount();
final int collapsedActivityCount = Math.min(expandedActivityCount, mMaxShownActivityCount);
// Populate the sub-menu with a sub set of the activities.
for (int i = 0; i < collapsedActivityCount; i++) {
ResolveInfo activity = dataModel.getActivity(i);
subMenu.add(0, i, i, activity.loadLabel(packageManager))
.setIcon(activity.loadIcon(packageManager))
.setOnMenuItemClickListener(mOnMenuItemClickListener);
}
if (collapsedActivityCount < expandedActivityCount) {
// Add a sub-menu for showing all activities as a list item.
SubMenu expandedSubMenu = subMenu.addSubMenu(Menu.NONE, collapsedActivityCount,
collapsedActivityCount,
mContext.getString(R.string.abc_activity_chooser_view_see_all));
for (int i = 0; i < expandedActivityCount; i++) {
ResolveInfo activity = dataModel.getActivity(i);
expandedSubMenu.add(0, i, i, activity.loadLabel(packageManager))
.setIcon(activity.loadIcon(packageManager))
.setOnMenuItemClickListener(mOnMenuItemClickListener);
}
}
}
/**
* Sets the file name of a file for persisting the share history which
* history will be used for ordering share targets. This file will be used
* for all view created by {#link #onCreateActionView()}. Defaults to
* {#link #DEFAULT_SHARE_HISTORY_FILE_NAME}. Set to <code>null</code>
* if share history should not be persisted between sessions.
* <p>
* <strong>Note:</strong> The history file name can be set any time, however
* only the action views created by {#link #onCreateActionView()} after setting
* the file name will be backed by the provided file. Therefore, if you want to
* use different history files for sharing specific types of content, every time
* you change the history file {#link #setShareHistoryFileName(String)} you must
* call {#link android.app.Activity#invalidateOptionsMenu()} to recreate the
* action view. You should <strong>not</strong> call
* {#link android.app.Activity#invalidateOptionsMenu()} from
* {#link android.app.Activity#onCreateOptionsMenu(Menu)}."
* <p>
* <code>
* private void doShare(Intent intent) {
* if (IMAGE.equals(intent.getMimeType())) {
* mShareActionProvider.setHistoryFileName(SHARE_IMAGE_HISTORY_FILE_NAME);
* } else if (TEXT.equals(intent.getMimeType())) {
* mShareActionProvider.setHistoryFileName(SHARE_TEXT_HISTORY_FILE_NAME);
* }
* mShareActionProvider.setIntent(intent);
* invalidateOptionsMenu();
* }
* <code>
*
* #param shareHistoryFile The share history file name.
*/
public void setShareHistoryFileName(String shareHistoryFile) {
mShareHistoryFileName = shareHistoryFile;
setActivityChooserPolicyIfNeeded();
}
/**
* Sets an intent with information about the share action. Here is a
* sample for constructing a share intent:
* <p>
* <pre>
* <code>
* Intent shareIntent = new Intent(Intent.ACTION_SEND);
* shareIntent.setType("image/*");
* Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
* shareIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
* </pre>
* </code>
* </p>
*
* #param shareIntent The share intent.
*
* #see Intent#ACTION_SEND
* #see Intent#ACTION_SEND_MULTIPLE
*/
public void setShareIntent(Intent shareIntent) {
if (shareIntent != null) {
final String action = shareIntent.getAction();
if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
updateIntent(shareIntent);
}
}
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
mShareHistoryFileName);
dataModel.setIntent(shareIntent);
}
/**
* Reusable listener for handling share item clicks.
*/
private class ShareMenuItemOnMenuItemClickListener implements OnMenuItemClickListener {
#Override
public boolean onMenuItemClick(MenuItem item) {
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext,
mShareHistoryFileName);
final int itemId = item.getItemId();
Intent launchIntent = dataModel.chooseActivity(itemId);
if (launchIntent != null) {
final String action = launchIntent.getAction();
if (Intent.ACTION_SEND.equals(action) ||
Intent.ACTION_SEND_MULTIPLE.equals(action)) {
updateIntent(launchIntent);
}
mContext.startActivity(launchIntent);
}
return true;
}
}
/**
* Set the activity chooser policy of the model backed by the current
* share history file if needed which is if there is a registered callback.
*/
private void setActivityChooserPolicyIfNeeded() {
if (mOnShareListener == null) {
return;
}
if (mOnChooseActivityListener == null) {
mOnChooseActivityListener = new ShareActivityChooserModelPolicy();
}
ActivityChooserModel dataModel = ActivityChooserModel.get(mContext, mShareHistoryFileName);
dataModel.setOnChooseActivityListener(mOnChooseActivityListener);
}
/**
* Policy that delegates to the {#link OnShareTargetSelectedListener}, if such.
*/
private class ShareActivityChooserModelPolicy implements OnChooseActivityListener {
#Override
public boolean onChooseActivity(ActivityChooserModel host, Intent intent) {
if (mOnShareListener != null) {
boolean result = mOnShareListener.willHandleShareTarget(
ShareActionProvider.this, intent);
return result;
}
return false;
}
}
private void updateIntent(Intent intent) {
if (Build.VERSION.SDK_INT >= 21) {
// If we're on Lollipop, we can open the intent as a document
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
} else {
// Else, we will use the old CLEAR_WHEN_TASK_RESET flag
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
}
}
}
There is a constructor here in my ShareActionProvider class;
public ShareActionProvider(Context context) {
super(context);
mContext = context;
}
Why it gives me this error ? How can I solve this problem. Thank you !
I renamed my custom ActionShareProvider.class to CustomActionShareProvider.class and problem resolved.
I have a question regarding static method access. I have a class within i have 4 static method. as shown in code:
package com.itrucking.util;
public class ZKUtil implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
* #author Shekhar
* #param _class
* #param listbox
* To make Listbox sorting enabled
* #throws NoSuchMethodException
* #throws SecurityException
*/
public static void setSortingEnabled(Class<?> _class, Listbox listbox){
Map<Listheader, String> sortingPair = new HashMap<Listheader, String>();
sortingPair = getMapForSorting(_class, listbox);
if (!sortingPair.isEmpty()) {
for (Map.Entry<Listheader, String> entry : sortingPair.entrySet()) {
entry.getKey().setSortAscending(
new FieldComparator(entry.getValue(), true));
entry.getKey().setSortDescending(
new FieldComparator(entry.getValue(), false));
}
}
}
/**
* #author Shekhar
* #param _class
* #param listbox
* #return Map<Listheader, String>
*/
private static Map<Listheader, String> getMapForSorting(Class<?> _class,Listbox listbox) {
List<Listheader> headerList = getListHeaderList(listbox);
Map<Listheader, String> sortingPair = new HashMap<Listheader, String>();
System.out.println(_class);
Field[] fields = _class.getDeclaredFields();
for (Field f : fields) {
// System.out.println(f.getName()+":"+f.getType());
for (Listheader lh : headerList) {
if (f.getName().equals(getId(lh)))
sortingPair.put(lh, f.getName());
}
}
System.out.println(sortingPair);
return sortingPair;
}
private static String getId(Listheader listheader) {
String listheaderId = null;
if (listheader.getId().contains("_")) {
listheaderId = listheader.getId().split("_")[1];
// System.out.println("listheaderId->"+listheaderId);
}
return listheaderId;
}
/**
* #author Shekhar
* #param listbox
* #return List<Listheader>
*/
#SuppressWarnings("unchecked")
private static List<Listheader> getListHeaderList(Listbox listbox) {
List<Listheader> headerList = new ArrayList<Listheader>();
Listhead listhead = null;
List<Component> listboxComponentList = listbox.getChildren();
for (Component listboxComponent : listboxComponentList) {
if (listboxComponent instanceof Listhead) {
listhead = (Listhead) listboxComponent;
break;
}
}
List<Component> listOfComp = listhead.getChildren();
if (listhead != null) {
for (Component c : listOfComp) {
if (c instanceof Listheader)
headerList.add((Listheader) c);
}
}
return headerList;
}
}
and i am calling setSortingEnabled() method from onLoadShipperDetailsListCtrl() from code bellow :
package com.itrucking.webui.controller;
public class ShipperDetailsListCtrl{
/**
* #param e
* #return void
*/
public void onCreate$window_shipperDetailsList(Event e){
onLoadShipperDetailsListCtrl();
}
/**
* #return void
*/
public void onLoadShipperDetailsListCtrl(){
System.out.println("onLoadShipperDetailsListCtrl called.");
shipperList = shipperService.getShipperList();
doRenderListboxShipperDetailsList(shipperList);
ZKUtil.setSortingEnabled(ShipperMaster.class, listbox_shipperDetailsList);
}
}
so what i think if i am calling setSortingEnabled() method from other class so i kept is as public and other method's i kept as private but it's giving me error as :
java.lang.NoSuchMethodError: com/itrucking/util/ZKUtil.getMapForSorting(Ljava/lang/Class;Lorg/zkoss/zul/Listbox;)Ljava/util/Map;
Why there is error NoSuchMethodError for ZKUtil.getMapForSorting() call in setSortingEnabled()
I know we can call private method from public in the same class. So i am not able to understand what is the problem.
Thanks in advance.
A NoSuchMethodError (the runtime error saying a method can't be found, instead of a compiler error) usually means that the .class files you're using are of a different version than the files you compiled against. In this case, you probably made changes to ZKUtil.java, but the JVM is loading an outdated version of ZKUtil.class. Clean and rebuild all of your .class files.
In an answer to a question I asked, I was advised to solve a particular (irrelevant) problem by making a class (test_C) designed to test the main class (C) be a child class of C:
public class test_C extends C {
Is this a common pattern in Java development?
Are there any reasons NOT to use this pattern for all test classes (assume that we always have 1-1 mapping between test class and tested class)?
Are there any reasons NOT to use this pattern for all test classes (assume that we always have 1-1 mapping between test class and tested class)?
The class being tested can be final, preventing any class from subclassing it.
public final class C { ... }
If a testing subclass is feasible, it could alter the behavior of the class being tested -- unintentionally as well as intentionally.
1) Well, I do not know if it is a general pattern but i already used it and found some drawbacks.
2) the reasons to not do it are fairy simple. It is recommended to use private accessor and final class or method.
If you really apply the later, you will end up with producing many duplicate classes to test a class or a method. Also, How can you make sure somebody in your team will not end up using the dummy extended class in production?
My solution to this problem was to use reflection to access private constructors and methods. It is somehow a bit tricky but afterwards it is a repetition. I am using now my utility reflection class for all my tests.
Below is my reflection utility class:
import static org.junit.Assert.fail;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* The Class JunitReflectionUtils.
*/
public final class JunitReflectionUtils {
/**
* Instantiates a new junit reflection utils.
*/
private JunitReflectionUtils() {
}
/**
* Gets the method.
*
* #param givenClass_ the given class_
* #param methodName_ the method name
* #param failIfException_ if true, the method will fail
* #param parametersClass_ the parameters
* #return the method
*/
public static Method getMethod(Class<?> givenClass_, String methodName_, boolean failIfException_, Class<?> ... parametersClass_) {
Method _method = null;
try {
_method = givenClass_.getDeclaredMethod(methodName_, parametersClass_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("A method called \"" + methodName_ + "\" could not be retrieved: " + _exception.getMessage());
} else {
return null;
}
}
_method.setAccessible(true);
return _method;
}
/**
* Gets the field.
*
* #param givenClass_ the given class
* #param fieldName_ the field name
* #param failIfException_ if true then the method will fail if an exception is thrown
* #return the field
*/
public static Field getField(Class<?> givenClass_, String fieldName_, boolean failIfException_) {
Field _field = null;
try {
_field = givenClass_.getDeclaredField(fieldName_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("A field called \"" + fieldName_ + "\" could not be retrieved: " + _exception.getMessage());
} else {
return null;
}
}
_field.setAccessible(true);
return _field;
}
/**
* assign value to a field.
*
* #param field_ the given field
* #param parentObject_ the parent containing the field
* #param failIfException_ if true then the method will fail if an exception is thrown
* #param value_ the value to assign to the field
* #return the field
*/
public static boolean assignValueToField(Field field_, Object parentObject_, boolean failIfException_, Object value_) {
try {
field_.set(parentObject_, value_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("An exception has occured while setting a value to a field: " + _exception.getMessage());
}
return false;
}
return true;
}
/**
* Gets the field value from a given object.
*
* #param object_ the object
* #param fieldName_ the field name
* #param failIfException_ if true, this method will fail if an exception is thrown
* #return the field value from object
*/
public static Object getFieldValueFromObject(Object object_, String fieldName_, boolean failIfException_) {
Field _givenField = getField(object_.getClass(), fieldName_, failIfException_);
Object _returnedValue = null;
if (_givenField == null) {
return null;
} else {
try {
_returnedValue = _givenField.get(object_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("An exception has occured while retrieving a value from a field : " + _exception.getMessage());
} else {
return null;
}
}
}
return _returnedValue;
}
/**
* Gets the constructor.
*
* #param givenClass_ the given class
* #param failIfException_ if true, a fail statement will be issued when an exception is thrown
* #param parametersClasses_ the parameters classes_
* #return the constructor
*/
public static Constructor<?> getConstructor(Class<?> givenClass_, boolean failIfException_, Class<?> ... parametersClasses_) {
Constructor<?> _constructor = null;
try {
_constructor = givenClass_.getDeclaredConstructor(parametersClasses_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("The constructor from the class \"" + givenClass_.getName() + "\" could not be retrieved");
} else {
return null;
}
}
_constructor.setAccessible(true);
return _constructor;
}
/**
* Instantiante an object.
*
* #param givenClass_ the given class
* #param failIfException_ if true then a fail statement will be issued if an exception is thrown
* #param parametersClasses_ the parameters classes
* #param parameters_ the parameters
* #return the object
*/
public static Object instantianteAnObject(Class<?> givenClass_, boolean failIfException_, Class<?> [] parametersClasses_, Object... parameters_) {
Constructor<?> _constructor = getConstructor(givenClass_, failIfException_, parametersClasses_);
Object _returnedObject = null;
if (_constructor != null) {
try {
_returnedObject = _constructor.newInstance(parameters_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("An instance of " + givenClass_.getName() + " could not be created : " + _exception.getMessage());
} else {
return null;
}
}
}
return _returnedObject;
}
}