#autowire annotation not working - java

I have a controller GGSNAcceptController.java:
package com.viettel.pcrf.controller;
import com.viettel.fw.Exception.LogicException;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.fw.web.controller.BaseController;
import com.viettel.pcrf.common.Const;
import com.viettel.pcrf.dto.GgsnAcceptDTO;
import com.viettel.pcrf.webconfig.service.GgsnAcceptService;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#ManagedBean(name = "ggsnAcceptController")
#Scope("view")
public class GGSNAcceptController extends BaseController implements Serializable, BaseTableCTRL {
/**
* VARIABLES & GETTER/SETTER
*/
private GgsnAcceptDTO ggsnAccept;
private GgsnAcceptDTO selectedGgsnAccept;
private List<GgsnAcceptDTO> listGgsnAccept;
public GgsnAcceptDTO getGgsnAccept() {
return ggsnAccept;
}
public void setGgsnAccept(GgsnAcceptDTO ggsnAccept) {
this.ggsnAccept = ggsnAccept;
}
public GgsnAcceptDTO getSelectedGgsnAccept() {
return selectedGgsnAccept;
}
public void setSelectedGgsnAccept(GgsnAcceptDTO selectedGgsnAccept) {
this.selectedGgsnAccept = selectedGgsnAccept;
}
public List<GgsnAcceptDTO> getListGgsnAccept() {
return listGgsnAccept;
}
public void setListGgsnAccept(List<GgsnAcceptDTO> listGgsnAccept) {
this.listGgsnAccept = listGgsnAccept;
}
/**
* SERVICE
*
*/
#Autowired
private GgsnAcceptService ggsnAcceptServ;
/**
* INIT
*
*/
#PostConstruct
#Override
public void init() {
updateCtrl();
}
#Override
public void updateCtrl() {
clear();
System.out.println(ggsnAcceptServ == null);
listGgsnAccept = ggsnAcceptServ.findAll();
}
private String ggsnAcceptSelected;
#Override
public void updateDB() {
try {
if (ggsnAccept == null) {
throw new LogicException("nullSelected", "GGSN Config is not yet selected!");
}
if (formStatus == Const.BTN_ADD && ggsnAcceptServ.isExisted(ggsnAccept)) {
throw new LogicException("insertExisted", "GGSN Config existed!");
}
// if (systemCfgSelected != null && systemCfgSelected.equals(systemCfg.getSystemCfgName()) && langServ.isExisted(systemCfg)) {
// throw new LogicException("updateExisted", "GGSN Config is existed!");
// }
BaseMessage msg = ggsnAcceptServ.updateGgsn(ggsnAccept);
if (msg.isSuccess()) {
reportSuccess("msgInfo", "Success");
}
updateCtrl();
selectedGgsnAccept = (GgsnAcceptDTO) msg.getOutputObject();
} catch (LogicException ex) {
reportError("msgInfo", ex.getDescription());
} catch (Exception ex) {
logger.error(ex, ex);
}
}
#Override
public void deleteDB() {
try {
if (ggsnAccept == null) {
throw new LogicException("nullSelected", "GGSN Config is not selected yet!");
}
BaseMessage msg = ggsnAcceptServ.deleteGgsn(ggsnAccept);
if (msg.isSuccess()) {
reportSuccess("msgInfo", "msg.delete.success");
}
updateCtrl();
} catch (LogicException ex) {
reportError("msgInfo", ex.getDescription());
} catch (Exception ex) {
logger.error(ex, ex);
}
}
#Override
public void prepareAdd() {
ggsnAccept = new GgsnAcceptDTO();
selectedGgsnAccept = null;
}
#Override
public void prepareEdit() {
if (selectedGgsnAccept != null) {
ggsnAccept = selectedGgsnAccept;
}
}
#Override
public void prepareDelete() {
if (selectedGgsnAccept != null) {
ggsnAccept = selectedGgsnAccept;
}
}
#Override
public void clear() {
selectedGgsnAccept = null;
ggsnAccept = null;
}
#Override
public void onRowChangeListener() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
An interface GgsnAcceptService.java:
package com.viettel.pcrf.webconfig.service;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.pcrf.dto.GgsnAcceptDTO;
import java.util.List;
public interface GgsnAcceptService {
public List<GgsnAcceptDTO> findAll();
public List<GgsnAcceptDTO> findAll(List filters);
public BaseMessage updateGgsn(GgsnAcceptDTO ggsn) throws Exception;
public BaseMessage deleteGgsn(GgsnAcceptDTO ggsn) throws Exception;
public boolean isExisted(GgsnAcceptDTO ggsn) throws Exception;
}
And a class implement above interface:
package com.viettel.pcrf.webconfig.service;
import com.viettel.fw.common.util.extjs.FilterRequest;
import com.viettel.fw.dto.BaseMessage;
import com.viettel.pcrf.webconfig.repo.GgsnAcceptRepository;
import com.viettel.pcrf.common.util.mapper.GgsnAcceptMapper;
import com.viettel.pcrf.dto.GgsnAcceptDTO;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.viettel.service.BaseServiceImpl;
import java.util.ArrayList;
#Service
public class GgsnAcceptServiceImpl extends BaseServiceImpl implements GgsnAcceptService {
private GgsnAcceptMapper mapper = new GgsnAcceptMapper();
#Autowired
private GgsnAcceptRepository repository;
public Logger logger = Logger.getLogger(GgsnAcceptService.class);
#Override
public List<GgsnAcceptDTO> findAll(List filters) {
return mapper.toDtoBean(repository.findAll(repository.toPredicate(filters)));
}
#Override
public List<GgsnAcceptDTO> findAll() {
return mapper.toDtoBean(repository.findAll());
}
#Override
public BaseMessage updateGgsn(GgsnAcceptDTO ggsn) throws Exception {
BaseMessage msg = new BaseMessage();
GgsnAcceptDTO newGgsn = mapper.toDtoBean(repository.saveAndFlush(mapper.toPersistenceBean(ggsn)));
msg.setOutputObject(newGgsn);
msg.setSuccess(true);
return msg;
}
#Override
public boolean isExisted(GgsnAcceptDTO ggsn) throws Exception {
List<FilterRequest> listReq = new ArrayList<>();
listReq.add(new FilterRequest("IP", ggsn.getIp()));
return repository.findOne(repository.toPredicate(listReq)) != null;
}
#Override
public BaseMessage deleteGgsn(GgsnAcceptDTO ggsn) throws Exception {
BaseMessage msg = new BaseMessage();
repository.delete(mapper.toPersistenceBean(ggsn));
msg.setSuccess(true);
return msg;
}
}
I got an null error when trying to access a page call controller. Is there anything wrong with my code ?
My property ggsnAcceptServ always null although i have already set autowired for it. I'm new in Spring, please help to explain why this property null. Any help would be great.

You have a problem mixing jsf and spring:
#Component
#ManagedBean(name = "ggsnAcceptController")
#Scope("view")
Your controller will be executed in jsf context not in spring context. Thats why autowiering not working.

Related

Cannot invoke "javax.swing.ActionMap.remove(Object)" because the return value of "javax.swing.AbstractButton.getActionMap()" is null [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 days ago.
Improve this question
I'm currently developing a JNLP application.
Application starts its "Splash Screen Loading Screen" phase of launch, but then crashes into my SystemShutDownUtility with the Error Log posted below.
I am unsure of how to fix this error as I am not seeing any bits of the code that is the problem. It's not showing the usual "Caused By..." log either.
I can and will add any class files that will help you guys assist me in resolving this issue.
Its probably really simple and I'm probably missing it cause its so late but any help on this is greatly appreciated!
Error Log:
java.lang.NullPointerException: Cannot invoke "javax.swing.ActionMap.remove(Object)" because the return value of "javax.swing.AbstractButton.getActionMap()" is null
at java.desktop/javax.swing.plaf.basic.BasicButtonUI.uninstallListeners(BasicButtonUI.java:244)
at java.desktop/javax.swing.plaf.basic.BasicButtonUI.uninstallUI(BasicButtonUI.java:211)
at java.desktop/javax.swing.JComponent.uninstallUIAndProperties(JComponent.java:745)
at java.desktop/javax.swing.JComponent.setUI(JComponent.java:720)
at java.desktop/javax.swing.AbstractButton.setUI(AbstractButton.java:1758)
at com.cthsprojects.apphost.ui.decorator.AppMenuToggleButtonDecorator.decorate(AppMenuToggleButtonDecorator.java:27)
at com.cthsprojects.apphost.ui.decorator.V7MenuToggleButtonDecorator.decorate(V7MenuToggleButtonDecorator.java:22)
at com.cthsprojects.apphost.ui.decorator.AppMenuToggleButtonDecorator.decorate(AppMenuToggleButtonDecorator.java:1)
at com.cthsprojects.common.view.adapters.AbstractComponentAdapterImpl.addDecorator(AbstractComponentAdapterImpl.java:63)
at com.cthsprojects.apphost.ui.ToolsSubMenuAdapter.addApplication(ToolsSubMenuAdapter.java:176)
at com.cthsprojects.apphost.ui.ToolsSubMenuAdapter.addDomainComponents(ToolsSubMenuAdapter.java:160)
at com.cthsprojects.apphost.ui.ToolsSubMenuAdapter.<init>(ToolsSubMenuAdapter.java:89)
at com.cthsprojects.apphost.ui.ToolsSubMenuAdapter.addDomainComponents(ToolsSubMenuAdapter.java:163)
at com.cthsprojects.apphost.ui.ToolsSubMenuAdapter.<init>(ToolsSubMenuAdapter.java:79)
at com.cthsprojects.apphost.ui.ToolsMenuAdapter.initialize(ToolsMenuAdapter.java:37)
at com.cthsprojects.apphost.ui.AppTopPanelAdapterImpl.initialize(AppTopPanelAdapterImpl.java:59)
at com.cthsprojects.apphost.loader.AppHostRootFrameImpl.initialize(AppHostRootFrameImpl.java:84)
at com.cthsprojects.apphost.launch.AppHost.run(AppHost.java:107)
at com.cthsprojects.apphost.launch.AppHost.main(AppHost.java:56)
AppHost Class File:
package com.cthsprojects.apphost.launch;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Locale;
import java.util.Properties;
import javax.jnlp.ServiceManager;
import javax.jnlp.SingleInstanceListener;
import javax.jnlp.SingleInstanceService;
import javax.jnlp.UnavailableServiceException;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.border.EtchedBorder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.support.GenericApplicationContext;
import com.cthsprojects.apphost.context.ApplicationLoader;
import com.cthsprojects.apphost.exceptiontracer.ExceptionLogger;
import com.cthsprojects.apphost.loader.AppHostRootFrame;
import com.cthsprojects.apphost.splash.SplashScreen;
import com.cthsprojects.common.components.decorators.StyleDecorator;
import com.cthsprojects.common.ui.theme.SSLookAndFeel;
import com.cthsprojects.common.ui.util.SwingUtils;
import com.cthsprojects.common.view.adapters.decorators.AdapterDecorator;
import com.cthsprojects.common.view.adapters.decorators.QAToolTipDecorator;
import com.cthsprojects.common.view.adapters.factory.AdapterFactory;
import com.cthsprojects.configuration.AppHostOptions;
import com.cthsprojects.configuration.ConfigurationBuilder;
import com.cthsprojects.configuration.ConfigurationException;
import com.cthsprojects.configuration.LoggingOutputStream;
import com.cthsprojects.configuration.ProfileNotFoundException;
import com.cthsprojects.configuration.UniversalOptions;
public class AppHost {
public static final String SOCRATES_VERSION = "4.26.7";
public static SingleInstanceListener sisL = null;
SingleInstanceService sis;
private AppHostRootFrame root;
private SplashScreen splashScreen;
private ExceptionLogger exceptionLogger;
public static void main(String[] args) {
AppHost host = new AppHost();
host.run();
}
void run() {
preventMultiLaunchIfJNLP();
StringBuilder startSocratesText = new StringBuilder();
startSocratesText.append("Starting Socrates (");
startSocratesText.append("4.26.7");
startSocratesText.append(")");
System.out.println(startSocratesText.toString());
String profile = System.getProperty("profile");
ConfigurationBuilder.getInstance().getLoggingConfigurer().configure(profile);
final Log LOGGER = LogFactory.getLog(AppHost.class);
LOGGER.info(startSocratesText.toString());
setC3P0Properties();
String os = System.getProperty("os.name").toLowerCase();
String javaVersion = System.getProperty("java.version").toLowerCase();
if (os.startsWith("win") && javaVersion.startsWith("1.8")) {
System.setOut(new PrintStream((OutputStream)new LoggingOutputStream(Logger.getLogger("sysout"), Level.INFO), true));
System.setErr(new PrintStream((OutputStream)new LoggingOutputStream(Logger.getLogger("sysout"), Level.ERROR), true));
}
restoreMultiLaunchIfConfigurationOff();
SwingUtils.switchToSSLookAndFeel();
if (this.splashScreen == null)
this.splashScreen = new SplashScreen();
showSplashScreen();
Thread.UncaughtExceptionHandler killSplash = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread arg0, Throwable e) {
String errorString;
if (e instanceof ExceptionInInitializerError) {
errorString = e.getCause().toString();
} else {
errorString = e.toString();
}
LOGGER.error("An error occurred with splash", e);
AppHost.this.splashScreen.error(errorString);
}
};
Thread.setDefaultUncaughtExceptionHandler(killSplash);
GenericApplicationContext factory = ApplicationLoader.getInstance().getFactory();
if (this.exceptionLogger == null) {
this.exceptionLogger = (ExceptionLogger)factory.getBean(ExceptionLogger.class.getSimpleName());
this.exceptionLogger.setSplashScreen(this.splashScreen);
}
if (this.root == null)
this.root = (AppHostRootFrame)factory.getBean(AppHostRootFrame.class.getSimpleName());
Thread.setDefaultUncaughtExceptionHandler((Thread.UncaughtExceptionHandler)this.exceptionLogger);
checkProfileSet();
overrideDefaultLocale();
setupToolTips();
setupDebug();
this.root.initialize(ApplicationLoader.getInstance().getApplicationDomains());
this.splashScreen.dispose();
this.root.setVisible(true);
this.root.setAlwaysOnTop(false);
}
private void setC3P0Properties() {
Log LOGGER = LogFactory.getLog(AppHost.class);
Properties prop = new Properties(System.getProperties());
InputStream input = getResourceFileAsInputStream("c3p0.properties");
if (input == null) {
LOGGER.info("Using c3p0-default.properties");
prop = loadProperties(prop, "c3p0-default.properties");
} else {
LOGGER.info("Using c3p0.properties");
}
prop.put("com.mchange.v2.log.MLog", "com.mchange.v2.log.log4j.Log4jMLog");
System.setProperties(prop);
}
private Properties loadProperties(Properties prop, String fileName) {
Log LOGGER = LogFactory.getLog(AppHost.class);
try {
InputStream input = getResourceFileAsInputStream(fileName);
prop.load(input);
} catch (IOException ex) {
LOGGER.error("Failed to read " + fileName, ex);
}
return prop;
}
private InputStream getResourceFileAsInputStream(String fileName) {
ClassLoader classLoader = AppHost.class.getClassLoader();
return classLoader.getResourceAsStream(fileName);
}
private void restoreMultiLaunchIfConfigurationOff() throws BeansException, ConfigurationException {
if (null != sisL &&
!AppHostOptions.getInstance().isSingleLaunch())
this.sis.removeSingleInstanceListener(sisL);
}
private void preventMultiLaunchIfJNLP() {
try {
this.sis = (SingleInstanceService)ServiceManager.lookup("javax.jnlp.SingleInstanceService");
sisL = new SingleInstanceListener() {
public void newActivation(String[] as) {}
};
this.sis.addSingleInstanceListener(sisL);
} catch (UnavailableServiceException e) {
this.sis = null;
}
}
private void showSplashScreen() {
if (AppHostOptions.getInstance().isSplashScreenEnabled())
this.splashScreen.setVisible(true);
}
private void checkProfileSet() {
if (System.getProperty("profile") == null)
throw new ProfileNotFoundException("Please specify a profile in sysargs\n\n\t-Dprofile=deploy");
}
private void setupToolTips() {
boolean qaToolTipsEnabled = UniversalOptions.getInstance().isQaToolTipsEnabled();
if (qaToolTipsEnabled) {
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setInitialDelay(10);
ToolTipManager.sharedInstance().setDismissDelay(7000);
AdapterFactory.addDefaultDecorator((AdapterDecorator)new QAToolTipDecorator());
}
SSLookAndFeel.setSScrolBarQAMode(qaToolTipsEnabled);
}
private void setupDebug() {
boolean uiDebugEnabled = UniversalOptions.getInstance().isUIDebugEnabled();
if (uiDebugEnabled) {
StyleDecorator debugStyle = new StyleDecorator();
debugStyle.setBorder(new EtchedBorder());
debugStyle.setNoFont(true);
AdapterFactory.addDefaultDecorator((AdapterDecorator)debugStyle);
}
}
private void overrideDefaultLocale() {
String localeOverride = System.getProperty("LocaleOverride");
if (localeOverride != null) {
Locale localeOverrideObject;
String[] localeArray = localeOverride.split("_");
switch (localeArray.length) {
case 1:
localeOverrideObject = new Locale(localeArray[0]);
break;
case 2:
localeOverrideObject = new Locale(localeArray[0], localeArray[1]);
break;
case 3:
localeOverrideObject = new Locale(localeArray[0], localeArray[1], localeArray[2]);
break;
default:
return;
}
Locale.setDefault(localeOverrideObject);
}
}
void setRootFrame(AppHostRootFrame root) {
this.root = root;
}
void setSplashScreen(SplashScreen splashScreen) {
this.splashScreen = splashScreen;
}
void setExceptionLogger(ExceptionLogger exceptionLogger) {
this.exceptionLogger = exceptionLogger;
}
}
ApplicationLoader class file:
package com.cthsprojects.apphost.context;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.support.GenericApplicationContext;
import com.cthsprojects.apphost.application.SocratesApplication;
import com.cthsprojects.apphost.applications.domains.ApplicationDomain;
import com.cthsprojects.apphost.applications.domains.DomainComponent;
import com.cthsprojects.apphost.applications.domains.DomainType;
import com.cthsprojects.apphost.resources.AppHostErrorMessagesTextToken;
import com.cthsprojects.application.login.LoginSocratesApplication;
import com.cthsprojects.common.view.adapters.PanelAdapter;
import com.cthsprojects.common.view.adapters.factory.AdapterFactory;
import com.cthsprojects.configuration.ConfigurationBuilder;
public final class ApplicationLoader {
private static ApplicationLoader instance;
private static List<SocratesApplication> applications;
private static final int MAP_INITIAL_CAPACITY = 4;
private final Map<DomainType, ApplicationDomain> domains;
private ApplicationLoader() {
ApplicationDomain defaultDomain = (ApplicationDomain)getFactory().getBean(DomainType.getDefaultDomainTypeName());
applications = new ArrayList<SocratesApplication>(BeanFactoryUtils.beansOfTypeIncludingAncestors((ListableBeanFactory)getFactory(), SocratesApplication.class).values());
for (Iterator<SocratesApplication> itr = applications.iterator(); itr.hasNext(); ) {
SocratesApplication app = itr.next();
ApplicationDomain dom = app.getApplicationDomain();
if (null == dom)
app.setApplicationDomain(defaultDomain);
}
this.domains = new HashMap<DomainType, ApplicationDomain>(4, 1.0F);
Collection<SocratesApplication> doms = BeanFactoryUtils.beansOfTypeIncludingAncestors((ListableBeanFactory)getFactory(), ApplicationDomain.class).values();
for (Iterator<SocratesApplication> iterator1 = doms.iterator(); iterator1.hasNext(); ) {
ApplicationDomain d = (ApplicationDomain)iterator1.next();
this.domains.put(d.getDomainType(), d);
}
}
public static ApplicationLoader getInstance() {
if (instance == null)
instance = new ApplicationLoader();
return instance;
}
public void close() {
for (Iterator<SocratesApplication> itr = applications.iterator(); itr.hasNext(); ) {
SocratesApplication app = itr.next();
app.doExit();
}
getFactory().close();
getFactory().destroy();
SharedContext.reset();
}
public Collection<ApplicationDomain> getApplicationDomains() {
return Collections.unmodifiableCollection(this.domains.values());
}
public Collection<SocratesApplication> getApplications() {
Collection<SocratesApplication> ans = applications;
if (ans == null)
ans = new ArrayList<SocratesApplication>();
return Collections.unmodifiableCollection(ans);
}
public SocratesApplication getApplicationByName(String applicationName) {
SocratesApplication targetApp = null;
for (SocratesApplication application : applications) {
if (application.getClass().getSimpleName().equals(applicationName)) {
targetApp = application;
break;
}
}
return targetApp;
}
public SocratesApplication getLoginApplication() {
return (SocratesApplication)getFactory().getBean(LoginSocratesApplication.class.getSimpleName());
}
public GenericApplicationContext getFactory() {
return ConfigurationBuilder.getInstance().getApplicationFactory();
}
public ApplicationDomain getDomain(DomainType aType) {
if (null == aType)
throw new NullPointerException();
ApplicationDomain d = this.domains.get(aType);
if (null == d)
throw new IllegalArgumentException(AppHostErrorMessagesTextToken.ERROR_INVALID_DOMAIN_TYPE.getText(new Object[] { aType.getName() }));
return d;
}
public List<SocratesApplication> findApplicationsForDomain(ApplicationDomain aApplicationDomain) {
List<SocratesApplication> l = new ArrayList<SocratesApplication>();
Iterator<DomainComponent> itr = aApplicationDomain.getChildren().iterator();
while (itr.hasNext()) {
DomainComponent dc = itr.next();
findApps(l, dc);
}
return l;
}
private List<SocratesApplication> findApps(List<SocratesApplication> aList, DomainComponent aDomainComponent) {
if (aDomainComponent.isLeaf()) {
aList.add(aDomainComponent.getAdaptee());
return aList;
}
for (Iterator<DomainComponent> itr = aDomainComponent.getChildren().iterator(); itr.hasNext(); ) {
DomainComponent child = itr.next();
findApps(aList, child);
}
return aList;
}
public void reset() {
for (Iterator<SocratesApplication> itr = applications.iterator(); itr.hasNext(); ) {
SocratesApplication app = itr.next();
if (app.isInitialized()) {
resetLocations(app);
app.reset();
}
}
}
private void resetLocations(SocratesApplication application) {
PanelAdapter containerPanel = AdapterFactory.getTracker().getPanel(null, "Host.CentrePanel.Container");
if (null != containerPanel)
containerPanel.removeAll();
}
}

ProducerTemplate. Camel. How to add attachment

Can someone tell me how to add an attachment using ProducerTemplate?
I have been searching but I can not find an answer to my case.
I am using Camen 2.1 and I have these three clases:
MailSender2.java
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
public class MailSender2 extends TypeMail{
private static final ResourceBundle RES = ResourceBundle.getBundle("mail");
protected static final String MAIL_NOTIFICATION_ENDPOINT=RES.getString("mail.host.location").trim()+":"+RES.getString("mail.port").trim();
private Map<String, Object> header;
public MailSender2() {
this.header=new HashMap<>();
}
public void send(ProducerTemplate template) {
this.header.put("From", this.getT_from());
this.header.put("To", this.getT_to());
this.header.put("Subject", this.getT_subject());
this.header.put(Exchange.CONTENT_TYPE, "text/html; charset=UTF-8");
//this.getF_ficher() <-- I have here the file to attach
//this.getT_ficnon() <-- I have here the name ot the file
//this.getT_ficext() <-- I have here the extension ot the file
template.sendBodyAndHeaders(MAIL_NOTIFICATION_ENDPOINT, this.getT_mensaje(), header);
}
}
TypeMail.java:
public class TypeMail {
private String t_id;
private String t_from;
private String t_to;
private String t_subject;
private String t_mensaje;
private byte[] f_ficher;
private String t_ficnon;
private String t_ficext;
public String getT_id() {
return t_id;
}
public void setT_id(String t_id) {
this.t_id = t_id;
}
public String getT_from() {
return t_from;
}
public void setT_from(String t_from) {
this.t_from = t_from;
}
public String getT_to() {
return t_to;
}
public void setT_to(String t_to) {
this.t_to = t_to;
}
public String getT_subject() {
return t_subject;
}
public void setT_subject(String t_subject) {
this.t_subject = t_subject;
}
public String getT_mensaje() {
return t_mensaje;
}
public void setT_mensaje(String t_mensaje) {
this.t_mensaje = t_mensaje;
}
public byte[] getF_ficher() {
return f_ficher;
}
public void setF_ficher(byte[] f_ficher) {
this.f_ficher = f_ficher;
}
public String getT_ficnon() {
return t_ficnon;
}
public void setT_ficnon(String t_ficnon) {
this.t_ficnon = t_ficnon;
}
public String getT_ficext() {
return t_ficext;
}
public void setT_ficext(String t_ficext) {
this.t_ficext = t_ficext;
}
}
MailCommunicationTransformer.java:
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.soap.client.SoapFaultClientException;
public class MailCommunicationTransformer {
MailSender2 mailSender = null;
static Logger logger = LoggerFactory.getLogger(MailCommunicationTransformer.class);
public MailCommunicationTransformer()
{
}
public MailLog transform(Object actualMessage, Exchange exchange, CamelContext context)
{
mailSender = exchange.getIn().getBody(MailSender2.class);
try {
MailSenderDAO mailSenderDAO = (MailSenderDAO)context.getRegistry().lookup("MailSenderDAO");
mailSenderDAO.validarInput(mailSender);
if (mailSender!=null) {
ProducerTemplate template=exchange.getContext().createProducerTemplate();
try {
mailSender.send(template);
}
catch (Throwable ex) {
ex.printStackTrace();
exchange.setProperty(Exchange.EXCEPTION_CAUGHT,ex);
}
}
}catch (MailException me) {
me.printStackTrace();
exchange.setProperty(Exchange.EXCEPTION_CAUGHT,me);
}
Throwable e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT,
Throwable.class);
String response = "OK";
if (e != null) {
StringBuffer mensaje = new StringBuffer();
if (e instanceof SoapFaultClientException) {
mensaje.append("MAIL fault exception: CLIENT. ");
} else {
mensaje.append("MAIL fault exception: MAIL. ");
}
logger.info("MailCommunicationTransformer",e);
while (e != null) {
e.printStackTrace();
mensaje.append(e.getMessage());
e = e.getCause();
}
response = mensaje.toString();
}
MailLog log = new MailLog(mailSender, response); //, protocolo
return log;
}
}
In TypeMail I have the file in f_ficher, and the fileName (t_ficnon) and extension (t_ficext), but I can not find how to attach this file in MailSender2 before template.sendBodyAndHeaders(.....)
Any help would be very appreciated.
Regards.
Perhaps I don't fully understand your question, but the ProducerTemplate don't know about the message type.
You just send a body and perhaps also headers to an endpoint.
Therefore the body just needs to be a fully constructed MimeMessage object as documented in the Camel Mail docs.
You can simply construct the mail message with Java and then use the object with the ProducerTemplate (what you already do).
template.sendBodyAndHeaders("your-smtp-endpoint", yourMimeMessageInstance, yourHeaderMap);
Thanks for the answer!
But, finally, I could do it this way:
new class EmailProcessor.java
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.util.Objects;
import java.util.ResourceBundle;
import javax.activation.DataHandler;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.commons.codec.binary.Base64;
public class EmailProcessor implements Processor {
// Atributos de la clase
private TypeMail typeMail;
public EmailProcessor(TypeMail typeMail) {
this.typeMail = typeMail;
}
#Override
public void process(Exchange exchange) throws Exception {
Message ms = exchange.getIn();
ms.setHeader("From", this.typeMail.getT_from());
ms.setHeader("To", this.typeMail.getT_to());
ms.setHeader("Subject", this.typeMail.getT_subject());
ms.setHeader(Exchange.CONTENT_TYPE, "text/html; charset=UTF-8");
ms.setBody("<p style='font-family: Calibri;'>" + this.typeMail.getT_mensaje() + "</p>");
if (this.typeMail.getF_ficher() != null) {
String mimeType = "application/pdf";
if ("zip".equals(typeMail.getT_ficext())) {
mimeType = "application/zip";
}
ms.addAttachment(typeMail.getT_ficnom() + "." + typeMail.getT_ficext(), new DataHandler(typeMail.getF_ficher(), mimeType));
}
}
}
MailSender.java:
import java.util.ResourceBundle;
import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
public class MailSender extends TypeMail{
private static final ResourceBundle RES = ResourceBundle.getBundle("mail");
protected static final String MAIL_NOTIFICATION_ENDPOINT=RES.getString("mail.host.location").trim()+":"+RES.getString("mail.port").trim();
public MailSender() {
}
public void send(ProducerTemplate template) {
template.send(MAIL_NOTIFICATION_ENDPOINT, ExchangePattern.InOnly, new EmailProcessor(this));
}
}

Mock getInstance() of a singleton to return child class (Quarkus)

I am trying to mock getInstance() of a singleton class below to return a mocked class instead:
Base class (passo9() is the method to be mocked):
package br.com.bb.ids.robo.passo09;
import br.com.bb.ids.robo.passo09.dao.RoboSkipDao;
import br.com.bb.ids.robo.passo09.exceptions.RoboSkipDaoFindException;
import br.com.bb.ids.robo.passo09.exceptions.RoboSkipDaoMergeException;
import br.com.bb.ids.robo.passo09.models.RoboSkip;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class Motor {
private static Motor instance;
public static Motor getInstance() {
if (instance == null) {
instance = new Motor();
}
return instance;
}
private Motor() {}
/**
* Method to be mocked
*
* #return error code (0 if successful)
* #throws Exception any non expected exception
*/
public int passo9() throws Exception {
try {
System.out.println("Verifica o ponto onde o robô parou");
RoboSkipDao rsDao = RoboSkipDao.getInstance();
RoboSkip rs = rsDao.findByPasso(9);
int resultadoPasso = Integer.parseInt(rs.getValor());
rs.setValor(Integer.toString(resultadoPasso + 32768));
rsDao.merge(rs);
}
catch (RoboSkipDaoFindException e) {
System.out.println("Erro ao consultar registro em robo_skip, passo = 9.");
e.printStackTrace();
return 2;
}
catch (NumberFormatException e) {
System.out.println("Número do registro inválido em robo_skip, passo 9.");
e.printStackTrace();
return 3;
}
catch (RoboSkipDaoMergeException e) {
System.out.println("Erro ao atualizar registro em robo_skip, passo 9.");
e.printStackTrace();
return 8;
}
return 0;
}
}
The extended class to be called instead of Motor above:
package br.com.bb.ids.robo.passo09;
import io.quarkus.test.Mock;
import javax.enterprise.context.ApplicationScoped;
#Mock
#ApplicationScoped
public class MotorMock extends Motor {
public MotorMock(Motor m) {}
#Override
public int passo9() throws Exception {
System.out.println("passo9() mockado - return 0");
return 0;
}
}
The Quarkus main class (Motor.getInstance() should return MotorMock instead of Motor in my test below):
package br.com.bb.ids.robo.passo09;
import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.annotations.QuarkusMain;
#QuarkusMain
public class Main {
public static void main(String[] args) {
if (args.length != 1 || !args[0].matches("true|false")) {
System.err.println("Indicação em desenvolvimento (true/false) obrigatória.");
return;
}
boolean emDesenvolvimento = Boolean.parseBoolean(args[0]);
System.out.println("Iniciando aplicação...");
try {
Motor motor = Motor.getInstance();
motor.setEmDesenvolvimento(emDesenvolvimento);
int returnCode = motor.passo9();
System.out.println("Finalizando aplicação...");
Quarkus.asyncExit(returnCode);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My test module:
package br.com.bb.ids.robo.passo09;
import io.quarkus.test.junit.QuarkusMock;
import io.quarkus.test.junit.QuarkusTest;
import javax.inject.Inject;
import org.junit.jupiter.api.Test;
#QuarkusTest
public class MainTest {
#Inject
Motor motor;
#Test
public void testMain() {
MotorMock mm = new MotorMock(Motor.getInstance());
Mockito.when(((Motor)mm).getInstance()).thenReturn(mm);
QuarkusMock.installMockForType(mm, Motor.class);
System.out.println("Testando Main.main(args)...");
String[] args = new String[1];
args[0] = "true";
Main.main(args);
System.out.println("Testes com Main.main(args) efetuados com sucesso.");
}
}
I want to call MotorMock.passo9() instead of Motor.passo9() inside my test case. How do I achieve this? If possible, share with code example.

map.size() not working with static map

Hey i am trying to get the size of Static map from other class...
i am defining Static map in one class...as
tasklet.class
package com.hcsc.ccsp.nonadj.subrogation.integration;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import com.hcsc.ccsp.nonadj.subrogation.batch.Subrogation;
import com.hcsc.ccsp.nonadj.subrogation.common.SubrogationConstants;
/**
* #author Manan Shah
*
*/
public class SubrogationFileTransferTasklet implements Tasklet,
InitializingBean {
private Logger logger = LogManager
.getLogger(SubrogationFileTransferTasklet.class);
private Resource inputfile;
private Resource outputfile;
public static String fileLastName;
public static String header = null;
public static String trailer = null;
public static List<Subrogation> fileDataListSubro = new ArrayList<Subrogation>();
public List<String> fileDataListS = new ArrayList<String>();
public static TreeMap<String, Subrogation> map = new TreeMap<String, Subrogation>();
public int counter = 0;
public String value;
#Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(inputfile, "inputfile must be set");
}
public void setTrailer(String trailer) {
this.trailer = trailer;
}
public void setHeader(String header) {
this.header = header;
}
public String getTrailer() {
return trailer;
}
public String getHeader() {
return header;
}
public Resource getInputfile() {
return inputfile;
}
public void setInputfile(Resource inputfile) {
this.inputfile = inputfile;
}
public Resource getOutputfile() {
return outputfile;
}
public void setOutputfile(Resource outputfile) {
this.outputfile = outputfile;
}
public static void setFileDataListSubro(List<Subrogation> fileDataListSubro) {
SubrogationFileTransferTasklet.fileDataListSubro = fileDataListSubro;
}
public static List<Subrogation> getFileDataListSubro() {
return fileDataListSubro;
}
public static void setMap(TreeMap<String, Subrogation> map) {
SubrogationFileTransferTasklet.map = map;
}
public static TreeMap<String, Subrogation> getMap() {
return map;
}
#Override
public RepeatStatus execute(StepContribution contribution,
ChunkContext chunkContext) throws Exception {
value = (String) chunkContext.getStepContext().getStepExecution()
.getJobExecution().getExecutionContext().get("outputFile");
readFromFile();
return RepeatStatus.FINISHED;
}
public void readFromFile() {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inputfile.getFile()));
fileLastName = inputfile.getFile().getName();
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.indexOf("TRAILER") != -1) {
setTrailer(sCurrentLine);
} else if (sCurrentLine.indexOf("HEADER") != -1) {
setHeader(sCurrentLine);
} else if (sCurrentLine.equalsIgnoreCase("")) {
} else {
fileDataListS.add(sCurrentLine);
}
}
convertListOfStringToListOfSubrogaion(fileDataListS);
writeDataToFile();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void convertListOfStringToListOfSubrogaion(List<String> list) {
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
Subrogation subrogration = new Subrogation();
String s = iterator.next();
subrogration.setGRP_NBR(StringUtils.substring(s, 0, 6));
subrogration.setSECT_NBR(StringUtils.substring(s, 6, 10));
subrogration.setAFP_VAL(StringUtils.substring(s, 10, 13));
subrogration.setDOL_MIN_VAL(StringUtils.substring(s, 13, 20));
subrogration
.setCORP_ENT_CD(StringUtils.substring(s, 20, s.length()));
map.put(subrogration.getGRP_NBR() + subrogration.getSECT_NBR(),
subrogration);
fileDataListSubro.add(subrogration);
}
}
public void writeDataToFile() {
try {
File file = new File(value);
if (!file.exists()) {
logger.info("output file is:-" + file.getAbsolutePath());
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry subrogation = (Map.Entry) it.next();
// System.out.println(subrogation.getKey() + " = " +
// subrogation.getValue());
// it.remove(); // avoids a ConcurrentModificationException
bw.append(subrogation.getValue().toString()
+ SubrogationConstants.filler58);
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("subrogationFileTransferTasklet Step completes");
}
}
In processor i want to put map size into int.
processor.class
package com.hcsc.ccsp.nonadj.subrogation.processor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.item.ItemProcessor;
import com.hcsc.ccsp.nonadj.subrogation.Utils.SubrogationUtils;
import com.hcsc.ccsp.nonadj.subrogation.batch.Subrogation;
import com.hcsc.ccsp.nonadj.subrogation.common.SubrogationConstants;
import com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFileTransferTasklet;
public class SubrogationProcessor implements
ItemProcessor<Subrogation, Subrogation> {
public SubrogationFileTransferTasklet fileTransferTasklet = new SubrogationFileTransferTasklet();
SubrogationUtils subrogationUtils = new SubrogationUtils();
public int countFromFile=SubrogationFileTransferTasklet.map.size();
public static int totalRecords = 0;
public static int duplicate = 0;
#Override
public Subrogation process(Subrogation subrogration) throws Exception {
// TODO Auto-generated method stub
if (subrogationUtils.validateData(subrogration)) {
Subrogation newSubro = new Subrogation();
newSubro.setGRP_NBR(StringUtils.leftPad(subrogration.getGRP_NBR()
.trim(), SubrogationConstants.length6, "0"));
if (subrogration.getSECT_NBR().trim().length() < 5) {
newSubro.setSECT_NBR(StringUtils.leftPad(subrogration
.getSECT_NBR().trim(), SubrogationConstants.length4,
"0"));
} else if (subrogration.getSECT_NBR().trim().length() == 5) {
newSubro.setSECT_NBR(StringUtils.substring(subrogration.getSECT_NBR().trim(), 1));
} else {
return null;
}
newSubro.setAFP_VAL(StringUtils.leftPad(subrogration.getAFP_VAL()
.trim(), SubrogationConstants.length3, "0"));
if (subrogration.getDOL_MIN_VAL().trim().contains(".")) {
newSubro.setDOL_MIN_VAL(StringUtils.leftPad(StringUtils.substring(subrogration.getDOL_MIN_VAL(),0,subrogration.getDOL_MIN_VAL().indexOf(".")), SubrogationConstants.length7,
"0"));
} else {
newSubro.setDOL_MIN_VAL(StringUtils.leftPad(subrogration
.getDOL_MIN_VAL().trim(), SubrogationConstants.length7,
"0"));
}
newSubro.setCORP_ENT_CD(StringUtils.substring(
subrogration.getCORP_ENT_CD(), 0, 2));
if (SubrogationFileTransferTasklet.map.containsKey(newSubro
.getGRP_NBR() + newSubro.getSECT_NBR())) {
duplicate++;
return null;
} else {
if(SubrogationFileTransferTasklet.fileLastName.contains("TX")){
if(newSubro.getCORP_ENT_CD().equalsIgnoreCase("TX")){
SubrogationFileTransferTasklet.map.put(newSubro
.getGRP_NBR() + newSubro.getSECT_NBR(), newSubro);
totalRecords++;
return newSubro;
}
}
else{
if(SubrogationFileTransferTasklet.fileLastName.contains("IL")){
if(!newSubro.getCORP_ENT_CD().equalsIgnoreCase("TX"))
{
newSubro.setCORP_ENT_CD("IL");
SubrogationFileTransferTasklet.map.put(newSubro
.getGRP_NBR() + newSubro.getSECT_NBR(), newSubro);
totalRecords++;
return newSubro;
}
}
else{
return null;
}
}
return null;
}
}
else {
return null;
}
}
}
class SubrogrationException extends RuntimeException {
private static final long serialVersionUID = -8971030257905108630L;
public SubrogrationException(String message) {
super(message);
}
}
and at last i want to use that countFromFile in other class..
writer.class
package com.hcsc.ccsp.nonadj.subrogation.writer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileFooterCallback;
import org.springframework.batch.item.file.FlatFileHeaderCallback;
import com.hcsc.ccsp.nonadj.subrogation.Utils.SubrogationUtils;
import com.hcsc.ccsp.nonadj.subrogation.batch.Subrogation;
import com.hcsc.ccsp.nonadj.subrogation.common.SubrogationConstants;
import com.hcsc.ccsp.nonadj.subrogation.integration.SubrogationFileTransferTasklet;
import com.hcsc.ccsp.nonadj.subrogation.processor.SubrogationProcessor;
public class SubrogationHeaderFooterWriter implements FlatFileFooterCallback,FlatFileHeaderCallback{
private Logger logger = LogManager
.getLogger(SubrogationHeaderFooterWriter.class);
SubrogationFileTransferTasklet fileTransferTasklet = new SubrogationFileTransferTasklet();
SubrogationUtils subrogationUtils=new SubrogationUtils();
SubrogationProcessor processor=new SubrogationProcessor();
private ItemWriter<Subrogation> delegate;
public void setDelegate(ItemWriter<Subrogation> delegate) {
this.delegate = delegate;
}
public ItemWriter<Subrogation> getDelegate() {
return delegate;
}
#Override
public void writeHeader(Writer writer) throws IOException {
//writer.write(SubrogationFileTransferTasklet.header);
}
#Override
public void writeFooter(Writer writer) throws IOException {
String trailer = SubrogationFileTransferTasklet.trailer;
String s1 = StringUtils.substring(trailer, 0, 23);
logger.info(" Data from input file size is---- "+new SubrogationProcessor().countFromFile);
int trailerCounter=new SubrogationProcessor().countFromFile+SubrogationProcessor.totalRecords;
logger.info(" Data comming from database is"+SubrogationProcessor.totalRecords);
logger.info(" Duplicate data From DataBase is " +SubrogationProcessor.duplicate);
logger.info(" Traileer is " + s1+ trailerCounter);
writer.write(s1 + trailerCounter);
SubrogationFileTransferTasklet.map.clear();
SubrogationFileTransferTasklet.fileDataListSubro.clear();
SubrogationProcessor.totalRecords=0;
SubrogationProcessor.duplicate=0;
}
public void writeErrorDataToFile(List<String> errorDataList,String errorfile){
File file;
try {
file = new File(errorfile);
logger.info("error file is "+errorfile);
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWriter);
for(String data:errorDataList){
bufferWritter.write(new Date()+" "+data);
bufferWritter.write(SubrogationConstants.LINE_SEPARATOR);
}
bufferWritter.close();
}
catch (IOException e) {
throw new ItemStreamException("Could not convert resource to file: [" + errorfile + "]", e);
}
}
/*
public void write(List<? extends Subrogation> subrogation) throws Exception {
System.out.println("inside writer");
delegate.write(subrogation);
}*/
}
so here in logger massage.size prints 0....
I am not able to understand why???
Do in this way to make sure that It is initialized with the current size of the map when object is constructed.
class SubrogationProcessor{
public int countFromFile;
public SubrogationProcessor(){
countFromFile=SubrogationFileTransferTasklet.map.size();
}
}
This depends on when the "map.put" line of code is run. Is it in a static block in the tasklet class?
If processor instance is initialized before record has been added to the map then map.size() will indeed be 0.
my suggestion would be to add the map into a static block if at all possible or to debug the code and see when the .put() method is being called in comparison to when the .size() method is called
public static TreeMap<String, Subrogation> map = new TreeMap<String, Subrogation>();
static{
map.put(subrogration.getGRP_NBR() + subrogration.getSECT_NBR(), subrogration);
}

JAVA RMI dispatchUncaughtException - Interface casting problem

For school we made a Java application with RMI, there are 3 applications: Server, Client and Rekenaar.
The line where it goes wrong is the Line: "test = (Range[])m.getAllRange();", it gives an dispatchUncaughtException.
package rekenaar;
import server.Opdracht;
import java.rmi.Naming;
import java.util.logging.Level;
import java.util.logging.Logger;
import interfaces.*;
import java.rmi.RemoteException;
/**
*
* #author Windows
*/
public class Rekenaar implements Runnable{
private Range range;
private IRekenCoördinator coordinator;
private long[] priemgetallen;
private Opdracht op;
private Range[] test;
public Rekenaar()
{
try{
this.coordinator = null;
this.coordinator = (IRekenCoördinator) Naming.lookup("rmi://127.0.0.1:1099/RekenC");
this.priemgetallen = coordinator.getPriemgetallen();
this.op = null;
}catch(Exception ex){ex.printStackTrace();}
}
public void Bereken()
{
try{
long rangeOndergrens = (op.getGetal()/2000) * 2000;
range = new Range(priemgetallen, rangeOndergrens);
op.setRange(range);
op.setUitkomst(range.geefSemiPriem(op.getGetal()));
coordinator.RemoveID(op.CheckRange());
IMagazijn m = op.getMagazijn();
test = (Range[])m.getAllRange();
String hoi = m.hoi();
m.AddRange(op);
}catch(RemoteException ex){ex.printStackTrace();}
}
#Override
public void run() {
KrijgtOpdracht();
}
private void KrijgtOpdracht()
{
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Rekenaar.class.getName()).log(Level.SEVERE, null, ex);
}
if(coordinator != null)
{
try{
op = (Opdracht)coordinator.getOpdracht();
}
catch (Exception ex)
{
ex.printStackTrace();
}
if(op != null ) this.Bereken();
this.run();
}
}
}
Interface:
package interfaces;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* #author Windows
*/
public interface IMagazijn extends Remote {
/**
*
* #param op Uitgerekende opdracht waarvan de gegevens verwerkt moeten worden op de server
* #throws IOException
*/
public String hoi() throws RemoteException;
public IRange[] getAllRange() throws RemoteException;
public void AddRange(IOpdracht op) throws RemoteException;
}
And here is the Magazijn itself which gives the IRange over RMI:
package server;
import java.rmi.RemoteException;
import java.util.ArrayList;
import interfaces.*;
import java.rmi.server.UnicastRemoteObject;
public class Magazijn extends UnicastRemoteObject implements IMagazijn{
private IRange[] ranges;
private long ondergrens;
public void setOndergrens(long ondergrens) {
this.ondergrens = ondergrens;
}
private long bovengrens;
public void setBovengrens(long bovengrens) {
this.bovengrens = bovengrens;
}
private transient MagazijnManager MM;
private transient ArrayList<Opdracht> dubbeleOpdrachten;
private transient RekenCoördinator RC;
private transient int MAGAZIJN_GROOTTE;
public Magazijn(long ondergrens, long bovengrens, MagazijnManager mm, RekenCoördinator RC)throws RemoteException
{
ranges = new IRange[(int)(bovengrens-ondergrens)/2000];
this.bovengrens = bovengrens;
this.ondergrens = ondergrens;
dubbeleOpdrachten = new ArrayList<Opdracht>();
this.MM = mm;
this.RC = RC;
MAGAZIJN_GROOTTE = (int)(bovengrens - ondergrens) + 1;
}
public void AddRange(IOpdracht op) throws RemoteException
{
ArrayList<IOpdracht> returnList = new ArrayList<IOpdracht>();
ranges[op.getRangeIndex()] = op.getRange();
returnList.add(op);
for(Opdracht o : dubbeleOpdrachten)
{
if(o.getRangeIndex() == op.getRangeIndex())
{
o.setRange(op.getRange());
o.setUitkomst(o.getRange().geefSemiPriem(o.getGetal()));
returnList.add(o);
}
}
MM.StuurOpdrachtenTerug(returnList);
}
public IRange[] getAllRange() throws RemoteException
{
return ranges;
}
public String hoi() throws RemoteException
{
return "poep";
}
public IRange getRange(int rangeIndex)
{
return ranges[rangeIndex];
}
public void StuurOpdracht(Opdracht op)
{
Opdracht o =null;
o = RC.AddOpdracht(op);
if(o!=null)
{
dubbeleOpdrachten.add(o);
}
}
public long getOndergrens()
{
return ondergrens;
}
public long getBovengrens()
{
return bovengrens;
}
public int getMagazijnGrootte()
{
return MAGAZIJN_GROOTTE;
}
}
The Rekenaar got the whole class "Range" so that is not the problem. The problem is something between the casting of IRange into Range. Range itself is Serializable and implements IRange.
The error I get: Exception in thread "main" java.lang.ClassCastException: [Linterfaces.IRange; cannot be cast to [Lrekenaar.Range;
When using RMI, you won't receive the same implementations you have on the server side. Instead you get a proxy class which will call your server. So you cannot cast your method.
Change test to a
IRange[] test
That should do it.

Categories