code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package org.vaadin.appfoundation.example.authorization;
import org.vaadin.appfoundation.example.Page;
public class DenyingAccess extends Page {
private static final long serialVersionUID = 7082724989547758176L;
public DenyingAccess() {
super("denying access text");
}
}
| Java |
package org.vaadin.appfoundation.example.authorization;
import org.vaadin.appfoundation.example.Page;
public class Resources extends Page {
private static final long serialVersionUID = -3718212835159660181L;
public Resources() {
super("resources text");
}
}
| Java |
package org.vaadin.appfoundation.example.authorization;
import org.vaadin.appfoundation.example.Page;
public class PermissionManagers extends Page {
private static final long serialVersionUID = -6274302806342638976L;
public PermissionManagers() {
super("permission managers text");
}
}
| Java |
package org.vaadin.appfoundation.example.authorization;
import org.vaadin.appfoundation.example.Page;
public class InitAuthorization extends Page {
private static final long serialVersionUID = -7484360026836952388L;
public InitAuthorization() {
super("init authorization text");
}
}
| Java |
package org.vaadin.appfoundation.example.components;
import org.vaadin.appfoundation.example.ExampleLoader;
import org.vaadin.appfoundation.example.ExampleLoader.Examples;
import org.vaadin.appfoundation.i18n.Lang;
import org.vaadin.codelabel.CodeLabel;
import org.vaadin.henrik.drawer.Drawer;
public class CodeExample extends Drawer {
private static final long serialVersionUID = 981189256494004603L;
public CodeExample(Examples example) {
super(Lang.getMessage("show code"), null);
CodeLabel codeExample = new CodeLabel();
codeExample.setValue(ExampleLoader.getExample(example));
setDrawerComponent(codeExample);
}
}
| Java |
package org.vaadin.appfoundation.example.components;
import org.vaadin.appfoundation.view.AbstractView;
import org.vaadin.appfoundation.view.View;
import org.vaadin.appfoundation.view.ViewContainer;
import org.vaadin.appfoundation.view.ViewHandler;
import com.vaadin.ui.Component;
import com.vaadin.ui.Panel;
public class MainArea extends AbstractView<Panel> implements ViewContainer {
private static final long serialVersionUID = 9010669373711637452L;
private View currentView;
public MainArea() {
super(new Panel());
getContent().setSizeFull();
getContent().addComponent(ViewHandler.getUriFragmentUtil());
}
/**
* {@inheritDoc}
*/
@Override
public void activated(Object... params) {
// Do nothing
}
/**
* {@inheritDoc}
*/
@Override
public void deactivated(Object... params) {
// Do nothing
}
/**
* {@inheritDoc}
*/
public void activate(View view) {
if (currentView == null) {
getContent().addComponent((Component) view);
} else {
getContent().replaceComponent((Component) currentView,
(Component) view);
}
currentView = view;
}
/**
* {@inheritDoc}
*/
public void deactivate(View view) {
if (currentView != null) {
getContent().removeComponent((Component) view);
}
currentView = null;
}
}
| Java |
package org.vaadin.appfoundation.example;
import java.util.Locale;
import org.vaadin.appfoundation.authentication.SessionHandler;
import org.vaadin.appfoundation.i18n.Lang;
import org.vaadin.appfoundation.view.ViewHandler;
import com.vaadin.Application;
import com.vaadin.ui.Window;
public class DemoApplication extends Application {
private static final long serialVersionUID = 1L;
private Window mainWindow;
@Override
public void init() {
Lang.initialize(this);
Lang.setLocale(Locale.ENGLISH);
ViewHandler.initialize(this);
SessionHandler.initialize(this);
ExampleData.initialize(this);
mainWindow = new MainWindow();
mainWindow.setSizeFull();
setMainWindow(mainWindow);
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class ViewContainerExample extends Page {
private static final long serialVersionUID = -4180097923322032070L;
public ViewContainerExample() {
super("view container text");
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class ViewIntro extends Page {
private static final long serialVersionUID = -4225762553285921918L;
public ViewIntro() {
super("view module intro text");
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class ConfiguringView extends Page {
private static final long serialVersionUID = 1602593248018609427L;
public ConfiguringView() {
super("configuring view module text");
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class Views extends Page {
private static final long serialVersionUID = -7650506914228979289L;
public Views() {
super("views text");
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class ViewFactories extends Page {
private static final long serialVersionUID = -935187288659828886L;
public ViewFactories() {
super("view factories text");
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class ViewHandlerExample extends Page {
private static final long serialVersionUID = 3391814647955929447L;
public ViewHandlerExample() {
super("view handler example text");
}
}
| Java |
package org.vaadin.appfoundation.example.view;
import org.vaadin.appfoundation.example.Page;
public class ViewEvents extends Page {
private static final long serialVersionUID = 8056163603161932812L;
public ViewEvents() {
super("view events text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class ConfiguringPersistence extends Page {
private static final long serialVersionUID = 8584529931203561701L;
public ConfiguringPersistence() {
super("configuring persistence module text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class StoringData extends Page {
private static final long serialVersionUID = -4227203122303296952L;
public StoringData() {
super("storing data text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class RemovingData extends Page {
private static final long serialVersionUID = 2858026847696773764L;
public RemovingData() {
super("removing data text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class CreatingPojos extends Page {
private static final long serialVersionUID = -8065190889615168139L;
public CreatingPojos() {
super("creating pojos text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class PersistenceIntro extends Page {
private static final long serialVersionUID = -247122143360422499L;
public PersistenceIntro() {
super("persistence module intro text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class FacadeFactoryExamples extends Page {
private static final long serialVersionUID = 2091504573134600933L;
public FacadeFactoryExamples() {
super("facade factory exmaple text");
}
}
| Java |
package org.vaadin.appfoundation.example.persistence;
import org.vaadin.appfoundation.example.Page;
public class FetchingData extends Page {
private static final long serialVersionUID = -8312944787394716728L;
public FetchingData() {
super("fetching data text");
}
}
| Java |
package org.vaadin.appfoundation.example;
import java.util.HashMap;
import java.util.Map;
import org.vaadin.appfoundation.example.authentication.AuthIntro;
import org.vaadin.appfoundation.example.authentication.ChangePassword;
import org.vaadin.appfoundation.example.authentication.ConfiguringAuth;
import org.vaadin.appfoundation.example.authentication.FetchUser;
import org.vaadin.appfoundation.example.authentication.GettingUserInstance;
import org.vaadin.appfoundation.example.authentication.LogoutExample;
import org.vaadin.appfoundation.example.authentication.PasswordUtilityMethods;
import org.vaadin.appfoundation.example.authentication.RegisterUser;
import org.vaadin.appfoundation.example.authentication.StoreUser;
import org.vaadin.appfoundation.example.authentication.UserAuth;
import org.vaadin.appfoundation.example.authorization.AuthorizationIntro;
import org.vaadin.appfoundation.example.authorization.CheckingAccessRights;
import org.vaadin.appfoundation.example.authorization.DenyingAccess;
import org.vaadin.appfoundation.example.authorization.GrantingAccess;
import org.vaadin.appfoundation.example.authorization.InitAuthorization;
import org.vaadin.appfoundation.example.authorization.JPAPm;
import org.vaadin.appfoundation.example.authorization.MemPm;
import org.vaadin.appfoundation.example.authorization.PermissionManagers;
import org.vaadin.appfoundation.example.authorization.RemovingPermissions;
import org.vaadin.appfoundation.example.authorization.Resources;
import org.vaadin.appfoundation.example.authorization.Roles;
import org.vaadin.appfoundation.example.components.MainArea;
import org.vaadin.appfoundation.example.i18n.ConfigureAndIniI18n;
import org.vaadin.appfoundation.example.i18n.FieldTranslations;
import org.vaadin.appfoundation.example.i18n.GettingMessages;
import org.vaadin.appfoundation.example.i18n.I18nIntro;
import org.vaadin.appfoundation.example.i18n.TranslationsFile;
import org.vaadin.appfoundation.example.i18n.UpdatingTranslationsFile;
import org.vaadin.appfoundation.example.persistence.ConfiguringPersistence;
import org.vaadin.appfoundation.example.persistence.CreatingPojos;
import org.vaadin.appfoundation.example.persistence.FacadeFactoryExamples;
import org.vaadin.appfoundation.example.persistence.FetchingData;
import org.vaadin.appfoundation.example.persistence.PersistenceIntro;
import org.vaadin.appfoundation.example.persistence.RemovingData;
import org.vaadin.appfoundation.example.persistence.StoringData;
import org.vaadin.appfoundation.example.view.ConfiguringView;
import org.vaadin.appfoundation.example.view.ViewContainerExample;
import org.vaadin.appfoundation.example.view.ViewEvents;
import org.vaadin.appfoundation.example.view.ViewFactories;
import org.vaadin.appfoundation.example.view.ViewHandlerExample;
import org.vaadin.appfoundation.example.view.ViewIntro;
import org.vaadin.appfoundation.example.view.Views;
import org.vaadin.appfoundation.i18n.Lang;
import org.vaadin.appfoundation.view.View;
import org.vaadin.appfoundation.view.ViewContainer;
import org.vaadin.appfoundation.view.ViewHandler;
import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.SplitPanel;
import com.vaadin.ui.Tree;
import com.vaadin.ui.Window;
import com.vaadin.ui.TabSheet.Tab;
public class MainWindow extends Window implements ViewContainer,
ValueChangeListener {
private static final long serialVersionUID = -7336305153060921847L;
private SplitPanel splitPanel;
private MainArea mainArea;
private Accordion menu;
private Tree authModuleTree;
private Tree authorizationModuleTree;
private Tree i18nModuleTree;
private Tree persistenceModuleTree;
private Tree viewModuleTree;
private Map<Object, Tree> viewToTree = new HashMap<Object, Tree>();
public MainWindow() {
setCaption(Lang.getMessage("application foundation"));
buildMainLayout();
buildAuthenticationModule();
buildAuthorizationModule();
buildI18nModule();
buildPersistenceModule();
buildViewModule();
ViewHandler.addView(MainView.class, this);
ViewHandler.activateView(MainView.class);
}
private void buildMainLayout() {
splitPanel = new SplitPanel();
menu = new Accordion();
mainArea = new MainArea();
splitPanel.addComponent(menu);
splitPanel.addComponent(mainArea);
splitPanel.setOrientation(SplitPanel.ORIENTATION_HORIZONTAL);
splitPanel.setSizeFull();
splitPanel.setSplitPosition(250, SplitPanel.UNITS_PIXELS);
setContent(splitPanel);
}
private void buildAuthenticationModule() {
initAuthTree();
addAuthViews();
Tab tab = menu.addTab(authModuleTree);
tab.setCaption(Lang.getMessage("auth module"));
}
private void buildAuthorizationModule() {
initAuthorizationTree();
addAuthorizationViews();
Tab tab = menu.addTab(authorizationModuleTree);
tab.setCaption(Lang.getMessage("authorization"));
}
private void buildI18nModule() {
initI18nTree();
addI18nViews();
Tab tab = menu.addTab(i18nModuleTree);
tab.setCaption(Lang.getMessage("i18n"));
}
private void buildPersistenceModule() {
initPersistenceTree();
addPersistenceViews();
Tab tab = menu.addTab(persistenceModuleTree);
tab.setCaption(Lang.getMessage("persistence"));
}
private void buildViewModule() {
initViewTree();
addViewViews();
Tab tab = menu.addTab(viewModuleTree);
tab.setCaption(Lang.getMessage("view module"));
}
private void initAuthTree() {
authModuleTree = new Tree();
prepareTree(authModuleTree);
}
private void initAuthorizationTree() {
authorizationModuleTree = new Tree();
prepareTree(authorizationModuleTree);
}
private void initI18nTree() {
i18nModuleTree = new Tree();
prepareTree(i18nModuleTree);
}
private void initPersistenceTree() {
persistenceModuleTree = new Tree();
prepareTree(persistenceModuleTree);
}
private void initViewTree() {
viewModuleTree = new Tree();
prepareTree(viewModuleTree);
}
private void prepareTree(Tree tree) {
tree.addContainerProperty("name", String.class, null);
tree.setItemCaptionPropertyId("name");
tree.addListener(this);
tree.setImmediate(true);
}
private void addAuthViews() {
addViewToModule(authModuleTree, AuthIntro.class, "auth intro",
"auth-intro");
addViewToModule(authModuleTree, ConfiguringAuth.class,
"configuring auth", "auth-config");
addViewToModule(authModuleTree, UserAuth.class, "auth a user",
"auth-authenticate");
addViewToModule(authModuleTree, GettingUserInstance.class,
"getting user instance caption", "get-user-instance");
addViewToModule(authModuleTree, LogoutExample.class,
"logging out a user caption", "logout");
addViewToModule(authModuleTree, ChangePassword.class,
"change password", "change-password");
addViewToModule(authModuleTree, RegisterUser.class, "register user",
"register-user");
addViewToModule(authModuleTree, FetchUser.class, "fetching users",
"fetch-user");
addViewToModule(authModuleTree, StoreUser.class, "storing users",
"store-user");
addViewToModule(authModuleTree, PasswordUtilityMethods.class,
"password util", "password-util");
}
private void addAuthorizationViews() {
addViewToModule(authorizationModuleTree, AuthorizationIntro.class,
"intro to authorization", "authorization-intro");
addViewToModule(authorizationModuleTree, Resources.class, "resources",
"resources");
addViewToModule(authorizationModuleTree, Roles.class, "roles", "roles");
addViewToModule(authorizationModuleTree, PermissionManagers.class,
"permission managers", "permission-managers");
addViewToModule(authorizationModuleTree, JPAPm.class, "jpapm",
"jpa-permission-managers");
addViewToModule(authorizationModuleTree, MemPm.class, "mempm",
"mem-permission-managers");
addViewToModule(authorizationModuleTree, InitAuthorization.class,
"init authorization", "init-authorization");
addViewToModule(authorizationModuleTree, GrantingAccess.class,
"granting access", "granting-access");
addViewToModule(authorizationModuleTree, DenyingAccess.class,
"denying access", "denying-access");
addViewToModule(authorizationModuleTree, CheckingAccessRights.class,
"checking for access rights", "checking-access");
addViewToModule(authorizationModuleTree, RemovingPermissions.class,
"removing permissions", "removing-permissions");
}
private void addI18nViews() {
addViewToModule(i18nModuleTree, I18nIntro.class, "i18n intro",
"i18n-intro");
addViewToModule(i18nModuleTree, TranslationsFile.class,
"translations file", "translations");
addViewToModule(i18nModuleTree, UpdatingTranslationsFile.class,
"updating translations file", "updating-translations");
addViewToModule(i18nModuleTree, ConfigureAndIniI18n.class,
"configure i18n", "i18n-config");
addViewToModule(i18nModuleTree, GettingMessages.class,
"getting messages", "getmsg");
addViewToModule(i18nModuleTree, FieldTranslations.class,
"field translations", "i18n-forms");
}
private void addPersistenceViews() {
addViewToModule(persistenceModuleTree, PersistenceIntro.class,
"persistence module intro", "persistence-intro");
addViewToModule(persistenceModuleTree, ConfiguringPersistence.class,
"configuring persistence module", "persistence-config");
addViewToModule(persistenceModuleTree, FacadeFactoryExamples.class,
"facade factory exmaple", "facadefactory");
addViewToModule(persistenceModuleTree, CreatingPojos.class,
"creating pojos", "creating-pojos");
addViewToModule(persistenceModuleTree, FetchingData.class,
"fetching data", "fetching-data");
addViewToModule(persistenceModuleTree, StoringData.class,
"storing data", "storing-data");
addViewToModule(persistenceModuleTree, RemovingData.class,
"removing data", "removing-data");
}
private void addViewViews() {
addViewToModule(viewModuleTree, ViewIntro.class, "view module intro",
"view-intro");
addViewToModule(viewModuleTree, ConfiguringView.class,
"configuring view module", "view-config");
addViewToModule(viewModuleTree, Views.class, "views", "views");
addViewToModule(viewModuleTree, ViewContainerExample.class,
"view container", "view-container");
addViewToModule(viewModuleTree, ViewEvents.class, "view events",
"view-events");
addViewToModule(viewModuleTree, ViewHandlerExample.class,
"view handler example", "viewhandler");
addViewToModule(viewModuleTree, ViewFactories.class, "view factories",
"viewfactories");
}
private void addViewToModule(Tree tree, Class<? extends View> c,
String captionTuid, String uri) {
ViewHandler.addView(c, this);
ViewHandler.addUri(uri, c);
viewToTree.put(c, tree);
Item item = tree.addItem(c);
item.getItemProperty("name").setValue(Lang.getMessage(captionTuid));
}
public void activate(View view) {
mainArea.activate(view);
Tree tree = viewToTree.get(view.getClass());
if (tree != null) {
menu.setSelectedTab(tree);
tree.select(view.getClass());
}
}
public void deactivate(View view) {
mainArea.deactivate(view);
}
public void valueChange(ValueChangeEvent event) {
if (event.getProperty().getValue() != null) {
ViewHandler.activateView(event.getProperty().getValue(), true);
}
}
}
| Java |
package org.vaadin.appfoundation.example;
import org.vaadin.appfoundation.authentication.data.User;
import org.vaadin.appfoundation.authentication.util.PasswordUtil;
import org.vaadin.appfoundation.view.ViewHandler;
import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;
public class ExampleData implements TransactionListener {
private static final long serialVersionUID = 5184835038248219005L;
// Store this instance of the view handler in this thread local variable
private static final ThreadLocal<ExampleData> instance = new ThreadLocal<ExampleData>();
private final Application application;
private User user1;
private User user2;
public ExampleData(Application application) {
instance.set(this);
this.application = application;
}
/**
* {@inheritDoc}
*/
public void transactionEnd(Application application, Object transactionData) {
// Clear thread local instance at the end of the transaction
if (this.application == application) {
instance.set(null);
}
}
/**
* {@inheritDoc}
*/
public void transactionStart(Application application, Object transactionData) {
// Set the thread local instance
if (this.application == application) {
instance.set(this);
}
}
/**
* Initializes the {@link ViewHandler} for the given {@link Application}
*
* @param application
*/
public static void initialize(Application application) {
if (application == null) {
throw new IllegalArgumentException("Application may not be null");
}
ExampleData exampleData = new ExampleData(application);
application.getContext().addTransactionListener(exampleData);
}
public static User getUser(Long id) {
if (id == 1L) {
if (instance.get().user1 == null) {
instance.get().user1 = new User();
instance.get().user1.setUsername("demo");
instance.get().user1.setPassword(PasswordUtil
.generateHashedPassword("demo123"));
}
return instance.get().user1;
} else if (id == 2L) {
if (instance.get().user2 == null) {
instance.get().user2 = new User();
instance.get().user2.setUsername("demo2");
instance.get().user2.setPassword(PasswordUtil
.generateHashedPassword("demo123"));
}
return instance.get().user2;
}
return null;
}
}
| Java |
package org.vaadin.appfoundation.example.i18n.data;
import org.vaadin.appfoundation.i18n.FieldTranslation;
public class Customer {
@FieldTranslation(tuid = "name")
private String name;
@FieldTranslation(tuid = "email")
private String email;
@FieldTranslation(tuid = "phone")
private String phone;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
}
| Java |
package org.vaadin.appfoundation.example.i18n;
import org.vaadin.appfoundation.example.Page;
public class TranslationsFile extends Page {
private static final long serialVersionUID = 7919159338285917176L;
public TranslationsFile() {
super("translations file text");
}
}
| Java |
package org.vaadin.appfoundation.example.i18n;
import org.vaadin.appfoundation.example.Page;
public class I18nIntro extends Page {
private static final long serialVersionUID = -8458896728089293287L;
public I18nIntro() {
super("i18n intro text");
}
}
| Java |
package org.vaadin.appfoundation.example.i18n;
import org.vaadin.appfoundation.example.Page;
import org.vaadin.appfoundation.example.ExampleLoader.Examples;
public class GettingMessages extends Page {
private static final long serialVersionUID = 987190244067153965L;
public GettingMessages() {
super("getting messages text");
addCodeExample(Examples.I18N_EXAMPLE_XML, "example translation xml");
addWikiText("getting messages text2");
addCodeExample(Examples.I18N_GET_MSG_TEXT_FIELD, "show code");
addWikiText("getting messages text3");
addCodeExample(Examples.I18N_GET_MSG_WITH_PARAM, "show code");
addWikiText("getting messages text4");
addCodeExample(Examples.I18N_GET_MSG_VIA_LANG, "show code");
}
}
| Java |
package org.vaadin.appfoundation.example.i18n;
import java.util.Locale;
import org.vaadin.appfoundation.example.Page;
import org.vaadin.appfoundation.example.ExampleLoader.Examples;
import org.vaadin.appfoundation.example.i18n.data.Customer;
import org.vaadin.appfoundation.i18n.I18nForm;
import org.vaadin.appfoundation.i18n.Lang;
import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Select;
public class FieldTranslations extends Page {
private static final long serialVersionUID = 2329869742045540584L;
public FieldTranslations() {
super("field translations text");
addCodeExample(Examples.I18N_CUSTOMER_POJO, "customer pojo");
addCodeExample(Examples.I18N_CUSTOMER_POJO_TRANSLATIONS,
"customer pojo translations");
addWikiText("field translations text2");
addForm();
addCodeExample(Examples.I18N_FORM, "show code");
}
private void addForm() {
Panel panel = new Panel();
final Customer customer = new Customer();
customer.setName("John Doe");
customer.setPhone("+123 456 7890");
customer.setEmail("john@some.site");
final I18nForm form = new I18nForm(Customer.class);
Select select = new Select();
select.addContainerProperty("name", String.class, null);
select.setItemCaptionPropertyId("name");
Item item = select.addItem("en");
item.getItemProperty("name").setValue(Lang.getMessage("en language"));
item = select.addItem("de");
item.getItemProperty("name").setValue(Lang.getMessage("de language"));
select.setImmediate(true);
select.addListener(new ValueChangeListener() {
private static final long serialVersionUID = -1667702475800410396L;
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
Lang.setLocale(value.equals("en") ? Locale.ENGLISH
: Locale.GERMAN);
BeanItem<Customer> customerItem = new BeanItem<Customer>(
customer);
form.setItemDataSource(customerItem);
Lang.setLocale(Locale.ENGLISH);
}
});
select.select("en");
panel.addComponent(select);
panel.addComponent(form);
getContent().addComponent(panel);
}
}
| Java |
package org.vaadin.appfoundation.example.i18n;
import org.vaadin.appfoundation.example.Page;
import org.vaadin.appfoundation.example.ExampleLoader.Examples;
public class UpdatingTranslationsFile extends Page {
private static final long serialVersionUID = -4620887553412342431L;
public UpdatingTranslationsFile() {
super("updating translations file text");
addCodeExample(Examples.I18N_ORIGINAL_XML,
"update trans file code 1 caption");
addWikiText("updating translations file text2");
addCodeExample(Examples.I18N_FILE_UPDATER,
"update trans file code 2 caption");
addWikiText("updating translations file text3");
addCodeExample(Examples.I18N_UPDATED_XML,
"update trans file code 3 caption");
addWikiText("updating translations file text4");
addCodeExample(Examples.I18N_LOAD_TRANSLATIONS,
"update trans file code 4 caption");
}
}
| Java |
package org.vaadin.appfoundation.example.i18n;
import org.vaadin.appfoundation.example.Page;
import org.vaadin.appfoundation.example.ExampleLoader.Examples;
public class ConfigureAndIniI18n extends Page {
private static final long serialVersionUID = -2316783633541238871L;
public ConfigureAndIniI18n() {
super("configure i18n text");
addCodeExample(Examples.I18N_SERVLET, "show code");
addCodeExample(Examples.I18N_INIT_LANG, "show code");
}
}
| Java |
public class Cons {
public static void main(String[] args) {
System.out.println("Hell");
}
}
| Java |
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
public class ChatServer extends Thread {
private final List<Socket> clients = new LinkedList<>();
private final ReadWriteLock lock = new ReadWriteLock();
@Override public void run() {
try(ServerSocket ss = new ServerSocket(9999)) {
while(true) {
final Socket clientSocket = ss.accept();
lock.setRead();
clients.add(clientSocket);
lock.resetRead();
new Thread() {
@Override public void run() {
while(true) {
try {
final String message = ">>" + new DataInputStream(clientSocket.getInputStream()).readUTF();
new Thread() {
@Override public void run() {
lock.setWrite();
for(Socket client : clients) {
try {
new DataOutputStream(client.getOutputStream()).writeUTF(message);
} catch (IOException e) {}
}
lock.resetWrite();
}
}.start();
} catch (IOException e) {}
}
}
}.start();
}
} catch(IOException e) {
System.out.println("Server stopped");
}
}
}
class ReadWriteLock {
private static int writersCount;
private Boolean isRead;
public synchronized void setRead() {
isRead = true;
while(writersCount > 0) {}
}
public synchronized void setWrite() {
while(isRead) {}
writersCount++;
}
public synchronized void resetRead() {
isRead = false;
}
public synchronized void resetWrite() {
writersCount--;
}
} | Java |
package server;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Coll {
public static void main(String[] args) throws IOException {
List<String> list = new ArrayList<>();
String s = new String("kkk");
System.out.println(list.size());
list.add(s);
System.out.println(list.size());
// list.remove(s);
System.out.println(list.size());
DataInputStream dis = new DataInputStream(new FileInputStream(new File("C:/temp/123.txt")));
// while(dis.available() > 0) {
// System.out.println(dis.readUTF());
// }
System.out.println(list.toString());
Calendar calendar = Calendar.getInstance();
System.out.println("" + calendar.get(Calendar.YEAR) + calendar.get(Calendar.DAY_OF_YEAR));
}
}
| Java |
package server;
import java.util.Scanner;
public class ClientsCreator {
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
while(true) {
System.out.println("alive clients - " + ChatClient.getClientsNumber());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
}.start();
Scanner scanner = new Scanner(System.in);
while(true) {
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
new ChatClient().start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
}
}
}
}
| Java |
package server;
import java.util.Scanner;
public class ServerStarter {
public static void main(String[] args) {
new ChatServer().start();
}
}
| Java |
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class ChatClient extends Thread {
private static int clientsNumber;
private static int n = 1234;
private static String idealHistory;
private static int falseHistory;
public static synchronized int getClientsNumber() {
return clientsNumber;
}
public void run() {
clientsNumber++;
try(final Socket socket = new Socket("localhost", 7777)) {
new Thread() {
private DataInputStream dis = new DataInputStream(socket.getInputStream());
private String lastMessage;
@Override public void run() {
while(true) {
try {
lastMessage = dis.readUTF();
// if((lastMessage.startsWith("ACK ")) && (lastMessage.length() > 200)) {
// if(idealHistory == null) {
// idealHistory = lastMessage;
// System.out.println(lastMessage);
// } else {
// if(lastMessage.equals(idealHistory)) {
// System.out.println(++falseHistory);
// }
// System.out.println(lastMessage);
// }
// }
} catch (IOException e) {break;}
}
}
}.start();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
n++;
dos.writeUTF("/reg " + n + " " + n);
dos.writeUTF("/log " + n + " " + n);
while(true) {
dos.writeUTF("/snd URGENT");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
}
} catch (IOException e) {}
clientsNumber--;
}
} | Java |
package server;
public class MemoryTest {
public static void main(String[] args) {
long[][] a = new long[10000][];
Thread[] t = new Thread[10000];
for(int i = 0; i < a.length; i++) {
a[i] = new long[1000000];
t[i] = new Thread() {
@Override
public void run() {
while(true) {}
}
};
t[i].start();
System.out.println(i);
// try {
// Thread.sleep(200);
// } catch (InterruptedException e) {}
}
}
}
| Java |
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class ChatClientManual extends Thread {
private static int clientsNumber;
private static int n = 1234;
public static synchronized int getClientsNumber() {
return clientsNumber;
}
public void run() {
clientsNumber++;
try(final Socket socket = new Socket("localhost", 7777)) {
new Thread() {
private DataInputStream dis = new DataInputStream(socket.getInputStream());
private String lastMessage;
@Override public void run() {
while(true) {
try {
lastMessage = dis.readUTF();
System.out.println(lastMessage);
} catch (IOException e) {break;}
}
}
}.start();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
//dos.writeUTF("/chid " + n++);
while(true) {
dos.writeUTF(sc.nextLine());
// dos.writeUTF("/snd URGENT_MESSAGE");
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {}
}
} catch (IOException e) {}
clientsNumber--;
}
public static void main(String[] args) {
new ChatClientManual().start();
}
} | Java |
package dao_Impl;
import interfaces.DALException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import connector.Connector;
import connector.NonStaticConnector;
import dto_objects.AuthorDTO;
import dto_objects.BookDTO;
import dto_objects.PublisherDTO;
import dto_objects.SubjectDTO;
public class MySQLSearchDAO {
public ArrayList<ArrayList> quickSearch(String search) throws DALException, SQLException{
ArrayList<BookDTO> list1 = new ArrayList<BookDTO>();
ArrayList<AuthorDTO> list2 = new ArrayList<AuthorDTO>();
ArrayList<SubjectDTO> list3 = new ArrayList<SubjectDTO>();
ArrayList<PublisherDTO> list4 = new ArrayList<PublisherDTO>();
try {
ResultSet rs1 = Connector.doQuery(
"SELECT distinct ISBN, title, publisherID, publisher_name, pages FROM Book NATURAL JOIN Publisher WHERE title Like '%"+search+"%'"
);
while (rs1.next())
{
PublisherDTO pub = new PublisherDTO(rs1.getInt(3), rs1.getString(4));
list1.add(new BookDTO(rs1.getInt(1), pub, rs1.getString(2), rs1.getInt(5)));
}
ResultSet rs2= Connector.doQuery(
"SELECT * FROM Author WHERE author_firstname Like '%" + search + "%' " +
"OR author_lastname Like '%" + search + "%'");
while (rs2.next())
{
list2.add(new AuthorDTO(rs2.getInt(1), rs2.getString(2), rs2.getString(3)));
}
ResultSet rs3 = Connector.doQuery(
"SELECT * FROM Subject " +
"WHERE subject_name Like '%" + search + "%'");
while (rs3.next())
{
list3.add(new SubjectDTO(rs3.getInt(1), rs3.getString(2)));
}
ResultSet rs4 = Connector.doQuery(
"SELECT * FROM Publisher " +
"WHERE publisher_name Like '%" + search + "%'");
while (rs4.next())
{
list4.add(new PublisherDTO(rs4.getInt(1), rs4.getString(2)));
}
for(BookDTO book: list1){
List<AuthorDTO> authors = AuthorsFromISBN(book.getISBN());
List<SubjectDTO> subjects = SubjectsFromISBN(book.getISBN());
book.setAuthors(authors);
book.setSubjects(subjects);
}
}
catch (SQLException e) { throw new DALException(e); }
ArrayList<ArrayList> retur = new ArrayList<ArrayList>();
retur.add(list1);
retur.add(list2);
retur.add(list3);
retur.add(list4);
return retur;
}
public List<BookDTO> advancedSearch(String bookname, String authorFirstName, String authorLastName, String subject, String publisher) throws DALException{
List<BookDTO> list = new ArrayList<BookDTO>();
ResultSet rs = Connector.doQuery(
"SELECT distinct ISBN, title, publisherID, publisher_name, pages " +
"FROM Book NATURAL JOIN Book_Authors NATURAL JOIN Author " +
"NATURAL JOIN Book_Subjects NATURAL JOIN Subject NATURAL JOIN Publisher " +
"WHERE title Like '%" + bookname + "%' " +
"AND author_firstname Like '%" + authorFirstName + "%' " +
"AND author_lastname Like '%" + authorLastName + "%' " +
"AND subject_name Like '%" + subject + "%' " +
"AND publisher_name Like '%" + publisher + "%' ");
try {
while (rs.next())
{
PublisherDTO pub = new PublisherDTO(rs.getInt(3), rs.getString(4));
list.add(new BookDTO(rs.getInt(1), pub, rs.getString(2), rs.getInt(5)));
}
}
catch (SQLException e) { throw new DALException(e); }
for(BookDTO book: list){
List<AuthorDTO> authors = AuthorsFromISBN(book.getISBN());
List<SubjectDTO> subjects = SubjectsFromISBN(book.getISBN());
book.setAuthors(authors);
book.setSubjects(subjects);
}
return list;
}
public List<AuthorDTO> AuthorsFromISBN(int ISBN) throws DALException {
List<AuthorDTO> list = new ArrayList<AuthorDTO>();
ResultSet rs = Connector.doQuery(
"SELECT authorID, author_firstname, author_lastname " +
"FROM Book NATURAL JOIN Book_Authors NATURAL JOIN Author " +
"WHERE ISBN = " + ISBN );
try {
while (rs.next())
{
list.add(new AuthorDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
public List<SubjectDTO> SubjectsFromISBN(int ISBN) throws DALException {
List<SubjectDTO> list = new ArrayList<SubjectDTO>();
ResultSet rs = Connector.doQuery(
"SELECT subjectID, subject_name " +
"FROM Book NATURAL JOIN Book_Subjects NATURAL JOIN Subject " +
"WHERE ISBN = " + ISBN );
try {
while (rs.next())
{
list.add(new SubjectDTO(rs.getInt(1), rs.getString(2)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
public List<BookDTO> SearchISBN(int ISBN) throws DALException{
List<BookDTO> list = new ArrayList<BookDTO>();
ResultSet rs = Connector.doQuery(
"SELECT distinct ISBN, title, publisherID, publisher_name, pages " +
"FROM Book NATURAL JOIN Book_Authors NATURAL JOIN Author " +
"NATURAL JOIN Book_Subjects NATURAL JOIN Subject NATURAL JOIN Publisher " +
"WHERE ISBN Like '%" + ISBN + "%' " );
try {
while (rs.next())
{
PublisherDTO pub = new PublisherDTO(rs.getInt(3), rs.getString(4));
list.add(new BookDTO(rs.getInt(1), pub, rs.getString(2), rs.getInt(5)));
}
}
catch (SQLException e) { throw new DALException(e); }
for(BookDTO book: list){
List<AuthorDTO> authors = AuthorsFromISBN(book.getISBN());
List<SubjectDTO> subjects = SubjectsFromISBN(book.getISBN());
book.setAuthors(authors);
book.setSubjects(subjects);
}
return list;
}
public List<BookDTO> SearchAuthorID(int authorID) throws DALException{
List<BookDTO> list = new ArrayList<BookDTO>();
ResultSet rs = Connector.doQuery(
"SELECT distinct ISBN, title, publisherID, publisher_name, pages " +
"FROM Book NATURAL JOIN Book_Authors NATURAL JOIN Author " +
"NATURAL JOIN Book_Subjects NATURAL JOIN Subject NATURAL JOIN Publisher " +
"WHERE authorID = '" + authorID + "' ");
try {
while (rs.next())
{
PublisherDTO pub = new PublisherDTO(rs.getInt(3), rs.getString(4));
list.add(new BookDTO(rs.getInt(1), pub, rs.getString(2), rs.getInt(5)));
}
}
catch (SQLException e) { throw new DALException(e); }
for(BookDTO book: list){
List<AuthorDTO> authors = AuthorsFromISBN(book.getISBN());
List<SubjectDTO> subjects = SubjectsFromISBN(book.getISBN());
book.setAuthors(authors);
book.setSubjects(subjects);
}
return list;
}
public List<AuthorDTO> SearchAuthorIDSingle(int authorID) throws DALException{
List<AuthorDTO> list = new ArrayList<AuthorDTO>();
ResultSet rs = Connector.doQuery(
"SELECT distinct authorID, author_firstname, author_lastname " +
"FROM Author " + "WHERE authorID = '" + authorID + "' ");
try {
while (rs.next())
{
list.add(new AuthorDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
public List<BookDTO> SearchSubjectID(int subjectID) throws DALException{
List<BookDTO> list = new ArrayList<BookDTO>();
ResultSet rs = Connector.doQuery(
"SELECT distinct ISBN, title, publisherID, publisher_name, pages " +
"FROM Book NATURAL JOIN Book_Authors NATURAL JOIN Author " +
"NATURAL JOIN Book_Subjects NATURAL JOIN Subject NATURAL JOIN Publisher " +
"WHERE subjectID = '" + subjectID + "' ");
try {
while (rs.next())
{
PublisherDTO pub = new PublisherDTO(rs.getInt(3), rs.getString(4));
list.add(new BookDTO(rs.getInt(1), pub, rs.getString(2), rs.getInt(5)));
}
}
catch (SQLException e) { throw new DALException(e); }
for(BookDTO book: list){
List<AuthorDTO> authors = AuthorsFromISBN(book.getISBN());
List<SubjectDTO> subjects = SubjectsFromISBN(book.getISBN());
book.setAuthors(authors);
book.setSubjects(subjects);
}
return list;
}
public List<BookDTO> SearchPublisherID(int publisherID) throws DALException{
List<BookDTO> list = new ArrayList<BookDTO>();
ResultSet rs = Connector.doQuery(
"SELECT distinct ISBN, title, publisherID, publisher_name, pages " +
"FROM Book NATURAL JOIN Book_Authors NATURAL JOIN Author " +
"NATURAL JOIN Book_Subjects NATURAL JOIN Subject NATURAL JOIN Publisher " +
"WHERE publisherID = '" + publisherID + "' ");
try {
while (rs.next())
{
PublisherDTO pub = new PublisherDTO(rs.getInt(3), rs.getString(4));
list.add(new BookDTO(rs.getInt(1), pub, rs.getString(2), rs.getInt(5)));
}
}
catch (SQLException e) { throw new DALException(e); }
for(BookDTO book: list){
List<AuthorDTO> authors = AuthorsFromISBN(book.getISBN());
List<SubjectDTO> subjects = SubjectsFromISBN(book.getISBN());
book.setAuthors(authors);
book.setSubjects(subjects);
}
return list;
}
}
| Java |
package dao_Impl;
import interfaces.DALException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.Connection;
import connector.Connector;
import dao_Impl.MySQLBookDAO;
import dto_objects.AuthorDTO;
import dto_objects.BookDTO;
public class TST {
/**
* @param args
*/
public static void main(String[] args) {
try {
new connector.Connector();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
MySQLSearchDAO testSearch = new MySQLSearchDAO();
try {
List<ArrayList> temp = testSearch.quickSearch("");
List<BookDTO> bookTemp = (List<BookDTO>)temp.get(0);
System.out.println(bookTemp.size());
for (BookDTO emp : (List<BookDTO>)temp.get(0)) {
System.out.println(emp.getTitle());
for (AuthorDTO author : emp.getAuthors()) {
System.out.println("\t" + author.getAuthorFirstName() + " " + author.getAuthorLastName());
}
System.out.println();
System.out.println(emp.getAuthorNames());
System.out.println();
}
for (AuthorDTO emp : (List<AuthorDTO>)temp.get(1)) {
System.out.println(emp.getAuthorFirstName());
}
System.out.println("YES!");
} catch (DALException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Java |
package dao_Impl;
import interfaces.DALException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import dto_objects.AuthorDTO;
import dto_objects.BookDTO;
import dto_objects.FakturaDTO;
public class TST_faktura {
/**
* @param args
*/
public static void main(String[] args) {
try {
new connector.Connector();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
MySQLFakturaDAO testFak = new MySQLFakturaDAO();
try {
List<FakturaDTO> temp = testFak.getFakturaByUsrID(6, 1);
System.out.println(temp.size());
System.out.println();
for (FakturaDTO emp : temp) {
System.out.println(emp.getFakID() + "\n" + emp.getUsrID() + "\n" + emp.getBookID() + "\n" + emp.getLoan_date() + "\n" + emp.getLoan_date());
System.out.println();
}
System.out.println("YES!");
} catch (DALException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Java |
package dao_Impl;
import interfaces.DALException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import dto_objects.BookDTO;
import dto_objects.FakturaDTO;
public class TST_Jonathan {
public static void main(String[] args) {
try {
new connector.Connector();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
MySQLBookDAO bookDAO = new MySQLBookDAO();
MySQLFakturaDAO fakturaDAO = new MySQLFakturaDAO();
BookDTO book = null;
FakturaDTO fakturaDTO = null;
try {
book = bookDAO.getBook_CopyByID(4);
System.out.println(fakturaDAO.getNewestFakID());
} catch (DALException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(book.getTitle());
System.out.println(book.getStatus());
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Calendar calDue = Calendar.getInstance();
calDue.add(Calendar.DATE, 20);
System.out.println(dateFormat.format(calDue.getTime()));
// FakturaDTO fak = new FakturaDTO(7, 8, "Test", "Test");
// try {
// fakturaDAO.createFaktura(fak);
// } catch (DALException e) {
// e.printStackTrace();
// }
}
}
| Java |
package dao_Impl;
import interfaces.DALException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import connector.Connector;
import connector.NonStaticConnector;
import dto_objects.AuthorDTO;
import dto_objects.BookDTO;
import dto_objects.PublisherDTO;
import dto_objects.SubjectDTO;
public class MySQLBookDAO {
//NYT
public List<AuthorDTO> getAuthorsByISBN(int ISBN) throws DALException{
ResultSet rs = Connector.doQuery("SELECT * FROM Book_Authors NATURAL JOIN Author WHERE ISBN = " + ISBN);
List<AuthorDTO> tempList = new ArrayList<AuthorDTO>();
try {
while(rs.next()){
tempList.add(new AuthorDTO(rs.getInt(1), rs.getString(3), rs.getString(4)));
}
if (!rs.first())
throw new DALException("Author " + ISBN + " does not excist");
return tempList;
}catch (SQLException e) {throw new DALException(e); }
}
public List<SubjectDTO> getSubjectByISBN(int ISBN) throws DALException{
ResultSet rs = Connector.doQuery("SELECT * FROM Book_Subjects NATURAL JOIN Subject WHERE ISBN = " + ISBN);
List<SubjectDTO> tempList = new ArrayList<SubjectDTO>();
try{
while(rs.next()){
tempList.add(new SubjectDTO(rs.getInt(1), rs.getString(3)));
}
// if (!rs.first())
// throw new DALException("Subject " + ISBN + " does not excist");
return tempList;
}catch (SQLException e) {
throw new DALException(e);
}
}
public BookDTO getBookByISBN(int ISBN) throws DALException{
ResultSet rs = Connector.doQuery("SELECT * FROM Book WHERE ISBN = " + ISBN);
try{
if (!rs.first())
throw new DALException("Book " + ISBN + " does not excist");
System.out.println("In try");
String temp3;
int temp1, temp2, temp4;
System.out.println("trying to get temp1");
temp1 = rs.getInt(1);
System.out.println(temp1);
temp2 = rs.getInt(2);
temp3 = rs.getString(3);
temp4 = rs.getInt(4);
System.out.println(temp1 + " " + temp2 + " " + temp3 + " " + temp4);
return new BookDTO(temp1, getPublisherByID(temp2), getAuthorsByISBN(temp1)
, getSubjectByISBN(temp1), temp3, temp4);
}
catch (SQLException e) {
throw new DALException(e);
}
}
//NYT SLUT
public List<BookDTO> getBooksByPublisherID(int publisherID)throws DALException {
NonStaticConnector conn = null;
try {
conn = new NonStaticConnector();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e1) {
throw new DALException(e1);
}
ResultSet rs2 = conn.doQuery("SELECT * FROM Book WHERE publisherID =" + publisherID);
List<BookDTO> list = new ArrayList<BookDTO>();
try {
while (rs2.next()) {
System.out.println("In try");
String temp3;
int temp1, temp2, temp4;
System.out.println("trying to get temp1");
temp1 = rs2.getInt(1);
System.out.println(temp1);
temp2 = rs2.getInt(2);
temp3 = rs2.getString(3);
temp4 = rs2.getInt(4);
System.out.println(temp1 + " " + temp2 + " " + temp3 + " " + temp4);
System.out.println("publisher: "+getPublisherByID(temp2).getPublisher_name());
System.out.println("Author: "+getAuthorsByISBN(temp1).get(0).getAuthorFirstName());
System.out.println("Subject: "+getSubjectByISBN(temp1).get(0).getSubject_name());
list.add(new BookDTO(temp1, getPublisherByID(temp2), getAuthorsByISBN(temp1)
, getSubjectByISBN(temp1), temp3, temp4));
}
if (!rs2.first())
throw new DALException("Publisher with ID " + publisherID + " does not excist");
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
public void createBook(BookDTO book, int authorID, int subjectID) throws DALException { // skal rettes
Connector.doUpdate(
"INSERT INTO Book(ISBN, publisherID, title, pages) VALUES " +
"(" + book.getISBN() + ", '" + book.getPublisher().getPublisherID() + "', '" + book.getTitle() + "', '" +
book.getPages() + "')"
);
Connector.doUpdate(
"INSERT INTO Book_Authors(authorID, ISBN) VALUES " +
"(" + authorID + ", '" + book.getISBN() + "')"
);
Connector.doUpdate(
"INSERT INTO Book_Subjects(subjectID, ISBN) VALUES " +
"(" + subjectID + ", '" + book.getISBN() + "')"
);
}
public void updateBook(BookDTO book, int authorID, int subjectID) throws DALException {
Connector.doUpdate(
"UPDATE Book SET ISBN = '" + book.getISBN() + "', publisherID = '" + book.getPublisher().getPublisherID() +
"', title = '" + book.getTitle() + "', pages = '" + book.getPages() + "' WHERE ISBN = " +
book.getOldISBN()
);
Connector.doUpdate(
"UPDATE Book_Authors SET authorID = '" + authorID + "', ISBN = '" + book.getISBN() + "' WHERE ISBN = " +
book.getOldISBN()
);
Connector.doUpdate(
"UPDATE Book_Subjects SET subjectID = '" + subjectID + "', ISBN = '" + book.getISBN() + "' WHERE ISBN = " +
book.getOldISBN()
);
}
public void getBookByTitle(String title) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Book WHERE title = " + title);
try {
if (!rs.first()) throw new DALException("Book " + title + " does not excist");
getBookByISBN(rs.getInt(1));
}
catch (SQLException e) {throw new DALException(e); }
}
// HER UNDER ARBEJDES DER P��������� BOOK_COPY TABELLEN
public BookDTO getBook_CopyByID(int bookID) throws DALException, SQLException {
ResultSet rs = Connector.doQuery("SELECT * FROM Book_Copy WHERE bookID = " + bookID);
if (!rs.first()) throw new DALException("Book Copy " + bookID + " does not excist");
return new BookDTO(rs.getInt(1), rs.getInt(2), rs.getString(3));
}
public int getISBNByBook_CopyID(int bookID) throws DALException, SQLException {
ResultSet rs = Connector.doQuery("SELECT ISBN FROM Book_Copy WHERE bookID = " + bookID);
if (!rs.first()) throw new DALException("Book Copy " + bookID + " does not excist");
return rs.getInt(1);
}
public List<BookDTO> getBook_CopyListByISBN(int ISBN) throws DALException {
List<BookDTO> list = new ArrayList<BookDTO>();
ResultSet rs = Connector.doQuery("SELECT * FROM Book_Copy WHERE ISBN =" + ISBN);
try {
while (rs.next())
{
list.add(new BookDTO(rs.getInt(1), rs.getInt(2), rs.getString(3)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
public void createBook_Copy(BookDTO book) throws DALException {
Connector.doUpdate(
"INSERT INTO Book_Copy(ISBN, bookID) VALUES " +
"(" + book.getISBN() + ", '" + book.getBookID() + ", '" + book.getStatus() + "')"
);
}
public void updateBook_Copy(BookDTO book) throws DALException {
Connector.doUpdate(
"UPDATE Book_Copy SET ISBN = '" + book.getISBN() + "', bookID = '" + book.getBookID() + "', status = '" + book.getStatus() + "' WHERE ISBN = " +
book.getISBN() + " AND bookID = " + book.getBookID()
);
}
public void deleteBook_Copy(int bookID) throws DALException {
Connector.doUpdate(
"UPDATE Book_Copy SET status = 'Udgået' WHERE bookID = " + bookID
);
}
// HER UNDER ARBEJDES DER P��������� AUTHORS
public AuthorDTO getAuthorByID(int authorID) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Authors WHERE authorID = " + authorID);
try {
if (!rs.first()) throw new DALException("Author " + authorID + " does not excist");
return new AuthorDTO(rs.getInt(1), rs.getString(2), rs.getString(3));
}
catch (SQLException e) {throw new DALException(e); }
}
public void createAuthor(AuthorDTO author) throws DALException {
Connector.doUpdate(
"INSERT INTO Author(authorID, author_firstname) VALUES " +
"(" + author.getAuthorId() + ", '" + author.getAuthorFirstName() + ", '" + author.getAuthorLastName() + "')"
);
}
public void updateAuthor(AuthorDTO author) throws DALException {
Connector.doUpdate(
"UPDATE Author SET authorID = '" + author.getAuthorId() + "', author_firstname = '" + author.getAuthorFirstName()
+ "', author_lastname = '" + "' WHERE authorID = " + author.getAuthorId()
);
}
public void deleteAuthor(AuthorDTO author) throws DALException {
Connector.doUpdate(
"DELETE FROM Author WHERE authorID = " + author.getAuthorId()
);
}
public AuthorDTO getAuthorByFirstName(String authorFirstName) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Author WHERE author_firstname = " + authorFirstName);
try {
if (!rs.first()) throw new DALException("Author " + authorFirstName + " does not excist");
return new AuthorDTO(rs.getInt(1), rs.getString(2), rs.getString(3));
}
catch (SQLException e) {throw new DALException(e); }
}
public AuthorDTO getAuthorByLastName(String authorLastName) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Author WHERE author_lastname = " + authorLastName);
try {
if (!rs.first()) throw new DALException("Author " + authorLastName + " does not excist");
return new AuthorDTO(rs.getInt(1), rs.getString(2), rs.getString(3));
}
catch (SQLException e) {throw new DALException(e); }
}
public List<AuthorDTO> getAuthorIdList() throws DALException {
List<AuthorDTO> list = new ArrayList<AuthorDTO>();
ResultSet rs = Connector.doQuery("SELECT * FROM Author");
try
{
while (rs.next())
{
list.add(new AuthorDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
// HER UNDER ARBEJDES DER P��������� PUBLISHER
public PublisherDTO getPublisherByID(int publisherID) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Publisher WHERE publisherID = " + publisherID);
try {
if (!rs.first()) throw new DALException("Publisher " + publisherID + " does not excist");
PublisherDTO blahDTO = new PublisherDTO(rs.getInt(1), rs.getString(2));
rs.close();
return blahDTO;
}
catch (SQLException e) {throw new DALException(e); }
}
public void createPublisher(PublisherDTO publisher) throws DALException {
Connector.doUpdate(
"INSERT INTO Publisher(publisherID, publisher_name) VALUES " +
"(" + publisher.getPublisherID() + ", '" + publisher.getPublisher_name() + "')"
);
}
public void updatePublisher(PublisherDTO publisher) throws DALException {
Connector.doUpdate(
"UPDATE Publisher SET publisherID = '" + publisher.getPublisherID() + "', publisher_name = '" + publisher.getPublisher_name()
+ "' WHERE publisherID = " + publisher.getPublisherID()
);
}
public void deletePublisher(PublisherDTO publisher) throws DALException {
Connector.doUpdate(
"DELETE FROM Publisher WHERE publisherID = " + publisher.getPublisherID()
);
}
public PublisherDTO getPublisherByName(String publisher_name) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Publisher WHERE publisher_name = " + publisher_name);
try {
if (!rs.first()) throw new DALException("Publisher " + publisher_name + " does not excist");
return new PublisherDTO(rs.getInt(1), rs.getString(2));
}
catch (SQLException e) {throw new DALException(e); }
}
public List<PublisherDTO> getPublisherIdList() throws DALException {
List<PublisherDTO> list = new ArrayList<PublisherDTO>();
ResultSet rs = Connector.doQuery("SELECT * FROM Publisher");
try
{
while (rs.next())
{
list.add(new PublisherDTO(rs.getInt(1), rs.getString(2)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
// HER UNDER ARBEJDES DER P��������� SUBJECTS
public SubjectDTO getSubjectByID(int subjectID) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Subject WHERE subjectID = " + subjectID);
try {
if (!rs.first()) throw new DALException("Subject " + subjectID + " does not excist");
return new SubjectDTO(rs.getInt(1), rs.getString(2));
} catch (SQLException e) {throw new DALException(e); }
}
public void createSubject(SubjectDTO subject) throws DALException {
Connector.doUpdate(
"INSERT INTO Subject(subjectID, subject_name) VALUES " +
"(" + subject.getSubjectID() + ", '" + subject.getSubject_name() + "')"
);
}
public void updateSubject(SubjectDTO subject) throws DALException {
Connector.doUpdate(
"UPDATE Subject SET subjectID = '" + subject.getSubjectID() + "', subject_name = '" + subject.getSubject_name()
+ "' WHERE subjectID = " + subject.getSubjectID()
);
}
public void deleteSubject(SubjectDTO subject) throws DALException {
Connector.doUpdate(
"DELETE FROM Subject WHERE subjectID = " + subject.getSubjectID()
);
}
public SubjectDTO getSubjectByName(String subject_name)
throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Subject WHERE subject_name = " + subject_name);
try {
if (!rs.first()) throw new DALException("Subject " + subject_name + " does not excist");
return new SubjectDTO(rs.getInt(1), rs.getString(2));
} catch (SQLException e) {throw new DALException(e); }
}
public List<SubjectDTO> getSubjectIdList() throws DALException {
List<SubjectDTO> list = new ArrayList<SubjectDTO>();
ResultSet rs = Connector.doQuery("SELECT * FROM Subject");
try
{
while (rs.next())
{
list.add(new SubjectDTO(rs.getInt(1), rs.getString(2)));
}
}
catch (SQLException e) { throw new DALException(e); }
return list;
}
}
| Java |
package dao_Impl;
public class TST_Jeppe {
/**
* @param args
*/
public static void main(String[] args) {
}
}
| Java |
package dao_Impl;
import interfaces.DALException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import connector.Connector;
import dto_objects.UserDTO;
public class MySQLUserDAO{
public UserDTO login(String login, String password) throws DALException{
ResultSet rs = Connector.doQuery("SELECT * FROM Users WHERE loginName = \"" + login + "\" AND password = \"" + password + "\"");
try {
if (!rs.first())
throw new DALException("Wrong Login or Password");
return getUserByUsrID(rs.getInt(1));
}
catch (SQLException e){
throw new DALException(e);
}
}
public List<UserDTO> getUsersByRigths(UserDTO user) throws DALException {
List<UserDTO> list = new ArrayList<UserDTO>();
ResultSet rs = Connector.doQuery("SELECT * FROM Users WHERE rights = '" + user.getRights() + "'");
try {
if (!rs.first()) throw new DALException("User right" + user.getRights() + " does not excist");
while (rs.next()) {
list.add(new UserDTO(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));
}
} catch (SQLException e) {
throw new DALException(e);
}
return list;
}
public void createUser(UserDTO user) throws DALException {
Connector.doUpdate(
"INSERT INTO Users VALUES (" + user.getUsrID() + ",'" + user.getRights() + "' , '" + user.getLoginName() + "' , '" + user.getPassword() + "')"+ "; "
);
Connector.doUpdate(
"INSERT INTO User_Data VALUES (" + user.getUsrID() + ",'" + user.getCPR() + "' , '" + user.getName() + "' , '" + user.getAddress() +
"' , '" + user.getZipcode() + "' , '" + user.getPhone() + "' , '" + user.getEmail() +"')"
);
}
public void updateUser(UserDTO user) throws DALException {
Connector.doUpdate(
"UPDATE Users" +
" SET usrID = '" + user.getUsrID() +" rights = '" + user.getRights() + "', loginName = '" + user.getLoginName() + "', password = '" + user.getPassword() + "'" +
" WHERE usrID =" + user.getUsrID()
);
Connector.doUpdate(
"UPDATE User_Data" +
" SET usrID = '" + user.getUsrID() + "', CPR = '" + user.getCPR() + "', name = '" + user.getName() + "'" + "', address = '" + user.getAddress() + "'" +
"', zipcode = '" + user.getZipcode() + "', phone = '" + user.getPhone() + "'" + "', email = '" + user.getEmail() + "'" +
" WHERE usrID =" + user.getUsrID()
);
}
public void deleteUser(UserDTO user) throws DALException {
Connector.doUpdate(
"UPDATE Users SET rights = 'deleted' WHERE usrID = " + user.getUsrID()
);
}
public UserDTO getUserByUsrID(int userID) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM Users NATURAL JOIN User_Data WHERE usrID = " + userID);
try {
if (!rs.first()) throw new DALException("UserID: " + userID + " does not exist");
return new UserDTO(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5), rs.getString(6), rs.getString(7), rs.getInt(8), rs.getInt(9), rs.getString(10));
}
catch (SQLException e){
throw new DALException(e);
}
}
public int getMaxUserID() throws DALException,SQLException {
ResultSet rs = Connector.doQuery("SELECT MAX(usrID) FROM Users");
if (!rs.first()) throw new DALException("No fakturas exsist");
return rs.getInt(1);
}
}
| Java |
package dto_objects;
import java.util.List;
public class BookDTO {
private int ISBN, oldISBN;
private PublisherDTO publisher;
private List<AuthorDTO> authors;
private List<SubjectDTO> subjects;
private String title;
private int pages;
private int bookID;
private String status;
public BookDTO(int ISBN, int bookID, String status){
this.ISBN = ISBN;
this.bookID = bookID;
this.status = status;
}
public BookDTO(int ISBN, PublisherDTO publisher, List<AuthorDTO> authors, List<SubjectDTO> subjects, String title, int pages){
this.oldISBN = ISBN;
this.ISBN = ISBN;
this.publisher = publisher;
this.authors = authors;
this.subjects = subjects;
this.title = title;
this.pages = pages;
}
public BookDTO(int ISBN, PublisherDTO publisher, String title, int pages){
this.oldISBN = ISBN;
this.ISBN = ISBN;
this.publisher = publisher;
this.title = title;
this.pages = pages;
}
public int getISBN() {
return ISBN;
}
public int getOldISBN() {
return oldISBN;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setISBN(int iSBN) {
ISBN = iSBN;
}
public PublisherDTO getPublisher() {
return publisher;
}
public void setPublisher(PublisherDTO publisher) {
this.publisher = publisher;
}
public List<AuthorDTO> getAuthors() {
return authors;
}
public void setAuthors(List<AuthorDTO> authors) {
this.authors = authors;
}
public List<SubjectDTO> getSubjects() {
return subjects;
}
public String getAuthorNames(){
String temp = "";
for (int i = 0; i < authors.size() ; i++) {
temp = temp + authors.get(i).getAuthorFirstName() +" "+ authors.get(i).getAuthorLastName();
if(i != authors.size() - 1)
temp = temp + ", ";
}
return temp;
}
public String getSubjectNames(){
String temp = "";
for (int i = 0; i < subjects.size() ; i++) {
temp = temp + subjects.get(i).getSubject_name();
if(i != subjects.size() - 1)
temp = temp + ", ";
}
return temp;
}
public void setSubjects(List<SubjectDTO> subjects) {
this.subjects = subjects;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
}
| Java |
package dto_objects;
public class UserDTO {
private int usrID, zipcode, phone, CPR;
private String rights, loginName, password, name, address, email;
public UserDTO(int usrID, String rights, String loginName, String password, int CPR, String name, String address, int zipcode
, int phone, String email) {
this.usrID = usrID;
this.rights = rights;
this.loginName = loginName;
this.password = password;
this.CPR = CPR;
this.name = name;
this.address = address;
this.zipcode = zipcode;
this.phone = phone;
this.email = email;
}
public UserDTO(int usrID, String rights, String loginName, String password) {
this.usrID = usrID;
this.rights = rights;
this.loginName = loginName;
this.password = password;
}
public UserDTO(int CPR, String name, String address, int zipcode, int phone, String email) {
this.CPR = CPR;
this.name = name;
this.address = address;
this.zipcode = zipcode;
this.phone = phone;
this.email = email;
}
public int getUsrID() {
return usrID;
}
public void setUsrID(int usrID) {
this.usrID = usrID;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCPR() {
return CPR;
}
public void setCPR(int CPR) {
this.CPR = CPR;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
| Java |
package dto_objects;
public class SubjectDTO {
private int subjectID;
private String subject_name;
public SubjectDTO(int subjectID, String subject_name){
this.subjectID = subjectID;
this.subject_name = subject_name;
}
public int getSubjectID() {
return subjectID;
}
public void setSubjectID(int subjectID) {
this.subjectID = subjectID;
}
public String getSubject_name() {
return subject_name;
}
public void setSubject_name(String subject_name) {
this.subject_name = subject_name;
}
}
| Java |
package dto_objects;
public class PublisherDTO {
private int publisherID;
private String publisher_name;
public PublisherDTO(int publisherID, String publisher_name){
this.publisherID = publisherID;
this.publisher_name = publisher_name;
}
public int getPublisherID() {
return publisherID;
}
public void setPublisherID(int publisherID) {
this.publisherID = publisherID;
}
public String getPublisher_name() {
return publisher_name;
}
public void setPublisher_name(String publisher_name) {
this.publisher_name = publisher_name;
}
}
| Java |
package dto_objects;
public class FakturaDTO {
private int fakID, usrID, bookID;
private String loan_date, loan_due;
public FakturaDTO(int usrID, int fakID, int bookID, String loan_date,
String loan_due) {
super();
this.usrID = usrID;
this.fakID = fakID;
this.bookID = bookID;
this.loan_date = loan_date;
this.loan_due = loan_due;
}
public FakturaDTO(int fakID, int bookID, String loan_date,
String loan_due) {
super();
this.fakID = fakID;
this.bookID = bookID;
this.loan_date = loan_date;
this.loan_due = loan_due;
}
public FakturaDTO(int fakID, int bookID) {
this.fakID = fakID;
this.bookID = bookID;
}
public int getUsrID() {
return usrID;
}
public void setUsrID(int usrID) {
this.usrID = usrID;
}
public int getFakID() {
return fakID;
}
public void setFakID(int fakID) {
this.fakID = fakID;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getLoan_date() {
return loan_date;
}
public void setLoan_date(String loan_date) {
this.loan_date = loan_date;
}
public String getLoan_due() {
return loan_due;
}
public void setLoan_due(String loan_due) {
this.loan_due = loan_due;
}
}
| Java |
package dto_objects;
public class AuthorDTO {
private int AuthorId;
private String AuthorFirstName, AuthorLastName;
public AuthorDTO(int authorId, String authorFirstName, String authorLastName) {
super();
AuthorId = authorId;
AuthorFirstName = authorFirstName;
AuthorLastName = authorLastName;
}
public int getAuthorId() {
return AuthorId;
}
public void setAuthorId(int authorId) {
AuthorId = authorId;
}
public String getAuthorFirstName() {
return AuthorFirstName;
}
public void setAuthorFirstName(String autherFirstName) {
AuthorFirstName = autherFirstName;
}
public String getAuthorLastName() {
return AuthorLastName;
}
public void setAuthorLastName(String authorLastName) {
AuthorLastName = authorLastName;
}
}
| Java |
package interfaces;
public class DALException extends Exception
{
public DALException(String message) { super(message); }
public DALException(Exception e) { super(e); }
} | Java |
package connector;
import interfaces.DALException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class NonStaticConnector
{
public Connection connectToDatabase(String url, String username, String password)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
return (Connection) DriverManager.getConnection(url, username, password);
}
private Connection conn;
private Statement stm;
public NonStaticConnector(String server, int port, String database,
String username, String password)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SQLException
{
conn = connectToDatabase("jdbc:mysql://"+server+":"+port+"/"+database,
username, password);
stm = conn.createStatement();
}
public NonStaticConnector() throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SQLException
{
this(Constant.server, Constant.port, Constant.database,
Constant.username, Constant.password);
}
public ResultSet doQuery(String cmd) throws DALException
{
try { return stm.executeQuery(cmd); }
catch (SQLException e) { throw new DALException(e); }
}
public int doUpdate(String cmd) throws DALException
{
try { return stm.executeUpdate(cmd); }
catch (SQLException e) { throw new DALException(e); }
}
} | Java |
package connector;
// erstat konstanterne nedenfor hvis anden database skal anvendes
public abstract class Constant
{
public static final String
server = "sql-lab1.cc.dtu.dk", // database-serveren
database = "s123688",
username = "s123688",
password = "123456";
public static final int
port = 3306;
} | Java |
package connector;
import interfaces.DALException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connector
{
public static Connection connectToDatabase(String url, String username, String password)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SQLException
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
return (Connection) DriverManager.getConnection(url, username, password);
}
private static Connection conn;
private static Statement stm;
public Connector(String server, int port, String database,
String username, String password)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SQLException
{
conn = connectToDatabase("jdbc:mysql://"+server+":"+port+"/"+database,
username, password);
stm = conn.createStatement();
}
public Connector() throws InstantiationException, IllegalAccessException,
ClassNotFoundException, SQLException
{
this(Constant.server, Constant.port, Constant.database,
Constant.username, Constant.password);
}
public static ResultSet doQuery(String cmd) throws DALException
{
try { return stm.executeQuery(cmd); }
catch (SQLException e) { throw new DALException(e); }
}
public static int doUpdate(String cmd) throws DALException
{
try { return stm.executeUpdate(cmd); }
catch (SQLException e) { throw new DALException(e); }
}
} | Java |
package Function;
import java.sql.SQLException;
import interfaces.DALException;
import dao_Impl.MySQLBookDAO;
import dao_Impl.MySQLFakturaDAO;
import dao_Impl.MySQLSearchDAO;
import dao_Impl.MySQLUserDAO;
import dto_objects.BookDTO;
import dto_objects.UserDTO;
public class FunctionADMIN extends FunctionLIBRARY {
public FunctionADMIN(){
super();
}
public void deleteUser(UserDTO User) throws DALException{
SQLUser.deleteUser(User);
}
public void createLibrarian(UserDTO Lib) throws DALException{
SQLUser.createUser(Lib);
}
public void updateLibrarian(UserDTO Lib) throws DALException{
SQLUser.updateUser(Lib);
}
}
| Java |
package Function;
import interfaces.DALException;
import dto_objects.AuthorDTO;
import dto_objects.BookDTO;
import dto_objects.SubjectDTO;
import dto_objects.UserDTO;
import dto_objects.PublisherDTO;
import java.util.List;
public class FunctionLIBRARY extends FunctionUSER {
public void createBook(BookDTO book, int authorID, int subjectID) throws DALException{
SQLBook.createBook(book, authorID, subjectID);
}
public UserDTO getUserByUsrID(int UserID) throws DALException{
return SQLUser.getUserByUsrID(UserID);
}
public BookDTO getBookByISBN(int ISBN) throws DALException{
return SQLBook.getBookByISBN(ISBN);
}
public List<BookDTO> getBookCopyListByISBN(int ISBN) throws DALException{
return SQLBook.getBook_CopyListByISBN(ISBN);
}
public void deleteBook_Copy(int bookID) throws DALException{
SQLBook.deleteBook_Copy(bookID);
}
public void createBook_Copy(BookDTO book) throws DALException{
SQLBook.createBook_Copy(book);
}
public void updateBook(BookDTO book, int authorID, int subjectID) throws DALException{
SQLBook.updateBook(book, authorID, subjectID);
}
public List<PublisherDTO> getPublisherIdList() throws DALException{
return SQLBook.getPublisherIdList();
}
public List<SubjectDTO> getSubjectIdList() throws DALException{
return SQLBook.getSubjectIdList();
}
public List<AuthorDTO> getAuthorIdList() throws DALException{
return SQLBook.getAuthorIdList();
}
}
| Java |
package Function;
import java.util.List;
import interfaces.DALException;
import dto_objects.BookDTO;
import dto_objects.FakturaDTO;
import dto_objects.UserDTO;
public class FunctionUSER extends FunctionWEB {
public void updateOwnUser(UserDTO user) throws DALException{
SQLUser.updateUser(user);
}
public void loanBook(BookDTO book, FakturaDTO faktura) throws DALException{
SQLBook.updateBook_Copy(book);
SQLFaktura.createFaktura(faktura);
}
public void turnInBook(BookDTO book) throws DALException{
SQLBook.updateBook_Copy(book);
}
public List<FakturaDTO> showCurrentLoans(int usrID, int action) throws DALException{
return SQLFaktura.getFakturaByUsrID(usrID, action);
}
}
| Java |
package Function;
import interfaces.DALException;
import java.awt.print.Book;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import dao_Impl.MySQLBookDAO;
import dao_Impl.MySQLFakturaDAO;
import dao_Impl.MySQLSearchDAO;
import dao_Impl.MySQLUserDAO;
import dto_objects.AuthorDTO;
import dto_objects.BookDTO;
import dto_objects.SubjectDTO;
import dto_objects.UserDTO;
import java.util.regex.*;
import sun.misc.Regexp;
public class FunctionWEB{
protected MySQLBookDAO SQLBook;
protected MySQLUserDAO SQLUser;
protected MySQLFakturaDAO SQLFaktura;
protected MySQLSearchDAO SQLSearch;
public FunctionWEB(){
try{
new connector.Connector();
SQLBook = new MySQLBookDAO();
SQLUser = new MySQLUserDAO();
SQLFaktura = new MySQLFakturaDAO();
SQLSearch = new MySQLSearchDAO();
}catch(ClassNotFoundException|IllegalAccessException|InstantiationException|SQLException e){
e.printStackTrace();
}
}
public int getMaxUsrID() throws DALException, SQLException{
return SQLUser.getMaxUserID();
}
public void createUser(UserDTO user) throws DALException{
SQLUser.createUser(user);
}
public void updateUser(UserDTO user) throws DALException{
SQLUser.updateUser(user);
}
public UserDTO login(String name, String pass) throws DALException{
return SQLUser.login(name, pass);
}
public ArrayList<ArrayList> quickSearch(String search)throws DALException, SQLException{
if(search != "" && !search.matches("^\\s*+$|[;]")){
try{
return SQLSearch.quickSearch(search);
}catch(NullPointerException e){
System.out.println("No search");
}
}
return null;
}
public List<BookDTO> advancedSearch(String bookname, String authorFirstName, String authorLastName, String subject, String publisher) throws DALException{
List<BookDTO> startList = SQLSearch.advancedSearch(bookname, authorFirstName, authorLastName, subject, publisher);
List<BookDTO> endList = new ArrayList<BookDTO>();
for(BookDTO book:startList){
endList.add(SQLBook.getBookByISBN(book.getISBN()));
}
return endList;
}
public List<BookDTO> SearchISBN(int ISBN) throws DALException{
List<BookDTO> startList = SQLSearch.SearchISBN(ISBN);
List<BookDTO> endList = new ArrayList<BookDTO>();
for(BookDTO book:startList){
endList.add(SQLBook.getBookByISBN(book.getISBN()));
}
return endList;
}
public List<BookDTO> SearchAuthorID(int authorID) throws DALException{
List<BookDTO> startList = SQLSearch.SearchAuthorID(authorID);
List<BookDTO> endList = new ArrayList<BookDTO>();
for(BookDTO book:startList){
endList.add(SQLBook.getBookByISBN(book.getISBN()));
}
return endList;
}
public List<AuthorDTO> SearchAuthorIDSingle(int authorID) throws DALException{
List<AuthorDTO> startList = SQLSearch.SearchAuthorIDSingle(authorID);
return startList;
}
public List<BookDTO> SearchSubjectID(int subjectID) throws DALException{
List<BookDTO> startList = SQLSearch.SearchSubjectID(subjectID);
List<BookDTO> endList = new ArrayList<BookDTO>();
for(BookDTO book:startList){
endList.add(SQLBook.getBookByISBN(book.getISBN()));
}
return endList;
}
public List<BookDTO> SearchPublisherID(int publisherID) throws DALException{
List<BookDTO> startList = SQLSearch.SearchPublisherID(publisherID);
List<BookDTO> endList = new ArrayList<BookDTO>();
for(BookDTO book:startList){
endList.add(SQLBook.getBookByISBN(book.getISBN()));
}
return endList;
}
//TEST FUNCTION
public List<BookDTO> getBookListByPublisherID(int ID){
try {
return SQLBook.getBooksByPublisherID(ID);
} catch (DALException e) {
System.out.println(e);
}
return null;
}
public BookDTO getBookCopyByID(int ID) throws DALException, SQLException{
return SQLBook.getBook_CopyByID(ID);
}
public int getISBNByBookCopyID(int ID) throws DALException, SQLException{
return SQLBook.getISBNByBook_CopyID(ID);
}
public void testAuthors(int isbn){
try {
List<AuthorDTO> templist = SQLBook.getAuthorsByISBN(isbn);
for (AuthorDTO authorDTO : templist) {
System.out.println(authorDTO.getAuthorId() + " " + authorDTO.getAuthorFirstName() + " " + authorDTO.getAuthorLastName());
}
} catch (Exception e) {
System.out.println("empty list");
e.printStackTrace();
}
}
public void testSubject(int ISBN){
try {
List<SubjectDTO> templist = SQLBook.getSubjectByISBN(ISBN);
for (SubjectDTO subjectDTO : templist) {
System.out.println(subjectDTO.getSubjectID() + " " + subjectDTO.getSubject_name());
}
} catch (Exception e) {
System.out.println("empty list");
e.printStackTrace();
}
}
public void testBook(){
try {
BookDTO test = SQLBook.getBookByISBN(654321);
System.out.println(test.getISBN()+" "+test.getTitle());
} catch (DALException e) {
System.out.println("error in testbook");
e.printStackTrace();
}
}
}
| Java |
package Function;
import interfaces.DALException;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dto_objects.UserDTO;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public String loggedInMenuUser = "<div id=menu><br>"+
"<span class=menu>Profile</span><br>"+
"<span class=tab><a href=\"../User/fakturaUser.jsp\">View Loans</a></span><br>"+
"<span class=tab><a href=\"../User/updateUser.jsp\">Update Profile</a></span><br>"+
"<br><br>"+
"</div>";
public String loggedInMenuLibary = "<div id=menu><br>"+
"<span class=menu>Books</span><br>"+
"<span class=tab><a href=\"../Libary/createBook.jsp\">Create Book</a></span><br>"+
"<span class=tab><a href=\"../Libary/updateBook.jsp\">Update Book</a></span><br>"+
"<span class=tab><a href=\"../Libary/deleteBookCopy.jsp\">Delete Book</a></span><br>"+
"<span class=menu>Users</span><br>"+
"<span class=tab><a href=\"../User/createUser.jsp\">Create User</a></span><br>"+
"<span class=tab><a href=\"../User/updateUserLibary.jsp\">Update User</a></span><br>"+
"<span class=tab><a href=\"../User/faktura.jsp\">User loans</span><br>"+
"<br><br>"+
"</div>";
public String loggedInMenuAdmin = "<div id=menu><br>"+
"<span class=menu>Books</span><br>"+
"<span class=tab><a href=\"../Libary/createBook.jsp\">Create Book</a></span><br>"+
"<span class=tab><a href=\"../Libary/updateBook.jsp\">Update Book</a></span><br>"+
"<span class=tab><a href=\"../Libary/deleteBookCopy.jsp\">Delete Book</a></span><br>"+
"<span class=menu>Users</span><br>"+
"<span class=tab><a href=\"../User/createUser.jsp\">Create User</a></span><br>"+
"<span class=tab><a href=\"../User/updateUserAdmin.jsp\">Update User</a></span><br>"+
"<span class=tab><a href=\"../User/faktura.jsp\">User loans</a></span><br>"+
"<span class=menu>Admin</span><br>"+
"<span class=tab><a href=\"../User/deleteUser.jsp\">Delete User</a></span><br>"+
"<br><br>"+
"</div>";
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = (request.getParameter("un"));
String pass = (request.getParameter("pw"));
//Debug
System.out.println("Debug - Login/Password");
System.out.println(user);
System.out.println(pass);
//----
HttpSession session = request.getSession(true);
String referer = request.getHeader("Referer");
if(session.getAttribute("currentSessionUser") == null){
session.removeAttribute("userMENU");
System.out.println("into if statement");
FunctionWEB func = (FunctionWEB)session.getAttribute("func");
try{
UserDTO userData = func.login(user, pass);
session.setAttribute("currentSessionUser", userData);
// user is logged in, getting the right function layer
session.removeAttribute("func");
String rights = userData.getRights();
if(rights.equals("user")){
FunctionUSER funcLoggedIn = new FunctionUSER();
session.setAttribute("func", funcLoggedIn);
session.setAttribute("userMENU", loggedInMenuUser);
}else if(rights.equals("libary")){
FunctionLIBRARY funcLoggedIn = new FunctionLIBRARY();
session.setAttribute("func", funcLoggedIn);
session.setAttribute("userMENU", loggedInMenuLibary);
}else if(rights.equals("admin")){
FunctionADMIN funcLoggedIn = new FunctionADMIN();
session.setAttribute("func", funcLoggedIn);
session.setAttribute("userMENU", loggedInMenuAdmin);
}
//
response.sendRedirect(referer); //logged-in page
}catch(DALException e){
System.out.println(e);
response.sendRedirect(referer); //logged-in page with error
}
}else{
if(request.getParameter("logout") !=null){
System.out.println("logout");
session.removeAttribute("func");
session.removeAttribute("currentSessionUser");
session.removeAttribute("userMENU");
}
response.sendRedirect(referer);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| Java |
package primary;
import interfaces.DALException;
public class Controller {
public static void main(String[] args) throws DALException {
Connecter connecter = new Connecter();
Function function = new Function(connecter);
FrontEnd frontEnd = new FrontEnd(function);
frontEnd.start();
}
} | Java |
package primary;
import interfaces.DALException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import dao_Impl.MySQLBookDAO;
import dao_Impl.MySQLFakturaDAO;
import dao_Impl.MySQLUserDAO;
import dto_objects.BookDTO;
import dto_objects.FakturaDTO;
import dto_objects.UserDTO;
public class Connecter {
private MySQLFakturaDAO fakturaDAO;
private MySQLBookDAO bookDAO;
private MySQLUserDAO userDAO;
private UserDTO currentUser;
public Connecter(){
try {
new connector.Connector();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
fakturaDAO = new MySQLFakturaDAO();
bookDAO = new MySQLBookDAO();
userDAO = new MySQLUserDAO();
}
public boolean validateLogin(String username, String password){
try {
currentUser = userDAO.login(username, password);
return true;
} catch (DALException e) {
System.out.println(e.getLocalizedMessage());
return false;
}
}
public BookDTO findBook(int bookID) throws DALException {
try {
return bookDAO.getBook_CopyByID(bookID);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void updateBookCopes(ArrayList<BookDTO> bookList) {
for (BookDTO bookDTO : bookList) {
try {
bookDAO.updateBook_Copy(bookDTO);
} catch (DALException e) {
e.printStackTrace();
}
}
}
public void createFaktura(ArrayList<BookDTO> bookList) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
Calendar calDue = Calendar.getInstance();
calDue.add(Calendar.DATE, 14);
int fakID = 0;
try {
fakID = fakturaDAO.getNewestFakID()+1;
} catch (DALException | SQLException e1) {
e1.printStackTrace();
}
//Creates the Faktura
FakturaDTO fakturaDTO = new FakturaDTO(currentUser.getUsrID(), fakID, bookList.get(0).getBookID(),
dateFormat.format(cal.getTime()), dateFormat.format(calDue.getTime()));
try {
fakturaDAO.createUserFaktura(fakturaDTO);
} catch (DALException e1) {
e1.printStackTrace();
}
for (BookDTO bookDTO : bookList) {
fakturaDTO = new FakturaDTO(currentUser.getUsrID(), fakID, bookDTO.getBookID(),
dateFormat.format(cal.getTime()), dateFormat.format(calDue.getTime()));
try {
fakturaDAO.createFaktura(fakturaDTO);
} catch (DALException e) {
e.printStackTrace();
}
}
}
}
| Java |
package primary;
public class BookException extends Exception {
private static final long serialVersionUID = -6800688480731488034L;
public BookException(String message) {
super(message);
}
} | Java |
package primary;
import interfaces.DALException;
import java.util.ArrayList;
import java.util.Scanner;
import dto_objects.BookDTO;
public class FrontEnd {
private Scanner input = new Scanner(System.in);
private Function function;
public FrontEnd(Function function) {
this.function = function;
}
public void start() {
System.out.print("Username:");
String username = input.nextLine();
System.out.print("Password:");
String password = input.nextLine();
if(function.validateLogin(username, password)){
loggedIn();
}else{
System.out.println("Invalid username or password");
System.out.println();
start();
}
}
private void loggedIn(){
System.out.println("Logged in!");
menu();
}
private void menu(){
System.out.println();
System.out.println("----------------------");
System.out.println("Press 1 to lend books");
System.out.println("Press 2 to return books");
System.out.println("press 3 to logout");
System.out.print("Input:");
String choiceString = input.nextLine();
try{
int intChoice = Integer.parseInt(choiceString);
switch (intChoice) {
case 1: firstBookInput("lend"); break;
case 2: firstBookInput("return"); break;
case 3: logout();break;
default:
System.out.println("Invalid input");
System.out.println();
menu();
break;
}
}
catch(NumberFormatException e){
System.out.println("Invalid input");
System.out.println();
menu();
}
}
private void logout() {
System.out.println("Logged out!");
System.out.println("----------------------");
System.out.println();
start();
}
private void firstBookInput(String lendReturn){
System.out.println();
System.out.println("----------------------");
System.out.println("Use scanner to scan the barcode of the books you want to "+lendReturn);
System.out.println("Press Enter when done");
scanBooks(lendReturn);
System.out.println(lendReturn+"ing done!");
menu();
}
private void scanBooks(String lendReturn){
ArrayList<BookDTO> bookList = new ArrayList<BookDTO>();
while(true){
System.out.print("Input:");
String bookInputString = input.nextLine();
if (bookInputString.equals("")){
break;
}
try{
int bookIDint = Integer.parseInt(bookInputString);
for (BookDTO bookDTO : bookList) {
if(bookDTO.getBookID() == bookIDint){
throw new BookException("Book already scanned!");
}
}
bookList.add(function.validateBook(bookIDint, lendReturn));
} catch(NumberFormatException e){
System.out.println("Invalid input");
} catch (DALException e) {
System.out.println("Book does not exist contact librarian");
} catch (BookException e) {
System.out.println(e.getMessage());
}
}
if(bookList != null){
bookList = function.updateDatabase(bookList, lendReturn); //Updates the statuses
}
}
}
| Java |
package integrity;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class VerifyKey {
/**
* @param args
* @throws Exception
* @throws Exception
*/
public static boolean VerifyFile() throws Exception {
//Generating the assymetric secret key
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey k = kg.generateKey();
//System.out.println("Checking Encrypted folder for publicKey..");
//Loading the Public key from the Encrypted folder
FileInputStream publicKeyLoad = new FileInputStream("PublicKey.publickey");
byte[] encKey = new byte[publicKeyLoad.available()];
publicKeyLoad.read(encKey);
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
//Using the RSA keyfactory
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
//System.out.println("Getting the signedFile...");
FileInputStream signedFileInput = new FileInputStream("credentials_signed.txt");
byte[] signatureToVerify = new byte[signedFileInput.available()];
signedFileInput.read(signatureToVerify);
signedFileInput.close();
//System.out.println("Verifying the signedFile with the publicKey");
//Verifying the signed file
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(pubKey);
FileInputStream enctryptedFileLoad = new FileInputStream("credentials.txt");
BufferedInputStream bufin = new BufferedInputStream(enctryptedFileLoad);
byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0) {
len = bufin.read(buffer);
sig.update(buffer, 0, len);
};
bufin.close();
boolean verfication = sig.verify(signatureToVerify);
return verfication;
}
}
| Java |
package integrity;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class SignKey {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//Generating the assymetric secret key
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);
SecretKey k = kg.generateKey();
//Generate Public and Private key
System.out.println("Generating your public and private key");
KeyPairGenerator keyParGen = KeyPairGenerator.getInstance("RSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
keyParGen.initialize(1024, random);
KeyPair pair = keyParGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();
//Generating the signature and signing it with the privateKey
Signature signedSignature = Signature.getInstance("SHA1withRSA");
signedSignature.initSign(privateKey);
FileInputStream loadedEnctryptedFile = new FileInputStream("credentials.txt");
BufferedInputStream bufin = new BufferedInputStream(loadedEnctryptedFile);
byte[] buffer = new byte[1024];
int len;
while ((len = bufin.read(buffer)) >= 0) {
signedSignature.update(buffer, 0, len);
};
bufin.close();
byte[] realSignature = signedSignature.sign();
//Saving the signed file
FileOutputStream signedFileOut = new FileOutputStream("credentials_signed.txt");
signedFileOut.write(realSignature);
System.out.println("Signed file saved...");
signedFileOut.close();
//Saving the public key file
byte[] publicKeyEncode = publicKey.getEncoded();
FileOutputStream publicKeyOut = new FileOutputStream("PublicKey." +"publicKey");
publicKeyOut.write(publicKeyEncode);
System.out.println("Public key saved...");
}
}
| Java |
/*
* @(#)SamplePrincipal.java 1.4 00/01/11
*
* Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Oracle or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/
package sample.principal;
import java.security.Principal;
/**
* <p> This class implements the <code>Principal</code> interface
* and represents a Sample user.
*
* <p> Principals such as this <code>SamplePrincipal</code>
* may be associated with a particular <code>Subject</code>
* to augment that <code>Subject</code> with an additional
* identity. Refer to the <code>Subject</code> class for more information
* on how to achieve this. Authorization decisions can then be based upon
* the Principals associated with a <code>Subject</code>.
*
* @version 1.4, 01/11/00
* @see java.security.Principal
* @see javax.security.auth.Subject
*/
public class SamplePrincipal implements Principal, java.io.Serializable {
/**
* @serial
*/
private String name;
/**
* Create a SamplePrincipal with a Sample username.
*
* <p>
*
* @param name the Sample username for this user.
*
* @exception NullPointerException if the <code>name</code>
* is <code>null</code>.
*/
public SamplePrincipal(String name) {
if (name == null)
throw new NullPointerException("illegal null input");
this.name = name;
}
/**
* Return the Sample username for this <code>SamplePrincipal</code>.
*
* <p>
*
* @return the Sample username for this <code>SamplePrincipal</code>
*/
public String getName() {
return name;
}
/**
* Return a string representation of this <code>SamplePrincipal</code>.
*
* <p>
*
* @return a string representation of this <code>SamplePrincipal</code>.
*/
public String toString() {
return("SamplePrincipal: " + name);
}
/**
* Compares the specified Object with this <code>SamplePrincipal</code>
* for equality. Returns true if the given object is also a
* <code>SamplePrincipal</code> and the two SamplePrincipals
* have the same username.
*
* <p>
*
* @param o Object to be compared for equality with this
* <code>SamplePrincipal</code>.
*
* @return true if the specified Object is equal equal to this
* <code>SamplePrincipal</code>.
*/
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (!(o instanceof SamplePrincipal))
return false;
SamplePrincipal that = (SamplePrincipal)o;
if (this.getName().equals(that.getName()))
return true;
return false;
}
/**
* Return a hash code for this <code>SamplePrincipal</code>.
*
* <p>
*
* @return a hash code for this <code>SamplePrincipal</code>.
*/
public int hashCode() {
return name.hashCode();
}
}
| Java |
/*
* @(#)SampleAcn.java
*
* Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Oracle or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/
package sample;
import java.io.*;
import java.util.*;
import javax.security.auth.login.*;
import javax.security.auth.*;
import javax.security.auth.callback.*;
/**
* <p> This Sample application attempts to authenticate a user
* and reports whether or not the authentication was successful.
*/
public class SampleAcn {
/**
* Attempt to authenticate the user.
*
* <p>
*
* @param args input arguments for this application. These are ignored.
*/
public static void main(String[] args) {
// Obtain a LoginContext, needed for authentication. Tell it
// to use the LoginModule implementation specified by the
// entry named "Sample" in the JAAS login configuration
// file and to also use the specified CallbackHandler.
LoginContext lc = null;
try {
lc = new LoginContext("Sample", new MyCallbackHandler());
} catch (LoginException le) {
System.err.println("Cannot create LoginContext. "
+ le.getMessage());
System.exit(-1);
} catch (SecurityException se) {
System.err.println("Cannot create LoginContext. "
+ se.getMessage());
System.exit(-1);
}
// the user has 3 attempts to authenticate successfully
int i;
for (i = 0; i < 3; i++) {
try {
// attempt authentication
lc.login();
// if we return with no exception, authentication succeeded
break;
} catch (LoginException le) {
System.err.println("Authentication failed:");
System.err.println(" " + le.getMessage());
try {
Thread.currentThread().sleep(3000);
} catch (Exception e) {
// ignore
}
}
}
// did they fail three times?
if (i == 3) {
System.out.println("Sorry");
System.exit(-1);
}
System.out.println("Authentication succeeded!");
}
}
/**
* The application implements the CallbackHandler.
*
* <p> This application is text-based. Therefore it displays information
* to the user using the OutputStreams System.out and System.err,
* and gathers input from the user using the InputStream System.in.
*/
class MyCallbackHandler implements CallbackHandler {
/**
* Invoke an array of Callbacks.
*
* <p>
*
* @param callbacks an array of <code>Callback</code> objects which contain
* the information requested by an underlying security
* service to be retrieved or displayed.
*
* @exception java.io.IOException if an input or output error occurs. <p>
*
* @exception UnsupportedCallbackException if the implementation of this
* method does not support one or more of the Callbacks
* specified in the <code>callbacks</code> parameter.
*/
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof TextOutputCallback) {
// display the message according to the specified type
TextOutputCallback toc = (TextOutputCallback)callbacks[i];
switch (toc.getMessageType()) {
case TextOutputCallback.INFORMATION:
System.out.println(toc.getMessage());
break;
case TextOutputCallback.ERROR:
System.out.println("ERROR: " + toc.getMessage());
break;
case TextOutputCallback.WARNING:
System.out.println("WARNING: " + toc.getMessage());
break;
default:
throw new IOException("Unsupported message type: " +
toc.getMessageType());
}
} else if (callbacks[i] instanceof NameCallback) {
// prompt the user for a username
NameCallback nc = (NameCallback)callbacks[i];
System.err.print(nc.getPrompt());
System.err.flush();
nc.setName((new BufferedReader
(new InputStreamReader(System.in))).readLine());
} else if (callbacks[i] instanceof PasswordCallback) {
// prompt the user for sensitive information
PasswordCallback pc = (PasswordCallback)callbacks[i];
System.err.print(pc.getPrompt());
System.err.flush();
pc.setPassword(readPassword(System.in));
} else {
throw new UnsupportedCallbackException
(callbacks[i], "Unrecognized Callback");
}
}
}
// Reads user password from given input stream.
private char[] readPassword(InputStream in) throws IOException {
char[] lineBuffer;
char[] buf;
int i;
buf = lineBuffer = new char[128];
int room = buf.length;
int offset = 0;
int c;
loop: while (true) {
switch (c = in.read()) {
case -1:
case '\n':
break loop;
case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) {
if (!(in instanceof PushbackInputStream)) {
in = new PushbackInputStream(in);
}
((PushbackInputStream)in).unread(c2);
} else
break loop;
default:
if (--room < 0) {
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}
if (offset == 0) {
return null;
}
char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');
return ret;
}
}
| Java |
package sample.module;
public class Credentials {
String username;
String password;
String salt;
public Credentials() {
}
public Credentials(String username, String password, String salt) {
super();
this.username = username;
this.password = password;
this.salt = salt;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
| Java |
/*
* @(#)SampleLoginModule.java 1.18 00/01/11
*
* Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Oracle or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/
package sample.module;
import java.util.*;
import java.io.IOException;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import sample.principal.SamplePrincipal;
/**
* <p> This sample LoginModule authenticates users with a password.
*
* <p> This LoginModule only recognizes one user: testUser
* <p> testUser's password is: testPassword
*
* <p> If testUser successfully authenticates itself,
* a <code>SamplePrincipal</code> with the testUser's user name
* is added to the Subject.
*
* <p> This LoginModule recognizes the debug option.
* If set to true in the login Configuration,
* debug messages will be output to the output stream, System.out.
*
* @version 1.18, 01/11/00
*/
public class SampleLoginModule implements LoginModule {
// initial state
private Subject subject;
private CallbackHandler callbackHandler;
private Map sharedState;
private Map options;
// configurable option
private boolean debug = false;
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
// username and password
private String username;
private char[] password;
// testUser's SamplePrincipal
private SamplePrincipal userPrincipal;
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for user names and
* passwords, for example). <p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
public void initialize(Subject subject,
CallbackHandler callbackHandler,
Map<java.lang.String, ?> sharedState,
Map<java.lang.String, ?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// initialize any configured options
debug = "true".equalsIgnoreCase((String)options.get("debug"));
}
/**
* Authenticate the user by prompting for a user name and password.
*
* <p>
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*
* @exception FailedLoginException if the authentication fails. <p>
*
* @exception LoginException if this <code>LoginModule</code>
* is unable to perform the authentication.
*/
public boolean login() throws LoginException {
// prompt for a user name and password
if (callbackHandler == null)
throw new LoginException("Error: no CallbackHandler available " +
"to garner authentication information from the user");
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("user name: ");
callbacks[1] = new PasswordCallback("password: ", false);
try {
callbackHandler.handle(callbacks);
username = ((NameCallback)callbacks[0]).getName();
char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
if (tmpPassword == null) {
// treat a NULL password as an empty password
tmpPassword = new char[0];
}
password = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0,
password, 0, tmpPassword.length);
((PasswordCallback)callbacks[1]).clearPassword();
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("Error: " + uce.getCallback().toString() +
" not available to garner authentication information " +
"from the user");
}
// print debugging information
if (debug) {
System.out.println("\t\t[SampleLoginModule] " +
"user entered user name: " +
username);
System.out.print("\t\t[SampleLoginModule] " +
"user entered password: ");
for (int i = 0; i < password.length; i++)
System.out.print(password[i]);
System.out.println();
}
// verify the username/password
boolean usernameCorrect = false;
boolean passwordCorrect = false;
if (username.equals("testUser"))
usernameCorrect = true;
if (usernameCorrect &&
password.length == 12 &&
password[0] == 't' &&
password[1] == 'e' &&
password[2] == 's' &&
password[3] == 't' &&
password[4] == 'P' &&
password[5] == 'a' &&
password[6] == 's' &&
password[7] == 's' &&
password[8] == 'w' &&
password[9] == 'o' &&
password[10] == 'r' &&
password[11] == 'd') {
// authentication succeeded!!!
passwordCorrect = true;
if (debug)
System.out.println("\t\t[SampleLoginModule] " +
"authentication succeeded");
succeeded = true;
return true;
} else {
// authentication failed -- clean out state
if (debug)
System.out.println("\t\t[SampleLoginModule] " +
"authentication failed");
succeeded = false;
username = null;
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
if (!usernameCorrect) {
throw new FailedLoginException("User Name Incorrect");
} else {
throw new FailedLoginException("Password Incorrect");
}
}
}
/**
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method associates a
* <code>SamplePrincipal</code>
* with the <code>Subject</code> located in the
* <code>LoginModule</code>. If this LoginModule's own
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails.
*
* @return true if this LoginModule's own login and commit
* attempts succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
if (succeeded == false) {
return false;
} else {
// add a Principal (authenticated identity)
// to the Subject
// assume the user we authenticated is the SamplePrincipal
userPrincipal = new SamplePrincipal(username);
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (debug) {
System.out.println("\t\t[SampleLoginModule] " +
"added SamplePrincipal to Subject");
}
// in any case, clean out state
username = null;
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
commitSucceeded = true;
return true;
}
}
/**
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> and <code>commit</code> methods),
* then this method cleans up any state that was originally saved.
*
* <p>
*
* @exception LoginException if the abort fails.
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
// login succeeded but overall authentication failed
succeeded = false;
username = null;
if (password != null) {
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
}
userPrincipal = null;
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
}
/**
* Logout the user.
*
* <p> This method removes the <code>SamplePrincipal</code>
* that was added by the <code>commit</code> method.
*
* <p>
*
* @exception LoginException if the logout fails.
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*/
public boolean logout() throws LoginException {
subject.getPrincipals().remove(userPrincipal);
succeeded = false;
succeeded = commitSucceeded;
username = null;
if (password != null) {
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
}
userPrincipal = null;
return true;
}
}
| Java |
/*
* @(#)SampleLoginModule.java 1.18 00/01/11
*
* Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Oracle or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
* DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
* RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR
* ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
* FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
* SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
* THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or
* intended for use in the design, construction, operation or
* maintenance of any nuclear facility.
*/
package sample.module;
import integrity.VerifyKey;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import sample.principal.SamplePrincipal;
/**
* <p> This sample LoginModule authenticates users with a password.
*
* <p> This LoginModule only recognizes one user: testUser
* <p> testUser's password is: testPassword
*
* <p> If testUser successfully authenticates itself,
* a <code>SamplePrincipal</code> with the testUser's user name
* is added to the Subject.
*
* <p> This LoginModule recognizes the debug option.
* If set to true in the login Configuration,
* debug messages will be output to the output stream, System.out.
*
* @version 1.18, 01/11/00
*/
public class SampleLoginModuleFileInput implements LoginModule {
// initial state
private Subject subject;
private CallbackHandler callbackHandler;
private Map sharedState;
private Map options;
// configurable option
private boolean debug = false;
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
// username and password
private String username;
private char[] password;
// testUser's SamplePrincipal
private SamplePrincipal userPrincipal;
/**
* Initialize this <code>LoginModule</code>.
*
* <p>
*
* @param subject the <code>Subject</code> to be authenticated. <p>
*
* @param callbackHandler a <code>CallbackHandler</code> for communicating
* with the end user (prompting for user names and
* passwords, for example). <p>
*
* @param sharedState shared <code>LoginModule</code> state. <p>
*
* @param options options specified in the login
* <code>Configuration</code> for this particular
* <code>LoginModule</code>.
*/
public void initialize(Subject subject,
CallbackHandler callbackHandler,
Map<java.lang.String, ?> sharedState,
Map<java.lang.String, ?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
// initialize any configured options
debug = "true".equalsIgnoreCase((String)options.get("debug"));
}
/**
* Authenticate the user by prompting for a user name and password.
*
* <p>
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*
* @exception FailedLoginException if the authentication fails. <p>
*
* @exception LoginException if this <code>LoginModule</code>
* is unable to perform the authentication.
*/
public boolean login() throws LoginException {
// prompt for a user name and password
if (callbackHandler == null)
throw new LoginException("Error: no CallbackHandler available " +
"to garner authentication information from the user");
System.out.println("Trying to verify the db...");
Callback[] callbacks = new Callback[2];
try {
if (VerifyKey.VerifyFile() == true)
{
System.out.println("The signed files is OK! Please login...");
callbacks[0] = new NameCallback("user name: ");
callbacks[1] = new PasswordCallback("password: ", false);
}
else
{
System.out.println("The signed files has been tampered with...");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
callbackHandler.handle(callbacks);
username = ((NameCallback)callbacks[0]).getName();
char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
if (tmpPassword == null) {
// treat a NULL password as an empty password
tmpPassword = new char[0];
}
password = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0,
password, 0, tmpPassword.length);
((PasswordCallback)callbacks[1]).clearPassword();
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("Error: " + uce.getCallback().toString() +
" not available to garner authentication information " +
"from the user");
}
// print debugging information
if (debug) {
System.out.println("\t\t[SampleLoginModule] " +
"user entered user name: " +
username);
System.out.print("\t\t[SampleLoginModule] " +
"user entered password: ");
for (int i = 0; i < password.length; i++)
System.out.print(password[i]);
System.out.println();
}
// verify the username/password
boolean usernameCorrect = false;
boolean passwordCorrect = false;
HashMap<String, Credentials> userlist = readFile();
if (userlist.containsKey(username))
usernameCorrect = true;
if (usernameCorrect && userlist.get(username).password.equals(hashPassword(new String(password), userlist.get(username).getSalt()))) {
// authentication succeeded!!!
passwordCorrect = true;
if (debug)
System.out.println("\t\t[SampleLoginModule] " +
"authentication succeeded");
succeeded = true;
return true;
} else {
// authentication failed -- clean out state
if (debug)
System.out.println("\t\t[SampleLoginModule] " +
"authentication failed");
succeeded = false;
username = null;
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
if (!usernameCorrect) {
throw new FailedLoginException("User Name Incorrect");
} else {
throw new FailedLoginException("Password Incorrect");
}
}
}
/**
* <p> This method is called if the LoginContext's
* overall authentication succeeded
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* succeeded).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> method), then this method associates a
* <code>SamplePrincipal</code>
* with the <code>Subject</code> located in the
* <code>LoginModule</code>. If this LoginModule's own
* authentication attempted failed, then this method removes
* any state that was originally saved.
*
* <p>
*
* @exception LoginException if the commit fails.
*
* @return true if this LoginModule's own login and commit
* attempts succeeded, or false otherwise.
*/
public boolean commit() throws LoginException {
if (succeeded == false) {
return false;
} else {
// add a Principal (authenticated identity)
// to the Subject
// assume the user we authenticated is the SamplePrincipal
userPrincipal = new SamplePrincipal(username);
if (!subject.getPrincipals().contains(userPrincipal))
subject.getPrincipals().add(userPrincipal);
if (debug) {
System.out.println("\t\t[SampleLoginModule] " +
"added SamplePrincipal to Subject");
}
// in any case, clean out state
username = null;
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
commitSucceeded = true;
return true;
}
}
/**
* <p> This method is called if the LoginContext's
* overall authentication failed.
* (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules
* did not succeed).
*
* <p> If this LoginModule's own authentication attempt
* succeeded (checked by retrieving the private state saved by the
* <code>login</code> and <code>commit</code> methods),
* then this method cleans up any state that was originally saved.
*
* <p>
*
* @exception LoginException if the abort fails.
*
* @return false if this LoginModule's own login and/or commit attempts
* failed, and true otherwise.
*/
public boolean abort() throws LoginException {
if (succeeded == false) {
return false;
} else if (succeeded == true && commitSucceeded == false) {
// login succeeded but overall authentication failed
succeeded = false;
username = null;
if (password != null) {
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
}
userPrincipal = null;
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
}
/**
* Logout the user.
*
* <p> This method removes the <code>SamplePrincipal</code>
* that was added by the <code>commit</code> method.
*
* <p>
*
* @exception LoginException if the logout fails.
*
* @return true in all cases since this <code>LoginModule</code>
* should not be ignored.
*/
public boolean logout() throws LoginException {
subject.getPrincipals().remove(userPrincipal);
succeeded = false;
succeeded = commitSucceeded;
username = null;
if (password != null) {
for (int i = 0; i < password.length; i++)
password[i] = ' ';
password = null;
}
userPrincipal = null;
return true;
}
public HashMap<String, Credentials> readFile() {
String filename = "credentials.txt";
HashMap<String, Credentials> hashmap = new HashMap<String, Credentials>();
try {
BufferedReader file = new BufferedReader(new FileReader(filename));
String readText;
while ((readText = file.readLine()) != null) {
String[] fileinput=readText.split(",");
Credentials cre = new Credentials();
cre.setUsername(fileinput[0]);
cre.setPassword(fileinput[1]);
cre.setSalt(fileinput[2]);
//addding the user object to the hashmap of all the users
hashmap.put(cre.getUsername(), cre);
}
} catch (Exception e) {
System.out.println("File Read Error");
}
return hashmap;
}
public String hashPassword(String pwd, String slt) {
//Using SHA-1 encryption on the password
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
System.out.println("WHOOPS. No such algorithm...");
}
//Updating the digest with the password
//get the password in bytes
digest.update(pwd.getBytes());
//Updating the hash again with the salt
//get the salt in bytes
digest.update(slt.getBytes());
//converting the bytes to integers and converting it toString to get the hashValue.
return new BigInteger(1, digest.digest()).toString(16);
}
}
| Java |
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
//import javax.swing.*;
import com.sun.java.swing.*;
import java.io.*;
import java.net.*;
import java.rmi.*;
import java.rmi.server.*;
import javax.crypto.*;
import javax.swing.*;
import java.security.*;
import java.security.interfaces.*;
class RMIClient1 extends JFrame
implements ActionListener{
JLabel col1, col2;
JLabel totalItems, totalCost;
JLabel cardNum, custID;
JLabel applechk, pearchk, peachchk;
JButton purchase, reset;
JPanel panel;
JTextField appleqnt, pearqnt, peachqnt;
JTextField creditCard, customer;
JTextArea items, cost;
static Send send;
int itotal=0;
double icost=0;
RMIClient1(){ //Begin Constructor
//Create left and right column labels
col1 = new JLabel("Select Items");
col2 = new JLabel("Specify Quantity");
//Create labels and text field components
applechk = new JLabel(" Apples");
appleqnt = new JTextField();
appleqnt.addActionListener(this);
pearchk = new JLabel(" Pears");
pearqnt = new JTextField();
pearqnt.addActionListener(this);
peachchk = new JLabel(" Peaches");
peachqnt = new JTextField();
peachqnt.addActionListener(this);
cardNum = new JLabel(" Credit Card:");
creditCard = new JTextField();
pearqnt.setNextFocusableComponent(creditCard);
customer = new JTextField();
custID = new JLabel(" Customer ID:");
//Create labels and text area components
totalItems = new JLabel("Total Items:");
totalCost = new JLabel("Total Cost:");
items = new JTextArea();
cost = new JTextArea();
//Create buttons and make action listeners
purchase = new JButton("Purchase");
purchase.addActionListener(this);
reset = new JButton("Reset");
reset.addActionListener(this);
creditCard.setNextFocusableComponent(reset);
//Create a panel for the components
panel = new JPanel();
//Set panel layout to 2-column grid
//on a white background
panel.setLayout(new GridLayout(0,2));
panel.setBackground(Color.white);
//Add components to panel columns
//going left to right and top to bottom
getContentPane().add(panel);
panel.add(col1);
panel.add(col2);
panel.add(applechk);
panel.add(appleqnt);
panel.add(peachchk);
panel.add(peachqnt);
panel.add(pearchk);
panel.add(pearqnt);
panel.add(totalItems);
panel.add(items);
panel.add(totalCost);
panel.add(cost);
panel.add(cardNum);
panel.add(creditCard);
panel.add(custID);
panel.add(customer);
panel.add(reset);
panel.add(purchase);
} //End Constructor
private void encrypt(String creditCardNumber) throws Exception {
// Create cipher for symmetric key encryption (DES)
Cipher myCipher = Cipher.getInstance("DES");
// Create a key generator
KeyGenerator kg = KeyGenerator.getInstance("DES");
// Create a secret (session) key with key generator
SecretKey sk = kg.generateKey();
// Initialize cipher for encryption with session key
myCipher.init(Cipher.DECRYPT_MODE, sk);
// Encrypt credit card number with cipher
myCipher.doFinal(creditCardNumber.getBytes());
// Get public key from server
// Create cipher for asymmetric encryption (so not use RSA)
// Initialize cipher for encryption with public key
// Seal session key using asymmetric cipher
// Serialize sealed session key
// Send encrypted credit card number and
// sealed session key to server
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
Integer applesNo, peachesNo, pearsNo, num;
Double cost;
String number, cardnum, custID, apples, peaches, pears, text, text2;
//If Purchase button pressed
if(source == purchase){
//Get data from text fields
cardnum = creditCard.getText();
custID = customer.getText();
apples = appleqnt.getText();
peaches = peachqnt.getText();
pears = pearqnt.getText();
//Calculate total items
if(apples.length() > 0){
//Catch invalid number error
try{
applesNo = Integer.valueOf(apples);
itotal += applesNo.intValue();
}catch(java.lang.NumberFormatException e){
appleqnt.setText("Invalid Value");
}
} else {
itotal += 0;
}
if(peaches.length() > 0){
//Catch invalid number error
try{
peachesNo = Integer.valueOf(peaches);
itotal += peachesNo.intValue();
}catch(java.lang.NumberFormatException e){
peachqnt.setText("Invalid Value");
}
} else {
itotal += 0;
}
if(pears.length() > 0){
//Catch invalid number error
try{
pearsNo = Integer.valueOf(pears);
itotal += pearsNo.intValue();
}catch(java.lang.NumberFormatException e){
pearqnt.setText("Invalid Value");
}
} else {
itotal += 0;
}
//Display running total
num = new Integer(itotal);
text = num.toString();
this.items.setText(text);
//Calculate and display running cost
icost = (itotal * 1.25);
cost = new Double(icost);
text2 = cost.toString();
this.cost.setText(text2);
//Encrypt credit card number
try {
encrypt(cardnum);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Send data over net
try{
send.sendCustID(custID);
send.sendAppleQnt(apples);
send.sendPeachQnt(peaches);
send.sendPearQnt(pears);
send.sendTotalCost(icost);
send.sendTotalItems(itotal);
} catch (java.rmi.RemoteException e) {
System.out.println("sendData exception: " + e.getMessage());
}
}
//If Reset button pressed
//Clear all fields
if(source == reset){
creditCard.setText("");
appleqnt.setText("");
peachqnt.setText("");
pearqnt.setText("");
creditCard.setText("");
customer.setText("");
icost = 0;
cost = new Double(icost);
text2 = cost.toString();
this.cost.setText(text2);
itotal = 0;
num = new Integer(itotal);
text = num.toString();
this.items.setText(text);
}
}
public static void main(String[] args){
try{
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
}catch (Exception e) {
System.out.println("Couldn't use the cross-platform"
+ "look and feel: " + e);
}
RMIClient1 frame = new RMIClient1();
frame.setTitle("Fruit $1.25 Each");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
String name = "//" + args[0] + "/Send";
send = ((Send) Naming.lookup(name));
} catch (Exception e) {
System.out.println("RMIClient1 exception: " + e.getMessage());
e.printStackTrace();
}
}
} | Java |
public interface Send {
void sendCustID(String custID);
void sendAppleQnt(String apples);
void sendPeachQnt(String peaches);
void sendPearQnt(String pears);
void sendTotalCost(double icost);
void sendTotalItems(int itotal);
String getCustID();
String getAppleQnt();
String getPeachQnt();
String getPearQnt();
double getTotalCost();
int getTotalItems();
byte[] getKey();
byte[] getEncrypted();
}
| Java |
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.SecureRandom;
public class RemoteServer {
//Generate and getPublicKey
public PublicKey getPublicKey() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
keyGen.initialize(512, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
java.io.FileOutputStream fos = new java.io.FileOutputStream("test.txt");
fos.close();
return keyPair.getPublic();
}
//A method to send the encryped credit card number
//A method to get the encrypted credit card number
//A method to send the encrypted symmetric key
//A method to get the encrypted symmetric key
}
| Java |
public class Kryptering01 {
public static void main() {
}
}
| Java |
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
//import javax.swing.*;
import com.sun.java.swing.*;
import java.io.*;
import java.net.*;
import java.rmi.*;
import java.rmi.server.*;
import java.io.FileInputStream.*;
import java.io.RandomAccessFile.*;
import java.io.File;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.swing.*;
import java.security.*;
class RMIClient2 extends JFrame
implements ActionListener {
JLabel creditCard, custID, apples, peaches, pears, total, cost, clicked;
JButton view, reset;
JPanel panel;
JTextArea creditNo, customerNo, applesNo, peachesNo, pearsNo, itotal, icost;
Socket socket = null;
PrintWriter out = null;
static Send send;
String customer;
RMIClient2(){ //Begin Constructor
//Create labels
creditCard = new JLabel("Credit Card:");
custID = new JLabel("Customer ID:");
apples = new JLabel("Apples:");
peaches = new JLabel("Peaches:");
pears = new JLabel("Pears:");
total = new JLabel("Total Items:");
cost = new JLabel("Total Cost:");
//Create text area components
creditNo = new JTextArea();
customerNo = new JTextArea();
applesNo = new JTextArea();
peachesNo = new JTextArea();
pearsNo = new JTextArea();
itotal = new JTextArea();
icost = new JTextArea();
//Create buttons
view = new JButton("View Order");
view.addActionListener(this);
reset = new JButton("Reset");
reset.addActionListener(this);
//Create panel for 2-column layout
//Set white background color
panel = new JPanel();
panel.setLayout(new GridLayout(0,2));
panel.setBackground(Color.white);
//Add components to panel columns
//going left to right and top to bottom
getContentPane().add(panel);
panel.add(creditCard);
panel.add(creditNo);
panel.add(custID);
panel.add(customerNo);
panel.add(apples);
panel.add(applesNo);
panel.add(peaches);
panel.add(peachesNo);
panel.add(pears);
panel.add(pearsNo);
panel.add(total);
panel.add(itotal);
panel.add(cost);
panel.add(icost);
panel.add(view);
panel.add(reset);
} //End Constructor
public String decrypt(sealed key, encrypted credit card number){
// Get private key from file
// Create asymmetric cipher (do not use RSA)
// Initialize cipher for decryption with private key
// Unseal wrapped session key using asymmetric cipher
// Create symmetric cipher
// Initialize cipher for decryption with session key
// Decrypt credit card number with symmetric cipher
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
String text=null, unit, i;
byte[] wrappedKey;
byte[] encrypted;
double cost;
Double price;
int items;
Integer itms;
//If View button pressed
//Get data from server and display it
if(source == view){
try{
wrappedKey = send.getKey();
encrypted = send.getEncrypted();
//Decrypt credit card number
String credit = decrypt(sealed, encrypted);
creditNo.setText(new String(credit));
text = send.getCustID();
customerNo.setText(text);
text = send.getAppleQnt();
applesNo.setText(text);
text = send.getPeachQnt();
peachesNo.setText(text);
text = send.getPearQnt();
pearsNo.setText(text);
cost = send.getTotalCost();
price = new Double(cost);
unit = price.toString();
icost.setText(unit);
items = send.getTotalItems();
itms = new Integer(items);
i = itms.toString();
itotal.setText(i);
} catch (java.rmi.RemoteException e) {
System.out.println("sendData exception: " + e.getMessage());
}
}
//If Reset button pressed
//Clear all fields
if(source == reset){
creditNo.setText("");
customerNo.setText("");
applesNo.setText("");
peachesNo.setText("");
pearsNo.setText("");
itotal.setText("");
icost.setText("");
}
}
public static void main(String[] args){
RMIClient2 frame = new RMIClient2();
frame.setTitle("Fruit Order");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
frame.addWindowListener(l);
frame.pack();
frame.setVisible(true);
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
String name = "//" + args[0] + "/Send";
send = ((Send) Naming.lookup(name));
} catch (java.rmi.NotBoundException e) {
System.out.println("Cannot access data in server");
} catch(java.rmi.RemoteException e){
System.out.println("Cannot access data in server");
} catch(java.net.MalformedURLException e) {
System.out.println("Cannot access data in server");
}
}
} | Java |
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Scanner;
public class GenerateSignature {
/**
* @param args
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
Scanner scan= new Scanner(System.in);
//byte[] keyBytes = ("this is my key").getBytes("UTF-8");
// keyBytes = Arrays.copyOf(keyBytes, 16);
KeyGenerator keygen=KeyGenerator.getInstance("AES");
keygen.init(128);
SecretKey skey=keygen.generateKey();
Boolean run=true;
while(run){
System.out.println("Press 1 for signing your file and 2 for verifying your file and 3 for terminating program:");
int choice = scan.nextInt();
scan.nextLine();
switch(choice){
case 1:
System.out.println("Generating private and public key..");
try{
//read in file
scan.reset();
System.out.println("Write path to the data file:");
String path=scan.nextLine();
String folderPath=path.substring(0, path.lastIndexOf("client 1"));
File file= new File(path);
byte[] data = new byte[(int)file.length()];
FileInputStream fileInput=new FileInputStream(file);
fileInput.read(data);
//encrypt byte data
System.out.println("input text : " + new String(data));
Cipher c = Cipher.getInstance("AES");
//SecretKeySpec k = new SecretKeySpec(keyBytes, "AES");
c.init(Cipher.ENCRYPT_MODE, skey);
byte[] encryptedData = c.doFinal(data);
System.out.println("encrypted data: " + new String(encryptedData));
//save encrypted data in file
FileOutputStream fos = new FileOutputStream(folderPath+"client 2\\encryptedData");
fos.write(encryptedData);
fos.close();
//make private and public key for signature
System.out.println("Generating private and public key");
KeyPairGenerator keyGen= KeyPairGenerator.getInstance("RSA");
SecureRandom random=SecureRandom.getInstance("SHA1PRNG", "SUN");
keyGen.initialize(1024, random);
KeyPair pair=keyGen.generateKeyPair();
PrivateKey privateK=pair.getPrivate();
PublicKey publicK=pair.getPublic();
System.out.println("Generating signature for file");
Signature sigDSA=Signature.getInstance("SHA1withRSA");
sigDSA.initSign(privateK);
FileInputStream fis=new FileInputStream(folderPath+"\\client 2\\encryptedData");
BufferedInputStream buf= new BufferedInputStream(fis);
byte[] buffer=new byte[1024];
int len;
while((len=buf.read(buffer))>=0){
sigDSA.update(buffer, 0, len);
}
buf.close();
byte [] finalSig=sigDSA.sign();
/* save the signature in a file */
FileOutputStream sigfos = new FileOutputStream(folderPath+"\\client 2\\signedFile");
sigfos.write(finalSig);
sigfos.close();
/* save the public key in a file */
byte[] publicKey = publicK.getEncoded();
FileOutputStream keyfos = new FileOutputStream(folderPath+"client 2\\publicKey");
keyfos.write(publicKey);
keyfos.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
break;
case 2:
try{
System.out.println("Write path to the folder where public key, signed file and ecrypted data is located:");
String folderPathPubAndSig=scan.nextLine();
System.out.println("getting public key");
FileInputStream keyInput = new FileInputStream(folderPathPubAndSig+"\\publicKey");
byte[] encKey = new byte[keyInput.available()];
keyInput.read(encKey);
keyInput.close();
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
System.out.println("getting signed file");
FileInputStream sigInput = new FileInputStream(folderPathPubAndSig+"\\signedFile");
byte[] sigToVerify = new byte[sigInput.available()];
sigInput.read(sigToVerify);
sigInput.close();
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(pubKey);
System.out.println("getting ecrypted data");
FileInputStream dataInput = new FileInputStream(folderPathPubAndSig+"\\encryptedData");
BufferedInputStream bufin = new BufferedInputStream(dataInput);
byte[] buffer = new byte[1024];
int len;
while (bufin.available() != 0) {
len = bufin.read(buffer);
sig.update(buffer, 0, len);
};
bufin.close();
boolean verifies = sig.verify(sigToVerify);
System.out.println("signature verifies: " + verifies);
if(verifies){
System.out.println("the decrypted messeage: ");
File file= new File(folderPathPubAndSig+"\\encryptedData");
byte[] encryptedData = new byte[(int)file.length()];
FileInputStream fileInput=new FileInputStream(file);
fileInput.read(encryptedData);
Cipher c = Cipher.getInstance("AES");
//SecretKeySpec k = new SecretKeySpec(keyBytes, "AES");
c.init(Cipher.DECRYPT_MODE, skey);
byte[] decryptData = c.doFinal(encryptedData);
System.out.println("Decrypted data: " + new String(decryptData));
}
}
catch(Exception e2)
{
}
break;
case 3:
run=false;
break;
}
}
}
}
| Java |
// -*- Java -*-
/*!
* @file ProxyComp.java
* @brief Standalone component
* @date $Date$
*
* $Id$
*/
import RTC.ComponentProfile;
import RTC.PortInterfacePolarity;
import RTC.PortInterfaceProfileListHolder;
import RTC.PortService;
import RTC.PortServiceListHolder;
import _SDOPackage.NVListHolder;
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.ModuleInitProc;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.util.NVUtil;
import jp.go.aist.rtm.RTC.util.Properties;
/*
* ! @class ProxyComp @brief Standalone component Class
*
*/
public class ProxyComp implements ModuleInitProc {
public void myModuleInit(Manager mgr) {
Properties prop = new Properties(Proxy.component_conf);
mgr.registerFactory(prop, new Proxy(), new Proxy());
// Create a component
RTObject_impl comp = mgr.createComponent("Proxy");
if (comp == null) {
System.err.println("Component create failed.");
System.exit(0);
}
// Create a component
System.out.println("Creating a component: \"Proxy\"....");
System.out.println("succeed.");
ComponentProfile prof = comp.get_component_profile();
System.out.println( "=================================================" );
System.out.println( " Component Profile" );
System.out.println( "-------------------------------------------------" );
System.out.println( "InstanceID: " + prof.instance_name );
System.out.println( "Implementation: " + prof.type_name );
System.out.println( "Description: " + prof.description );
System.out.println( "Version: " + prof.version );
System.out.println( "Maker: " + prof.vendor );
System.out.println( "Category: " + prof.category );
System.out.println( " Other properties " );
NVUtil.dump(new NVListHolder(prof.properties));
System.out.println( "=================================================" );
PortServiceListHolder portlist = new PortServiceListHolder(comp.get_ports());
for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
PortService port = portlist.value[intIdx];
System.out.println( "=================================================" );
System.out.println( "Port" + intIdx + " (name): ");
System.out.println( port.get_port_profile().name );
System.out.println( "-------------------------------------------------" );
PortInterfaceProfileListHolder iflist = new PortInterfaceProfileListHolder(port.get_port_profile().interfaces);
for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
System.out.println( "I/F name: " );
System.out.println( iflist.value[intIdx2].instance_name );
System.out.println( "I/F type: ");
System.out.println( iflist.value[intIdx2].type_name );
if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED ) {
System.out.println( "Polarity: PROVIDED" );
} else {
System.out.println( "Polarity: REQUIRED" );
}
}
System.out.println( "- properties -" );
NVUtil.dump(new NVListHolder(port.get_port_profile().properties));
System.out.println( "-------------------------------------------------" );
}
// Example
// The following procedure is examples how handle RT-Components.
// These should not be in this function.
// // Get the component's object reference
// Manager manager = Manager.instance();
// RTObject rtobj = null;
// try {
// rtobj =
// RTObjectHelper.narrow(manager.getPOA().servant_to_reference(comp));
// } catch (ServantNotActive e) {
// e.printStackTrace();
// } catch (WrongPolicy e) {
// e.printStackTrace();
// }
//
// // Get the port list of the component
// PortListHolder portlist = new PortListHolder();
// portlist.value = rtobj.get_ports();
//
// // getting port profiles
// System.out.println( "Number of Ports: " );
// System.out.println( portlist.value.length );
// for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
// Port port = portlist.value[intIdx];
// System.out.println( "Port" + intIdx + " (name): ");
// System.out.println( port.get_port_profile().name );
//
// PortInterfaceProfileListHolder iflist = new
// PortInterfaceProfileListHolder();
// iflist.value = port.get_port_profile().interfaces;
// System.out.println( "---interfaces---" );
// for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
// System.out.println( "I/F name: " );
// System.out.println( iflist.value[intIdx2].instance_name );
// System.out.println( "I/F type: " );
// System.out.println( iflist.value[intIdx2].type_name );
// if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED )
// {
// System.out.println( "Polarity: PROVIDED" );
// } else {
// System.out.println( "Polarity: REQUIRED" );
// }
// }
// System.out.println( "---properties---" );
// NVUtil.dump( new NVListHolder(port.get_port_profile().properties) );
// System.out.println( "----------------" );
// }
}
public static void main(String[] args) {
// Initialize manager
final Manager manager = Manager.init(args);
// Set module initialization proceduer
// This procedure will be invoked in activateManager() function.
ProxyComp init = new ProxyComp();
manager.setModuleInitProc(init);
// Activate manager and register to naming service
manager.activateManager();
// run the manager in blocking mode
// runManager(false) is the default.
manager.runManager();
// If you want to run the manager in non-blocking mode, do like this
// manager.runManager(true);
}
}
| Java |
// -*- Java -*-
/*!
* @file Proxy.java
* @date $Date$
*
* $Id$
*/
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.RtcDeleteFunc;
import jp.go.aist.rtm.RTC.RtcNewFunc;
import jp.go.aist.rtm.RTC.util.Properties;
/*
* ! @class Proxy @brief RTC-Lite for Arduino
*/
public class Proxy implements RtcNewFunc, RtcDeleteFunc {
// Module specification
// <rtc-template block="module_spec">
public static String component_conf[] = { "implementation_id", "Proxy",
"type_name", "Proxy", "description", "RTC-Lite for Arduino",
"version", "1.0.0", "vendor", "AIST", "category", "Proxy",
"activity_type", "STATIC", "max_instance", "1", "language", "Java",
"lang_type", "compile", "exec_cxt.periodic.rate", "0.2",
// Configuration variables
"conf.default.MAC_addr", "00-00-00-00-00-00", "" };
// </rtc-template>
public RTObject_impl createRtc(Manager mgr) {
return new ProxyImpl(mgr);
}
public void deleteRtc(RTObject_impl rtcBase) {
rtcBase = null;
}
public void registerModule() {
Properties prop = new Properties(component_conf);
final Manager manager = Manager.instance();
manager.registerFactory(prop, new Proxy(), new Proxy());
}
}
| Java |
// -*- Java -*-
/*!
* @file ProxyComp.java
* @brief Standalone component
* @date $Date$
*
* $Id$
*/
import RTC.ComponentProfile;
import RTC.PortInterfacePolarity;
import RTC.PortInterfaceProfileListHolder;
import RTC.PortService;
import RTC.PortServiceListHolder;
import _SDOPackage.NVListHolder;
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.ModuleInitProc;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.util.NVUtil;
import jp.go.aist.rtm.RTC.util.Properties;
/*
* ! @class ProxyComp @brief Standalone component Class
*
*/
public class ProxyComp implements ModuleInitProc {
public void myModuleInit(Manager mgr) {
Properties prop = new Properties(Proxy.component_conf);
mgr.registerFactory(prop, new Proxy(), new Proxy());
// Create a component
RTObject_impl comp = mgr.createComponent("Proxy");
if (comp == null) {
System.err.println("Component create failed.");
System.exit(0);
}
// Create a component
System.out.println("Creating a component: \"Proxy\"....");
System.out.println("succeed.");
ComponentProfile prof = comp.get_component_profile();
System.out.println( "=================================================" );
System.out.println( " Component Profile" );
System.out.println( "-------------------------------------------------" );
System.out.println( "InstanceID: " + prof.instance_name );
System.out.println( "Implementation: " + prof.type_name );
System.out.println( "Description: " + prof.description );
System.out.println( "Version: " + prof.version );
System.out.println( "Maker: " + prof.vendor );
System.out.println( "Category: " + prof.category );
System.out.println( " Other properties " );
NVUtil.dump(new NVListHolder(prof.properties));
System.out.println( "=================================================" );
PortServiceListHolder portlist = new PortServiceListHolder(comp.get_ports());
for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
PortService port = portlist.value[intIdx];
System.out.println( "=================================================" );
System.out.println( "Port" + intIdx + " (name): ");
System.out.println( port.get_port_profile().name );
System.out.println( "-------------------------------------------------" );
PortInterfaceProfileListHolder iflist = new PortInterfaceProfileListHolder(port.get_port_profile().interfaces);
for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
System.out.println( "I/F name: " );
System.out.println( iflist.value[intIdx2].instance_name );
System.out.println( "I/F type: ");
System.out.println( iflist.value[intIdx2].type_name );
if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED ) {
System.out.println( "Polarity: PROVIDED" );
} else {
System.out.println( "Polarity: REQUIRED" );
}
}
System.out.println( "- properties -" );
NVUtil.dump(new NVListHolder(port.get_port_profile().properties));
System.out.println( "-------------------------------------------------" );
}
// Example
// The following procedure is examples how handle RT-Components.
// These should not be in this function.
// // Get the component's object reference
// Manager manager = Manager.instance();
// RTObject rtobj = null;
// try {
// rtobj =
// RTObjectHelper.narrow(manager.getPOA().servant_to_reference(comp));
// } catch (ServantNotActive e) {
// e.printStackTrace();
// } catch (WrongPolicy e) {
// e.printStackTrace();
// }
//
// // Get the port list of the component
// PortListHolder portlist = new PortListHolder();
// portlist.value = rtobj.get_ports();
//
// // getting port profiles
// System.out.println( "Number of Ports: " );
// System.out.println( portlist.value.length );
// for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
// Port port = portlist.value[intIdx];
// System.out.println( "Port" + intIdx + " (name): ");
// System.out.println( port.get_port_profile().name );
//
// PortInterfaceProfileListHolder iflist = new
// PortInterfaceProfileListHolder();
// iflist.value = port.get_port_profile().interfaces;
// System.out.println( "---interfaces---" );
// for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
// System.out.println( "I/F name: " );
// System.out.println( iflist.value[intIdx2].instance_name );
// System.out.println( "I/F type: " );
// System.out.println( iflist.value[intIdx2].type_name );
// if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED )
// {
// System.out.println( "Polarity: PROVIDED" );
// } else {
// System.out.println( "Polarity: REQUIRED" );
// }
// }
// System.out.println( "---properties---" );
// NVUtil.dump( new NVListHolder(port.get_port_profile().properties) );
// System.out.println( "----------------" );
// }
}
public static void main(String[] args) {
// Initialize manager
final Manager manager = Manager.init(args);
// Set module initialization proceduer
// This procedure will be invoked in activateManager() function.
ProxyComp init = new ProxyComp();
manager.setModuleInitProc(init);
// Activate manager and register to naming service
manager.activateManager();
// run the manager in blocking mode
// runManager(false) is the default.
manager.runManager();
// If you want to run the manager in non-blocking mode, do like this
// manager.runManager(true);
}
}
| Java |
// -*- Java -*-
/*!
* @file Proxy.java
* @date $Date$
*
* $Id$
*/
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.RtcDeleteFunc;
import jp.go.aist.rtm.RTC.RtcNewFunc;
import jp.go.aist.rtm.RTC.util.Properties;
/*
* ! @class Proxy @brief RTC-Lite for Arduino
*/
public class Proxy implements RtcNewFunc, RtcDeleteFunc {
// Module specification
// <rtc-template block="module_spec">
public static String component_conf[] = { "implementation_id", "Proxy",
"type_name", "Proxy", "description", "RTC-Lite for Arduino",
"version", "1.0.0", "vendor", "AIST", "category", "Proxy",
"activity_type", "STATIC", "max_instance", "1", "language", "Java",
"lang_type", "compile", "exec_cxt.periodic.rate", "0.2",
// Configuration variables
"conf.default.MAC_addr", "00-00-00-00-00-00", "" };
// </rtc-template>
public RTObject_impl createRtc(Manager mgr) {
return new ProxyImpl(mgr);
}
public void deleteRtc(RTObject_impl rtcBase) {
rtcBase = null;
}
public void registerModule() {
Properties prop = new Properties(component_conf);
final Manager manager = Manager.instance();
manager.registerFactory(prop, new Proxy(), new Proxy());
}
}
| Java |
// -*- Java -*-
/*!
* @file GAEConnectorComp.java
* @brief Standalone component
* @date $Date$
*
* $Id$
*/
import RTC.ComponentProfile;
import RTC.PortInterfacePolarity;
import RTC.PortInterfaceProfileListHolder;
import RTC.PortService;
import RTC.PortServiceListHolder;
import _SDOPackage.NVListHolder;
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.ModuleInitProc;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.util.NVUtil;
import jp.go.aist.rtm.RTC.util.Properties;
/*!
* @class GAEConnectorComp
* @brief Standalone component Class
*
*/
public class GAEConnectorComp implements ModuleInitProc {
public void myModuleInit(Manager mgr) {
Properties prop = new Properties(GAEConnector.component_conf);
mgr.registerFactory(prop, new GAEConnector(), new GAEConnector());
// Create a component
RTObject_impl comp = mgr.createComponent("GAEConnector");
if( comp==null ) {
System.err.println("Component create failed.");
System.exit(0);
}
// Create a component
System.out.println("Creating a component: \"GAEConnector\"....");
System.out.println("succeed.");
ComponentProfile prof = comp.get_component_profile();
System.out.println( "=================================================" );
System.out.println( " Component Profile" );
System.out.println( "-------------------------------------------------" );
System.out.println( "InstanceID: " + prof.instance_name );
System.out.println( "Implementation: " + prof.type_name );
System.out.println( "Description: " + prof.description );
System.out.println( "Version: " + prof.version );
System.out.println( "Maker: " + prof.vendor );
System.out.println( "Category: " + prof.category );
System.out.println( " Other properties " );
NVUtil.dump(new NVListHolder(prof.properties));
System.out.println( "=================================================" );
PortServiceListHolder portlist = new PortServiceListHolder(comp.get_ports());
for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
PortService port = portlist.value[intIdx];
System.out.println( "=================================================" );
System.out.println( "Port" + intIdx + " (name): ");
System.out.println( port.get_port_profile().name );
System.out.println( "-------------------------------------------------" );
PortInterfaceProfileListHolder iflist = new PortInterfaceProfileListHolder(port.get_port_profile().interfaces);
for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
System.out.println( "I/F name: " );
System.out.println( iflist.value[intIdx2].instance_name );
System.out.println( "I/F type: ");
System.out.println( iflist.value[intIdx2].type_name );
if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED ) {
System.out.println( "Polarity: PROVIDED" );
} else {
System.out.println( "Polarity: REQUIRED" );
}
}
System.out.println( "- properties -" );
NVUtil.dump(new NVListHolder(port.get_port_profile().properties));
System.out.println( "-------------------------------------------------" );
}
// Example
// The following procedure is examples how handle RT-Components.
// These should not be in this function.
// // Get the component's object reference
// Manager manager = Manager.instance();
// RTObject rtobj = null;
// try {
// rtobj = RTObjectHelper.narrow(manager.getPOA().servant_to_reference(comp));
// } catch (ServantNotActive e) {
// e.printStackTrace();
// } catch (WrongPolicy e) {
// e.printStackTrace();
// }
//
// // Get the port list of the component
// PortListHolder portlist = new PortListHolder();
// portlist.value = rtobj.get_ports();
//
// // getting port profiles
// System.out.println( "Number of Ports: " );
// System.out.println( portlist.value.length );
// for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
// Port port = portlist.value[intIdx];
// System.out.println( "Port" + intIdx + " (name): ");
// System.out.println( port.get_port_profile().name );
//
// PortInterfaceProfileListHolder iflist = new PortInterfaceProfileListHolder();
// iflist.value = port.get_port_profile().interfaces;
// System.out.println( "---interfaces---" );
// for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
// System.out.println( "I/F name: " );
// System.out.println( iflist.value[intIdx2].instance_name );
// System.out.println( "I/F type: " );
// System.out.println( iflist.value[intIdx2].type_name );
// if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED ) {
// System.out.println( "Polarity: PROVIDED" );
// } else {
// System.out.println( "Polarity: REQUIRED" );
// }
// }
// System.out.println( "---properties---" );
// NVUtil.dump( new NVListHolder(port.get_port_profile().properties) );
// System.out.println( "----------------" );
// }
}
public static void main(String[] args) {
// Initialize manager
final Manager manager = Manager.init(args);
// Set module initialization proceduer
// This procedure will be invoked in activateManager() function.
GAEConnectorComp init = new GAEConnectorComp();
manager.setModuleInitProc(init);
// Activate manager and register to naming service
manager.activateManager();
// run the manager in blocking mode
// runManager(false) is the default.
manager.runManager();
// If you want to run the manager in non-blocking mode, do like this
// manager.runManager(true);
}
}
| Java |
// -*- Java -*-
/*!
* @file GAEConnector.java
* @date $Date$
*
* $Id$
*/
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.RtcDeleteFunc;
import jp.go.aist.rtm.RTC.RtcNewFunc;
import jp.go.aist.rtm.RTC.RegisterModuleFunc;
import jp.go.aist.rtm.RTC.util.Properties;
/*!
* @class GAEConnector
* @brief http connector for GAE
*/
public class GAEConnector implements RtcNewFunc, RtcDeleteFunc, RegisterModuleFunc {
// Module specification
// <rtc-template block="module_spec">
public static String component_conf[] = {
"implementation_id", "GAEConnector",
"type_name", "GAEConnector",
"description", "http connector for GAE",
"version", "1.0.0",
"vendor", "AIST",
"category", "Connector",
"activity_type", "STATIC",
"max_instance", "1",
"language", "Java",
"lang_type", "compile",
"exec_cxt.periodic.rate", "1.0",
// Configuration variables
"conf.default.Account", "xxxxxxxx",
"conf.default.Password", "xxxxxxxx",
""
};
// </rtc-template>
public RTObject_impl createRtc(Manager mgr) {
return new GAEConnectorImpl(mgr);
}
public void deleteRtc(RTObject_impl rtcBase) {
rtcBase = null;
}
public void registerModule() {
Properties prop = new Properties(component_conf);
final Manager manager = Manager.instance();
manager.registerFactory(prop, new GAEConnector(), new GAEConnector());
}
}
| Java |
// -*- Java -*-
/*!
* @file GAEConnectorComp.java
* @brief Standalone component
* @date $Date$
*
* $Id$
*/
import RTC.ComponentProfile;
import RTC.PortInterfacePolarity;
import RTC.PortInterfaceProfileListHolder;
import RTC.PortService;
import RTC.PortServiceListHolder;
import _SDOPackage.NVListHolder;
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.ModuleInitProc;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.util.NVUtil;
import jp.go.aist.rtm.RTC.util.Properties;
/*!
* @class GAEConnectorComp
* @brief Standalone component Class
*
*/
public class GAEConnectorComp implements ModuleInitProc {
public void myModuleInit(Manager mgr) {
Properties prop = new Properties(GAEConnector.component_conf);
mgr.registerFactory(prop, new GAEConnector(), new GAEConnector());
// Create a component
RTObject_impl comp = mgr.createComponent("GAEConnector");
if( comp==null ) {
System.err.println("Component create failed.");
System.exit(0);
}
// Create a component
System.out.println("Creating a component: \"GAEConnector\"....");
System.out.println("succeed.");
ComponentProfile prof = comp.get_component_profile();
System.out.println( "=================================================" );
System.out.println( " Component Profile" );
System.out.println( "-------------------------------------------------" );
System.out.println( "InstanceID: " + prof.instance_name );
System.out.println( "Implementation: " + prof.type_name );
System.out.println( "Description: " + prof.description );
System.out.println( "Version: " + prof.version );
System.out.println( "Maker: " + prof.vendor );
System.out.println( "Category: " + prof.category );
System.out.println( " Other properties " );
NVUtil.dump(new NVListHolder(prof.properties));
System.out.println( "=================================================" );
PortServiceListHolder portlist = new PortServiceListHolder(comp.get_ports());
for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
PortService port = portlist.value[intIdx];
System.out.println( "=================================================" );
System.out.println( "Port" + intIdx + " (name): ");
System.out.println( port.get_port_profile().name );
System.out.println( "-------------------------------------------------" );
PortInterfaceProfileListHolder iflist = new PortInterfaceProfileListHolder(port.get_port_profile().interfaces);
for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
System.out.println( "I/F name: " );
System.out.println( iflist.value[intIdx2].instance_name );
System.out.println( "I/F type: ");
System.out.println( iflist.value[intIdx2].type_name );
if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED ) {
System.out.println( "Polarity: PROVIDED" );
} else {
System.out.println( "Polarity: REQUIRED" );
}
}
System.out.println( "- properties -" );
NVUtil.dump(new NVListHolder(port.get_port_profile().properties));
System.out.println( "-------------------------------------------------" );
}
// Example
// The following procedure is examples how handle RT-Components.
// These should not be in this function.
// // Get the component's object reference
// Manager manager = Manager.instance();
// RTObject rtobj = null;
// try {
// rtobj = RTObjectHelper.narrow(manager.getPOA().servant_to_reference(comp));
// } catch (ServantNotActive e) {
// e.printStackTrace();
// } catch (WrongPolicy e) {
// e.printStackTrace();
// }
//
// // Get the port list of the component
// PortListHolder portlist = new PortListHolder();
// portlist.value = rtobj.get_ports();
//
// // getting port profiles
// System.out.println( "Number of Ports: " );
// System.out.println( portlist.value.length );
// for( int intIdx=0;intIdx<portlist.value.length;++intIdx ) {
// Port port = portlist.value[intIdx];
// System.out.println( "Port" + intIdx + " (name): ");
// System.out.println( port.get_port_profile().name );
//
// PortInterfaceProfileListHolder iflist = new PortInterfaceProfileListHolder();
// iflist.value = port.get_port_profile().interfaces;
// System.out.println( "---interfaces---" );
// for( int intIdx2=0;intIdx2<iflist.value.length;++intIdx2 ) {
// System.out.println( "I/F name: " );
// System.out.println( iflist.value[intIdx2].instance_name );
// System.out.println( "I/F type: " );
// System.out.println( iflist.value[intIdx2].type_name );
// if( iflist.value[intIdx2].polarity==PortInterfacePolarity.PROVIDED ) {
// System.out.println( "Polarity: PROVIDED" );
// } else {
// System.out.println( "Polarity: REQUIRED" );
// }
// }
// System.out.println( "---properties---" );
// NVUtil.dump( new NVListHolder(port.get_port_profile().properties) );
// System.out.println( "----------------" );
// }
}
public static void main(String[] args) {
// Initialize manager
final Manager manager = Manager.init(args);
// Set module initialization proceduer
// This procedure will be invoked in activateManager() function.
GAEConnectorComp init = new GAEConnectorComp();
manager.setModuleInitProc(init);
// Activate manager and register to naming service
manager.activateManager();
// run the manager in blocking mode
// runManager(false) is the default.
manager.runManager();
// If you want to run the manager in non-blocking mode, do like this
// manager.runManager(true);
}
}
| Java |
// -*- Java -*-
/*!
* @file GAEConnector.java
* @date $Date$
*
* $Id$
*/
import jp.go.aist.rtm.RTC.Manager;
import jp.go.aist.rtm.RTC.RTObject_impl;
import jp.go.aist.rtm.RTC.RtcDeleteFunc;
import jp.go.aist.rtm.RTC.RtcNewFunc;
import jp.go.aist.rtm.RTC.RegisterModuleFunc;
import jp.go.aist.rtm.RTC.util.Properties;
/*!
* @class GAEConnector
* @brief http connector for GAE
*/
public class GAEConnector implements RtcNewFunc, RtcDeleteFunc, RegisterModuleFunc {
// Module specification
// <rtc-template block="module_spec">
public static String component_conf[] = {
"implementation_id", "GAEConnector",
"type_name", "GAEConnector",
"description", "http connector for GAE",
"version", "1.0.0",
"vendor", "AIST",
"category", "Connector",
"activity_type", "STATIC",
"max_instance", "1",
"language", "Java",
"lang_type", "compile",
"exec_cxt.periodic.rate", "1.0",
// Configuration variables
"conf.default.Account", "xxxxxxxx",
"conf.default.Password", "xxxxxxxx",
""
};
// </rtc-template>
public RTObject_impl createRtc(Manager mgr) {
return new GAEConnectorImpl(mgr);
}
public void deleteRtc(RTObject_impl rtcBase) {
rtcBase = null;
}
public void registerModule() {
Properties prop = new Properties(component_conf);
final Manager manager = Manager.instance();
manager.registerFactory(prop, new GAEConnector(), new GAEConnector());
}
}
| Java |
package constants;
import client.Command;
public class Constants {
public static enum Color{
blue,
red,
green,
cyan,
magenta,
orange,
pink,
yellow
}
// Order of enum important for determining opposites
public static enum dir {
N, W, E, S
};
public static dir oppositeDir(dir d){
if(d== dir.N) return dir.S;
else if(d == dir.E) return dir.W;
else if(d == dir.W) return dir.E;
else return dir.N;
}
public static Command NOOP = new Command("NoOp");
}
| Java |
package client;
import java.util.LinkedList;
import constants.Constants.*;
public class Command {
static {
LinkedList< Command > cmds = new LinkedList< Command >();
for ( dir d : dir.values() ) {
cmds.add( new Command( d ) );
}
for ( dir d1 : dir.values() ) {
for ( dir d2 : dir.values() ) {
if ( !Command.isOpposite( d1, d2 ) ) {
cmds.add( new Command( "Push", d1, d2 ) );
}
}
}
for ( dir d1 : dir.values() ) {
for ( dir d2 : dir.values() ) {
if ( d1 != d2 ) {
cmds.add( new Command( "Pull", d1, d2 ) );
}
}
}
every = cmds.toArray( new Command[0] );
}
public final static Command[] every;
private static boolean isOpposite( dir d1, dir d2 ) {
return d1.ordinal() + d2.ordinal() == 3;
}
public String cmd;
public dir dir1;
public dir dir2;
public Command( dir d ) {
cmd = "Move";
dir1 = d;
}
public Command(String s) {
if (s.toLowerCase().equals("noop"))
cmd = "NoOp";
cmd = "NoOp"; // Are there others?
}
public Command( String s, dir d1, dir d2 ) {
cmd = s;
dir1 = d1;
dir2 = d2;
}
public String toString() {
if ( dir1 == null )
return cmd;
else if ( dir2 == null)
return cmd + "(" + dir1 + ")";
return cmd + "(" + dir1 + "," + dir2 + ")";
}
}
| Java |
package client;
public enum Action
{
MoveEast,
MoveWest,
MoveNorth,
MoveSouth,
PushNW,
PushW,
PushSW,
PushS,
PushSE,
PushE,
PushNE,
PushN,
PullNW,
PullW,
PullSW,
PullS,
PullSE,
PullE,
PullNE,
PullN,
NoOp
} | Java |
package client.planners;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Random;
import utils.FindFreeSpaces;
import utils.GoalPriority;
import constants.Constants;
import constants.Constants.dir;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
import client.Command;
import datastructures.AgentInState;
import datastructures.BoxInState;
import datastructures.State;
public class GoalCountPlanner implements Planner {
Level level;
Random rand;
HashMap<String, ArrayList<String>> closedSet;
private static final String name = "GoalCountPlanner";
@Override
public String getName() {
return name;
}
public GoalCountPlanner(Level l) {
this.level = l;
rand = new Random();
GoalPriority.createGoalPrioritization(level, true);
// FindFreeSpaces.FindSpaces(level);
}
public void makePlan() {
State firstState = new State();
closedSet = new HashMap<String, ArrayList<String>>();
{
ArrayList<String> newList = new ArrayList<String>();
String[] startIdentifier = getIdentifierStringForState(firstState);
newList.add(startIdentifier[1]);
closedSet.put(startIdentifier[0], newList);
}
for (Agent a : level.agents) {
firstState.agents.add(new AgentInState(a, a.getAtField()));
}
for (Box b : level.boxes) {
firstState.boxes.add(new BoxInState(b, b.getAtField()));
}
PriorityQueue<State> stateQueue = new PriorityQueue<State>();
stateQueue.add(firstState);
State currentState = stateQueue.poll();
while (currentState != null && !allBoxesAtGoals(currentState)) {
ArrayList<ArrayList<Command>> c = getCommandsForCurrentState(currentState);
ArrayList<State> newStatesFromCommands = getNewStatesFromCommands(
currentState, c);
for (State state : newStatesFromCommands) {
String[] identifierString = getIdentifierStringForState(state);
// System.err.println(identifierString[0] + "\t" + identifierString[1]);
if (closedSet.keySet().contains(identifierString[0])) {
if (closedSet.get(identifierString[0]).contains(
identifierString[1])) {
continue; // This means that we already have met this
// state. We continue to the next possible
// state.
} else {
closedSet.get(identifierString[0]).add(
identifierString[1]);
}
} else {
ArrayList<String> newList = new ArrayList<String>();
newList.add(identifierString[1]);
closedSet.put(identifierString[0], newList);
}
state.parent = currentState;
stateQueue.add(state);
}
currentState = stateQueue.poll();
}
System.err.println("Number of explored agent states: " + closedSet.size());
int counter = 0;
for (ArrayList<String> agentState : closedSet.values()) {
counter += agentState.size();
}
System.err.println("Number of combined states: " + counter);
ArrayList<ArrayList<Command>> commands = new ArrayList<ArrayList<Command>>();
if (currentState == null) {
System.err.println("Level cannot be solved!");
System.exit(0);
}
while (currentState != null) {
commands.add(currentState.commandFromParent);
currentState = currentState.parent;
}
Collections.reverse(commands);
for (ArrayList<Command> arrayList : commands) {
int agentIndex = 0;
for (int i = 0; i < arrayList.size(); i++) {
Command command = arrayList.get(i);
level.agents.get(agentIndex).commandQueue.add(command);
agentIndex++;
}
}
}
private ArrayList<ArrayList<Command>> getCommandsForCurrentState(
State currentState) {
ArrayList<ArrayList<Command>> returnCommands = new ArrayList<ArrayList<Command>>();
for (AgentInState a : currentState.agents) {
ArrayList<Command> cmds = addPossibleCommandsForAgent(a,
currentState);
returnCommands.add(cmds);
}
return returnCommands;
}
private ArrayList<State> getNewStatesFromCommands(State currentState,
ArrayList<ArrayList<Command>> c) {
ArrayList<State> returnStates = new ArrayList<State>();
// Code here
int index = 0;
for (ArrayList<Command> arrayList : c) {
for (Command command : arrayList) {
State newState = new State();
addCommandToState(command, currentState.agents.get(index),
newState, currentState);
newState.commandFromParent.add(command);
newState.heuristicValue = getHeuristicEstimate(newState);
for (int i = 0; i < c.size(); i++) {
if (i != index) {
for (Command commandOfOtherAgent : c.get(i)) {
addCommandToState(commandOfOtherAgent,
currentState.agents.get(i), newState,
currentState);
// BE SURE THAT ORDER CORRESPONDS TO AGENTS!
newState.commandFromParent.add(commandOfOtherAgent);
}
}
}
returnStates.add(newState);
}
index++;
}
return returnStates;
}
private int getHeuristicEstimate(State newState) {
int count = 0;
ArrayList<Box> usedBoxes = new ArrayList<Box>();
for (Goal g : level.goals) {
BoxInState bestBox = newState.boxes.get(0);
for (BoxInState b : newState.boxes) {
if (!usedBoxes.contains(b.b) && g.getId() == Character.toLowerCase(b.b.getId())
&& heuristicDistance(b.f, g) < heuristicDistance(bestBox.f, g)
){
bestBox = b;
usedBoxes.add(b.b);
}
}
if ( !(bestBox.f instanceof Goal && ((Goal) bestBox.f).getId() == Character.toLowerCase(bestBox.b.getId()))) {
count += heuristicDistance(bestBox.f, g);
//TODO Make this work with multi-agents
count += heuristicDistance(newState.agents.get(0).f, bestBox.f);
}
}
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// count -= (noOfGoalsFulfilled(newState) * 5);
// System.err.println(Arrays.toString(getIdentifierStringForState(newState)));
// System.err.println(count);
return count;
}
private int heuristicDistance(Field a, Field goal) {
return heuristicDistanceManhattan(a, goal);
}
private int heuristicDistanceEuclid(Field a, Field goal) {
int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2)
+ Math.pow(Math.abs(a.y - goal.y), 2));
return h;
}
// Manhattan distance
private int heuristicDistanceManhattan(Field a, Field goal) {
int h = (int) Math.abs(a.x - goal.x) + Math.abs(a.y - goal.y);
return h;
}
private void addCommandToState(Command command, AgentInState aPos,
State newState, State currentState) {
for (BoxInState bPos : currentState.boxes) {
newState.boxes.add(new BoxInState(bPos.b, bPos.f));
}
if (command.cmd.equals("Move")) {
newState.agents.add(new AgentInState(aPos.a,
aPos.f.neighbours[command.dir1.ordinal()]));
} else if (command.cmd.equals("Pull")) {
for (BoxInState bPos : newState.boxes) {
if (aPos.f.neighbours[command.dir2.ordinal()] == bPos.f) {
bPos.f = aPos.f;
newState.agents.add(new AgentInState(aPos.a,
aPos.f.neighbours[command.dir1.ordinal()]));
}
}
} else if (command.cmd.equals("Push")) {
for (BoxInState bPos : newState.boxes) {
if (aPos.f.neighbours[command.dir1.ordinal()] == bPos.f) {
// newState.boxes.add(new BoxPosInState(bPos.b,
// bPos.f.neighbours[command.dir2.ordinal()]));
newState.agents.add(new AgentInState(aPos.a, bPos.f));
bPos.f = bPos.f.neighbours[command.dir2.ordinal()];
}
}
}
}
public ArrayList<Command> addPossibleCommandsForAgent(AgentInState aPos,
State currentState) {
ArrayList<Command> possibleCommands = new ArrayList<Command>();
Field agentLocationInPlan = aPos.f;
// Commented because we are not interested in move commands at current
// time.
for (dir direction : dir.values()) {
if (neighbourFreeInState(
agentLocationInPlan.neighbours[direction.ordinal()],
currentState)) {
possibleCommands.add(new Command(direction));
}
// Find possible pull and push commands
for (dir d : dir.values()) {
// we cannot pull a box forward in the box's direction
if (d != direction
&& neighbourIsBoxOfSameColourInState(
agentLocationInPlan.neighbours[d.ordinal()],
currentState, aPos)
&& neighbourFreeInState(
agentLocationInPlan.neighbours[direction
.ordinal()],
currentState)) {
possibleCommands.add(new Command("Pull", direction, d));
}
// We cannot push a box backwards in the agents direction
if (d != Constants.oppositeDir(direction)
&& neighbourIsBoxOfSameColourInState(
agentLocationInPlan.neighbours[d.ordinal()],
currentState, aPos)
&& neighbourFreeInState(
agentLocationInPlan.neighbours[d.ordinal()].neighbours[direction
.ordinal()], currentState)) {
possibleCommands.add(new Command("Push", d, direction));
}
}
}
return possibleCommands;
}
private boolean allBoxesAtGoals(State currentState) {
boolean[] boxAtGoalArray = new boolean[level.goals.size()];
int index = 0;
for (Goal g : level.goals) {
for (BoxInState bPos : currentState.boxes) {
if (bPos.f == g
&& Character.toLowerCase(bPos.b.getId()) == g.getId()) {
boxAtGoalArray[index] = true;
}
}
index++;
}
boolean returnBool = true;
for (boolean b : boxAtGoalArray) {
if (!b)
return false;
}
return returnBool;
}
private int noOfGoalsFulfilled(State currentState){
boolean[] boxAtGoalArray = new boolean[level.goals.size()];
int index = 0;
for (Goal g : level.goals) {
for (BoxInState bPos : currentState.boxes) {
if (bPos.f == g
&& Character.toLowerCase(bPos.b.getId()) == g.getId()) {
boxAtGoalArray[index] = true;
}
}
index++;
}
int counter = 0;
for (boolean b : boxAtGoalArray) {
if (b) counter++;
}
return counter;
}
private boolean neighbourFreeInState(Field f, State s) {
if (f == null)
return false;
boolean fieldFree = true;
for (AgentInState aPos : s.agents) {
if (aPos.f == f)
fieldFree = false;
}
for (BoxInState bPos : s.boxes) {
if (bPos.f == f)
fieldFree = false;
}
return fieldFree;
}
private boolean neighbourIsBoxOfSameColourInState(Field f, State s,
AgentInState a) {
if (f == null)
return false;
for (BoxInState bPos : s.boxes) {
if (bPos.f == f && bPos.b.getColor() == a.a.getColor()) {
return true;
}
}
return false;
}
private String[] getIdentifierStringForState(State s) {
String[] returnString = new String[2];
AgentInState[] agentArray = new AgentInState[s.agents.size()];
for (int i = 0; i < s.agents.size(); i++) {
agentArray[i] = s.agents.get(i);
}
Arrays.sort(agentArray);
String agentString = "";
for (AgentInState aPos : s.agents) {
agentString += aPos.f.x + "." + aPos.f.y + aPos.a.getColor();
}
BoxInState[] boxArray = new BoxInState[s.boxes.size()];
for (int i = 0; i < s.boxes.size(); i++) {
boxArray[i] = s.boxes.get(i);
}
Arrays.sort(boxArray);
String boxString = "";
for (BoxInState box : boxArray) {
boxString += box.f.x + "."+ box.f.y + box.b.getId();
}
returnString[0] = agentString;
returnString[1] = boxString;
return returnString;
}
}
| Java |
package client.planners;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;
import constants.Constants.dir;
import utils.Utils;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
import client.Command;
import client.Desire;
import datastructures.ActionSequence;
import datastructures.AgentInState;
import datastructures.BoxInState;
import datastructures.GoalActionSequence;
import datastructures.MoveActionSequence;
import datastructures.State;
public class ProgressionWithHeuristic implements Planner {
Level level;
Random rand;
private static final String name = "ProgressionPlannerWithHeurustic";
@Override
public String getName() {
return name;
}
public ProgressionWithHeuristic(Level l) {
this.level = l;
rand = new Random();
}
public void makePlan() {
System.err.println("Make plan!");
State firstState = Utils.getState(level.agents, level.boxes);
PriorityQueue<State> stateQueue = new PriorityQueue<State>();
HashMap<ArrayList<Field>, ArrayList<ArrayList<Field>>> closedSet = new HashMap<ArrayList<Field>, ArrayList<ArrayList<Field>>>();
stateQueue.add(firstState);
ArrayList<Field> agentPositions = new ArrayList<Field>();
for (AgentInState a : firstState.agents) {
agentPositions.add(a.f);
}
ArrayList<Field> boxPositions = new ArrayList<Field>();
for (BoxInState b : firstState.boxes) {
boxPositions.add(b.f);
}
closedSet.put(agentPositions, new ArrayList<ArrayList<Field>>());
closedSet.get(agentPositions).add(boxPositions);
State currentState = stateQueue.poll();
while (currentState != null && !Utils.allGoalsHasBoxes(currentState,level)) {
//Start by finding the possible actions.
ArrayList<State> newStates = findPossibleActions(currentState);
for (State state : newStates) {
ArrayList<Field> tempAgentPositions = new ArrayList<Field>();
for (AgentInState a : state.agents) tempAgentPositions.add(a.f);
ArrayList<Field> tempBoxPositions = new ArrayList<Field>();
for (BoxInState b : state.boxes) tempBoxPositions.add(b.f);
//Pruning of states.
if (closedSet.containsKey(tempAgentPositions)) {
if (closedSet.get(tempAgentPositions).contains(tempBoxPositions)) {
continue;
}
else{
closedSet.get(tempAgentPositions).add(tempBoxPositions);
}
}
else{
closedSet.put(tempAgentPositions, new ArrayList<ArrayList<Field>>());
closedSet.get(tempAgentPositions).add(tempBoxPositions);
}
stateQueue.add(state);
}
currentState = stateQueue.poll();
}
if (currentState == null) return;
ArrayList<State> states = new ArrayList<State>();
while (currentState != null) {
states.add(states.size(), currentState);
currentState = currentState.parent;
}
Collections.reverse(states);
for (State state : states) {
for (ActionSequence actionSequence : state.actionSequencesFromParent) {
for (Command command : actionSequence.getCommands()) {
System.err.println(command.toString());
level.agents.get(0).commandQueue.add(command); //Should be changed to work with multi-agents
}
}
}
}
private ArrayList<State> findPossibleActions(State currentState){
ArrayList<State> returnStates = new ArrayList<State>();
for (AgentInState a : currentState.agents) {
for (BoxInState b : currentState.boxes) {
//Continue if the agent does not match the box or the box is at it's goal
if (b.b.getColor() != a.a.getColor() ||
(b.f instanceof Goal && Character.toLowerCase(b.b.getId()) == ((Goal) b.f).getId() )) continue;
ArrayList<Field> blockedFields = new ArrayList<Field>();
for (AgentInState agent : currentState.agents) {
if(agent != a) blockedFields.add(agent.f);
}
for (BoxInState box : currentState.boxes) {
blockedFields.add(box.f);
}
for (dir d : dir.values()) {
if(b.f.neighbours[d.ordinal()] != null){
//The following line will not find a path to adjacent boxes.
MoveActionSequence moveAction = Utils.findRoute(level, a.f, b.f.neighbours[d.ordinal()], blockedFields);
if (moveAction != null) {
//Here we have decided that we can get to a box. Now we must check if the box can get to a goal.
//Because we are now moving the box, it's field is free.
blockedFields.remove(b.f);
for (Goal goal : level.goals) {
if(Utils.boxFitsGoal(b.b, goal)){
for (dir goalNeighbourDir : dir.values()) {
Field goalNeighbour = goal.neighbours[goalNeighbourDir.ordinal()];
if (goalNeighbour != null) {
GoalActionSequence routeToGoal = Utils.findGoalRoute(level, a.a, b.b, b.f.neighbours[d.ordinal()], goalNeighbour, b.f, goal, blockedFields);
if (routeToGoal != null) {
//If we get here, we have found a route to the goal.
State newState = new State();
newState.actionSequencesFromParent.add(moveAction);
newState.actionSequencesFromParent.add(routeToGoal);
newState.parent = currentState;
for (AgentInState agent : currentState.agents) {
if(agent != a) newState.agents.add(agent);
else newState.agents.add(new AgentInState(agent.a, goalNeighbour));
}
for (BoxInState box : currentState.boxes) {
if(box != b) newState.boxes.add(box);
else newState.boxes.add(new BoxInState(box.b, goal));
}
returnStates.add(newState);
}
}
}
}
}
blockedFields.add(b.f);
}
}
}
}
}
return returnStates;
}
}
| Java |
package client.planners;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Random;
import utils.Utils;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
import client.Command;
import datastructures.ActionSequence;
import datastructures.AgentInState;
import datastructures.BoxInState;
import datastructures.GoalActionSequence;
import datastructures.MoveActionSequence;
import datastructures.State;
public class PrioritizedGoalPlanner implements Planner {
Level level;
Random rand;
PriorityQueue<State> stateQueue;
HashMap<String, ArrayList<String>> closedSet;
boolean clearedBox = false;
boolean goalPriosSet = false;
private static final String name = "AStarPlanner";
@Override
public String getName() {
return name;
}
public PrioritizedGoalPlanner(Level l) {
this.level = l;
rand = new Random();
}
public void makePlan() {
System.err.println("make plan");
long timestamp1 = System.currentTimeMillis();
// Hardcode the goal priorities.
int t = 10;
if (!goalPriosSet) {
for (Goal g : level.goals)
g.priority = t--;
}
goalPriosSet = true;
// Sort the goals such that we iterate best goals first.
Collections.sort(level.goals);
stateQueue = new PriorityQueue<State>();
closedSet = new HashMap<String, ArrayList<String>>();
// Find eligible boxes to first goal
//int nextGoalindex
for (Goal g : level.goals) {
for (Box b : Utils.getBoxesInLevel(level.boxes, g.getId())) {
for (Agent a : Utils.getAgents(level.agents, b.getColor())) {
ArrayList<State> firstStates = Utils.getStateFromLevel(
level.agents, level.boxes, b.getAtField());
for (State state : firstStates) {
state.heuristicValue = level.goals.size() * 2;
state.goal.agent = new AgentInState(a, a.getAtField());
state.goal.box = new BoxInState(b, b.getAtField());
state.goal.boxToPos = g;
state.goal.nextGoalIndex = 1;
state.goal.isMoveToBoxGoal = true;
stateQueue.add(state);
}
}
}
}
State currentState = stateQueue.poll();
ArrayList<Field> agentPositions = new ArrayList<Field>();
for (AgentInState a : currentState.agents) {
agentPositions.add(a.f);
}
String boxPositions = "";
for (BoxInState b : currentState.boxes) {
boxPositions += b.f.toString() + b.b.getId();
}
closedSet.put(agentPositions.toString(), new ArrayList<String>());
closedSet.get(agentPositions.toString()).add(boxPositions);
// Start the search
while (currentState != null
&& !Utils.allGoalsHasBoxes(currentState, level)) {
// The goal of the state is to get to a box.
if (currentState.goal.isMoveToBoxGoal) {
// System.err.println("Move: " +currentState.goal.nextGoalIndex+ " Try move agent to " + currentState.goal.agentToPos);
AgentInState agent = currentState.goal.agent;
BoxInState box = currentState.goal.box;
ArrayList<Field> blockedFields = getBlockedField(currentState,
agent);
MoveActionSequence routeToGoal = Utils.findRoute(level,
agent.f, currentState.goal.agentToPos, blockedFields);
if (routeToGoal == null) {
clearPath(agent, currentState);
currentState = stateQueue.poll();
continue;
}
// System.err.println("Completed move " + currentState.goal.nextGoalIndex);
// System.err.println("Move agent successfully to " + currentState.goal.agentToPos);
completedMoveToBox(currentState, agent, box, routeToGoal, currentState.goal.boxToPos, currentState.goal.isClearPathGoal);
} else {
AgentInState agent = currentState.goal.agent;
BoxInState box = currentState.goal.box;
ArrayList<Field> blockedFields = getBlockedField(currentState,
agent, box);
// The stateGoal has a box and an agent. As well as the positions they should move to.
GoalActionSequence routeToGoal = Utils.findGoalRoute(level,
currentState.goal.agent.a, currentState.goal.box.b,
currentState.goal.agent.f,
currentState.goal.agentToPos, currentState.goal.box.f,
currentState.goal.boxToPos, blockedFields);
if (routeToGoal == null) {
// Try to clear a path
currentState = stateQueue.poll();
continue;
}
int nextGoalIndex = currentState.goal.nextGoalIndex;
if (!currentState.goal.isClearPathGoal) {
System.err.println("Goal: " +currentState.goal.nextGoalIndex+ " Push agent to " + currentState.goal.agentToPos + " and box "+ currentState.goal.box.b.getId() +" to " + currentState.goal.boxToPos);
if (nextGoalIndex >= level.goals.size()) {
System.err.println("Goal count exceeded");
State goalState = new State();
goalState.actionSequencesFromParent.add(routeToGoal);
goalState.parent = currentState;
currentState = goalState;
break;
}
}
else{
// System.err.println("Completed push " + currentState.goal.nextGoalIndex);
}
completeGoal(nextGoalIndex, currentState,
routeToGoal);
}
currentState = stateQueue.poll();
}
// System.err.println(currentState.parent.agents.get(0).f.toString());
// for (BoxInState b : currentState.parent.boxes) {
// System.err.println(b.f.toString());
// }
long timestamp2 = System.currentTimeMillis();
System.err.println("Done in " + (timestamp2-timestamp1)/1000.0 + " seconds");
System.err.println("States left: " + stateQueue.size());
System.err.println("Cleared box " + clearedBox);
ArrayList<Command> commands = new ArrayList<Command>();
int counter = 0;
while (currentState != null) {
counter++;
for (ActionSequence as : currentState.actionSequencesFromParent) {
Collections.reverse(as.getCommands());
for (Command c : as.getCommands()) {
commands.add(c);
}
}
currentState = currentState.parent;
}
System.err.println("Sequences " + counter);
Collections.reverse(commands);
for (Command command : commands) {
level.agents.get(0).commandQueue.add(command);
}
}
private void completeGoal(int nextGoalIndex,
State currentState,
GoalActionSequence routeToGoal) {
int index;
if (currentState.goal.isClearPathGoal) {
index = nextGoalIndex-1;
}
else {
index= nextGoalIndex;
}
// We have found a route to the goal. Find next states to check.
for (Box b : Utils.getBoxesInLevel(level.boxes,
level.goals.get(index).getId())) {
BoxInState boxInState = findBoxInCompletedState(currentState, b);
if (boxInState.f instanceof Goal && Utils.boxFitsGoal(boxInState.b, (Goal) boxInState.f))
continue;
for (Agent a : Utils.getAgents(level.agents, b.getColor())) {
ArrayList<State> newStates = Utils.getState(
currentState.agents, currentState.boxes,
currentState.goal.box.b, currentState.goal.boxToPos, a,
currentState.goal.agentToPos, boxInState.f);
for (State newState : newStates) {
newState.goal.box = boxInState;
newState.goal.boxToPos = level.goals.get(index);
newState.goal.isClearPathGoal = false;//currentState.goal.isClearPathGoal;
if (!addState(newState))
continue;
newState.actionSequencesFromParent.add(routeToGoal);
newState.parent = currentState;
if (currentState.goal.isClearPathGoal){
newState.heuristicValue = newState.parent.heuristicValue+1;
newState.goal.nextGoalIndex = nextGoalIndex;
}
else{
newState.goal.nextGoalIndex = nextGoalIndex+1;
newState.heuristicValue = newState.parent.heuristicValue-2;
}
newState.goal.agent = new AgentInState(a,
currentState.goal.agentToPos);
newState.goal.isMoveToBoxGoal = true;
stateQueue.add(newState);
}
}
}
}
private void completedMoveToBox(
State currentState, AgentInState agent,
BoxInState boxInState, MoveActionSequence routeToGoal, Field boxToPos, boolean isClearPath) {
ArrayList<State> newStates = Utils.getState(currentState.agents,
currentState.boxes, agent.a, routeToGoal.getEndField(),
boxToPos);
for (State newState : newStates) {
newState.goal.box = boxInState;
newState.goal.boxToPos = boxToPos;
newState.goal.isClearPathGoal = isClearPath;
if (!addState(newState))
continue;
newState.goal.nextGoalIndex = currentState.goal.nextGoalIndex;
newState.actionSequencesFromParent.add(routeToGoal);
newState.parent = currentState;
if (isClearPath) {
newState.heuristicValue = newState.parent.heuristicValue + 1;
}
else{
newState.heuristicValue = newState.parent.heuristicValue - 1;
}
newState.goal.agent = new AgentInState(agent.a, routeToGoal.getEndField());
newState.goal.isMoveToBoxGoal = false;
stateQueue.add(newState);
}
}
private BoxInState findBoxInCompletedState(State currentState, Box box) {
BoxInState boxInState = currentState.goal.box;
for (BoxInState b : currentState.boxes) {
if(b.b == boxInState.b && box == b.b){
return new BoxInState(box, currentState.goal.boxToPos);
}
else if (b.b == box) {
return b;
}
}
return null;
}
private boolean addState(State newState) {
ArrayList<Field> tempAgentPositions = new ArrayList<Field>();
// for (AgentInState a : newState.agents) tempAgentPositions.add(a.f);
tempAgentPositions.add(newState.goal.agentToPos);
String key = newState.goal.isClearPathGoal + " " + tempAgentPositions.toString();
String tempBoxPositions = "";
// ArrayList<Field> tempBoxPositions = new ArrayList<Field>();
for (BoxInState b : newState.boxes) {
if (newState.goal.box == null || newState.goal.box.b != b.b) {
tempBoxPositions += b.f.toString() + b.b.getId();
} else {
// System.err.println("This one " + newState.goal.boxToPos.toString());
tempBoxPositions += newState.goal.boxToPos.toString() + b.b.getId();
}
}
if (closedSet.containsKey(key)) {
if (closedSet.get(key).contains(tempBoxPositions)) {
return false;
} else {
closedSet.get(key).add(tempBoxPositions);
}
} else {
closedSet.put(key, new ArrayList<String>());
closedSet.get(key).add(tempBoxPositions);
}
// System.err.println("Adding state " + key + " " + tempBoxPositions.toString());
return true;
}
private ArrayList<Field> getBlockedField(State currentState,
AgentInState agent) {
ArrayList<Field> blockedFields = new ArrayList<Field>();
for (AgentInState a : currentState.agents) {
if (agent.f != a.f)
blockedFields.add(a.f);
}
for (BoxInState box : currentState.boxes) {
blockedFields.add(box.f);
}
return blockedFields;
}
private ArrayList<Field> getBlockedField(State currentState,
AgentInState agent, BoxInState box) {
ArrayList<Field> blockedFields = new ArrayList<Field>();
for (AgentInState a : currentState.agents) {
if (agent.f != a.f)
blockedFields.add(a.f);
}
for (BoxInState b : currentState.boxes) {
if (box.f != b.f)
blockedFields.add(b.f);
}
return blockedFields;
}
private void clearPath(AgentInState agent, State currentState) {
MoveActionSequence requiredClear = Utils.findRoute(level, agent.f, currentState.goal.agentToPos);
int index = 0;
for (Field firstBoxAtField : requiredClear.fields) {
BoxInState boxInState = Utils.getBoxAtField(currentState, firstBoxAtField);
if (Utils.isFieldClear(currentState, firstBoxAtField) && boxInState == null) {
index++;
continue;
}
Field agentToField;
if (index == 0) agentToField = agent.f;
else agentToField = requiredClear.fields.get(index - 1);
ArrayList<Field> blockedFields = getBlockedField(currentState,
agent, boxInState);
MoveActionSequence routeToGoal = Utils.findRoute(level,
agent.f, agentToField, blockedFields);
if (routeToGoal == null) {
return;
}
for (Field freeField : Utils
.findFreeField(level, blockedFields)) {
completedMoveToBox(currentState, agent, boxInState, routeToGoal, freeField, true);
}
break;
}
}
}
| Java |
package client.planners;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import agent.objectives.DockABox;
import agent.objectives.GoalABox;
import agent.objectives.Objective;
import agent.planners.AgentPlanner;
import agent.planners.AgentProgressionPlanner;
import utils.GoalPriority;
import utils.Utils;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
import client.Command;
import constants.Constants.Color;
import constants.Constants.dir;
import datastructures.ActionSequence;
import datastructures.AgentInState;
import datastructures.BoxInState;
import datastructures.GoalActionSequence;
import datastructures.MoveActionSequence;
import datastructures.State;
public class ClientPlanner implements Planner {
Level level;
Random rand;
public boolean firstRun = true;
private static final String name = "ClientPlanner";
@Override
public String getName() {
return name;
}
public ClientPlanner(Level l) {
this.level = l;
rand = new Random();
}
public void makePlan() {
// System.err.println("Make plan!");
AgentPlanner planner = new AgentProgressionPlanner(level);
int agentsNeedsPlans = 0;
for (Agent agent : level.agents) {
if(agent.objectives.isEmpty())
agentsNeedsPlans++;
}
if(agentsNeedsPlans == level.agents.size() && !Utils.allGoalsHasBoxes(level))
firstRun = true;
if (firstRun)
{
GoalPriority.createGoalPrioritization(level, true);
for (Agent a : level.agents)
{
a.priority = 99;
a.planner = planner;
a.possibleBoxesToGoals = Utils.findPossibleBoxes(level, a);
}
// Find goals in order and find an agent to goal it
for (Goal g : level.goals)
{
for (Agent a : level.agents)
{
for (Box b : a.possibleBoxesToGoals.keySet())
{
Goal goal = null;
if (a.possibleBoxesToGoals.containsKey(b) && Utils.boxFitsGoal(b, g)){
//add goal with lowest priority
goal = GoalPriority.FindGoalWithHighestPriority(a, b, level);
if(a.objectives == null)
a.objectives.addFirst(new GoalABox(b, goal));
else{
Objective o = a.objectives.peek();
if(o instanceof GoalABox && ((GoalABox) o).goal.getPriority() > goal.getPriority()){
a.objectives.addFirst(new GoalABox(b, goal));
}
else{
a.objectives.addLast(new GoalABox(b, goal));
}
}
if(a.priority > goal.priority)
a.priority = goal.priority;
}
}
}
}
firstRun = false;
}
for (Agent a : level.agents)
{
if(a.objectives.isEmpty()){
Goal goal_highest_priority = Utils.allOfAgentGoalsHasBoxes(a, level);
if(goal_highest_priority != null){
//Find route to goal
Collection<Field> blockedFields = null;
ArrayList<Box> boxesInTheWay = null;
boxesInTheWay = Utils.findRouteCountBoxesInTheWay(level, a, a.getAtField(), new Field(goal_highest_priority.x, goal_highest_priority.y), blockedFields);
//remove boxes in the way
boxesInTheWayLoop : for (Box box : boxesInTheWay) {
if(box.getId() == a.getId()){
//make DockABox thing
Objective o = new DockABox(box.getAtField(), box, 15);
a.objectives.addFirst(o);
break boxesInTheWayLoop;
}
}
}
}
a.planAndExecute(level);
}
}
}
| Java |
package client.planners;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Random;
import utils.FOMAUtils;
import utils.PrioriGoalUtils;
import utils.Utils;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
import client.Command;
import datastructures.ActionSequence;
import datastructures.AgentInState;
import datastructures.BoxInState;
import datastructures.FieldBlockedChange;
import datastructures.FieldInState;
import datastructures.GoalActionSequence;
import datastructures.MoveActionSequence;
import datastructures.State;
public class FOMAPrioritizedGoalPlanner implements Planner {
Level level;
Random rand;
PriorityQueue<State> stateQueue;
HashMap<String, ArrayList<String>> closedSet;
boolean clearedBox = false;
boolean goalPriosSet = false;
private static final String name = "AStarPlanner";
@Override
public String getName() {
return name;
}
public FOMAPrioritizedGoalPlanner(Level l) {
this.level = l;
rand = new Random();
}
public void makePlan() {
System.err.println("make plan");
long timestamp1 = System.currentTimeMillis();
// Hardcode the goal priorities.
int t = 20;
if (!goalPriosSet) {
for (Goal g : level.goals)
g.priority = t--;
}
goalPriosSet = true;
// Sort the goals such that we iterate best goals first.
Collections.sort(level.goals);
ArrayList<ArrayList<Command>> agentCommands = new ArrayList<ArrayList<Command>>();
for (Agent a : level.agents) {
State currentState = planForAgent(a,agentCommands);
ArrayList<Command> commands = new ArrayList<Command>();
while (currentState != null) {
for (ActionSequence as : currentState.actionSequencesFromParent) {
Collections.reverse(as.getCommands());
for (Command c : as.getCommands()) {
commands.add(c);
}
}
currentState = currentState.parent;
}
Collections.reverse(commands);
agentCommands.add(commands);
for (Command command : commands) {
a.commandQueue.add(command);
}
}
long timestamp2 = System.currentTimeMillis();
System.err.println("Plans made in " + (timestamp2 - timestamp1) / 1000.0 + " seconds");
}
private State planForAgent(Agent currentAgent, ArrayList<ArrayList<Command>> agentCommands){
Object[] setup = setupPlan(currentAgent);
State currentState = (State) setup[0];
ArrayList<Goal> agentGoals = (ArrayList<Goal>) setup[1];
FOMAUtils.mergeState(level,currentState, agentCommands);
System.err.println("NEW STATE");
while (currentState != null && !Utils.allGoalsAtHasBoxes(currentState, level, agentGoals)) {
// The goal of the state is to get to a box.
// System.err.println(stateQueue.size());
// System.err.println("New state");
currentState.printFieldChanges();
if (currentState.goal.isMoveToBoxGoal) {
AgentInState agent = currentState.goal.agent;
BoxInState box = currentState.goal.box;
ArrayList<FieldInState> blockedFields = PrioriGoalUtils.getBlockedFields(currentState);
MoveActionSequence routeToGoal = FOMAUtils.findRoute(level, agent.f, currentState.goal.agentToPos, blockedFields, currentState.indexOfCommands);
if (routeToGoal == null) {
clearPath(agent, currentState);
currentState = stateQueue.poll();
continue;
}
// System.err.println("Found route to " + routeToGoal.getEndField());
completedMoveToBox(currentState, agent, box, routeToGoal,
currentState.goal.boxToPos,
currentState.goal.isClearPathGoal);
} else {
AgentInState agent = currentState.goal.agent;
BoxInState box = currentState.goal.box;
ArrayList<FieldInState> blockedFields = PrioriGoalUtils.getBlockedFields(currentState);
// The stateGoal has a box and an agent. As well as the positions they should move to.
GoalActionSequence routeToGoal = FOMAUtils.findGoalRoute(level, currentState, blockedFields);
if (routeToGoal == null) {
// Try to clear a path
System.err.println("No route to goal");
currentState = stateQueue.poll();
continue;
}
// System.err.println("Route to goal " + currentState.goal.isClearPathGoal + " " + currentState.goal.nextGoalIndex + " " + agentGoals.size());
int nextGoalIndex = currentState.goal.nextGoalIndex;
if (!currentState.goal.isClearPathGoal && nextGoalIndex >= agentGoals.size()) {
System.err.println("Goal count exceeded");
State goalState = new State();
goalState.actionSequencesFromParent.add(routeToGoal);
goalState.parent = currentState;
currentState = goalState;
break;
}
completeGoal(nextGoalIndex, currentState, routeToGoal, agentGoals);
}
currentState = stateQueue.poll();
}
if(currentState == null)
System.err.println("State space explored");
return currentState;
}
private void completeGoal(int nextGoalIndex, State currentState,
GoalActionSequence routeToGoal, ArrayList<Goal> goals) {
int index;
if (currentState.goal.isClearPathGoal) {
index = nextGoalIndex - 1;
} else {
index = nextGoalIndex;
}
// We have found a route to the goal. Find next states to check.
for (Box b : Utils.getBoxesInLevel(level.boxes, goals.get(index)
.getId())) {
BoxInState boxInState = Utils.findBoxInCompletedState(currentState, b);
if (boxInState.f instanceof Goal
&& Utils.boxFitsGoal(boxInState.b, (Goal) boxInState.f))
continue;
for (Agent a : Utils.getAgents(level.agents, b.getColor())) {
ArrayList<State> newStates = FOMAUtils.getStateFromCompletedGoal(currentState, a, boxInState.f, routeToGoal);
for (State newState : newStates) {
newState.goal.box = boxInState;
newState.goal.boxToPos = goals.get(index);
newState.goal.isClearPathGoal = false;// currentState.goal.isClearPathGoal;
if (!addState(newState))
continue;
newState.actionSequencesFromParent.add(routeToGoal);
newState.parent = currentState;
if (currentState.goal.isClearPathGoal) {
newState.heuristicValue = newState.parent.heuristicValue + 1;
newState.goal.nextGoalIndex = nextGoalIndex;
} else {
newState.goal.nextGoalIndex = nextGoalIndex + 1;
newState.heuristicValue = newState.parent.heuristicValue - 2;
}
newState.goal.agent = new AgentInState(a,
currentState.goal.agentToPos);
newState.goal.isMoveToBoxGoal = true;
stateQueue.add(newState);
}
}
}
}
private void completedMoveToBox(State currentState, AgentInState agent,
BoxInState boxInState, MoveActionSequence routeToGoal,
Field boxToPos, boolean isClearPath) {
ArrayList<State> newStates = FOMAUtils.getStateFromCompletedMove(currentState, agent.a, routeToGoal, boxToPos);
for (State newState : newStates) {
newState.goal.box = boxInState;
newState.goal.boxToPos = boxToPos;
newState.goal.isClearPathGoal = isClearPath;
newState.indexOfCommands = currentState.indexOfCommands + routeToGoal.getCommands().size();
if (!addState(newState))
continue;
newState.goal.nextGoalIndex = currentState.goal.nextGoalIndex;
newState.actionSequencesFromParent.add(routeToGoal);
newState.parent = currentState;
if (isClearPath) {
newState.heuristicValue = newState.parent.heuristicValue + 1;
} else {
newState.heuristicValue = newState.parent.heuristicValue - 1;
}
newState.goal.agent = new AgentInState(agent.a,
routeToGoal.getEndField());
newState.goal.isMoveToBoxGoal = false;
stateQueue.add(newState);
}
}
private boolean addState(State newState) {
ArrayList<Field> tempAgentPositions = new ArrayList<Field>();
// for (AgentInState a : newState.agents) tempAgentPositions.add(a.f);
tempAgentPositions.add(newState.goal.agentToPos);
String key = newState.goal.isClearPathGoal + " "
+ tempAgentPositions.toString();
String tempBoxPositions = "";
// ArrayList<Field> tempBoxPositions = new ArrayList<Field>();
for (BoxInState b : newState.boxes) {
if (newState.goal.box == null || newState.goal.box.b != b.b) {
tempBoxPositions += b.f.toString() + b.b.getId();
} else {
// System.err.println("This one " +
// newState.goal.boxToPos.toString());
tempBoxPositions += newState.goal.boxToPos.toString()
+ b.b.getId();
}
}
if (closedSet.containsKey(key)) {
if (closedSet.get(key).contains(tempBoxPositions)) {
return false;
} else {
closedSet.get(key).add(tempBoxPositions);
}
} else {
closedSet.put(key, new ArrayList<String>());
closedSet.get(key).add(tempBoxPositions);
}
// System.err.println("Adding state " + key + " " +
// tempBoxPositions.toString());
return true;
}
private void clearPath(AgentInState agent, State currentState) {
MoveActionSequence requiredClear = Utils.findRoute(level, agent.f,
currentState.goal.agentToPos);
if (requiredClear == null) {
return;
}
int index = 0;
for (Field firstBoxAtField : requiredClear.fields) {
BoxInState boxInState = Utils.getBoxAtField(currentState,
firstBoxAtField);
if (Utils.isFieldClear(currentState, firstBoxAtField)
&& boxInState == null) {
index++;
continue;
}
Field agentToField;
if (index == 0)
agentToField = agent.f;
else
agentToField = requiredClear.fields.get(index - 1);
ArrayList<Field> blockedFields = PrioriGoalUtils.getBlockedFields(currentState,
agent, boxInState);
MoveActionSequence routeToGoal = Utils.findRoute(level, agent.f,
agentToField, blockedFields);
if (routeToGoal == null) {
return;
}
for (Field freeField : Utils.findFreeField(level, blockedFields)) {
completedMoveToBox(currentState, agent, boxInState,
routeToGoal, freeField, true);
}
break;
}
}
private Object[] setupPlan(Agent currentAgent) {
Object[] stateAndGoals = new Object[2];
stateQueue = new PriorityQueue<State>();
ArrayList<Goal> returnGoals = new ArrayList<Goal>();
int nextGoalIndex = 1;
boolean firstStateSet = false;
for(Goal g : level.goals){
for (Box b : Utils.getBoxesWithId(level.boxes, g.getId())) {
if (b.getColor() != currentAgent.getColor()) continue;
if (!firstStateSet) {
ArrayList<State> firstStates = FOMAUtils.getStateFromLevel(
level.agents, level.boxes, level.fields, b.getAtField());
for (State state : firstStates) {
state.heuristicValue = level.goals.size() * 2;
state.goal.agent = new AgentInState(currentAgent, currentAgent.getAtField());
state.goal.box = new BoxInState(b, b.getAtField());
state.goal.boxToPos = g;
state.goal.nextGoalIndex = nextGoalIndex;
state.indexOfCommands = 0;
state.goal.isMoveToBoxGoal = true;
stateQueue.add(state);
}
firstStateSet = true;
}
if (!returnGoals.contains(g)) {
returnGoals.add(g);
nextGoalIndex++;
}
}
}
State currentState = stateQueue.poll();
ArrayList<Field> agentPositions = new ArrayList<Field>();
for (AgentInState a : currentState.agents) {
agentPositions.add(a.f);
}
String boxPositions = "";
for (BoxInState b : currentState.boxes) {
boxPositions += b.f.toString() + b.b.getId();
}
closedSet = new HashMap<String, ArrayList<String>>();
closedSet.put(agentPositions.toString(), new ArrayList<String>());
closedSet.get(agentPositions.toString()).add(boxPositions);
stateAndGoals[0] = currentState;
stateAndGoals[1] = returnGoals;
return stateAndGoals;
}
//Here we want to resolve any conflicts
private void validatePlan(ArrayList<ArrayList<ActionSequence>> agentSequences) {
}
}
| Java |
package client.planners;
public interface Planner {
public String getName();
public void makePlan();
}
| Java |
package client.planners;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Set;
import utils.AStarField;
import constants.Constants.dir;
import client.Command;
import client.Desire;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
public class SimplePlanner implements Planner {
Level level;
Random rand;
private static final String name = "SimplePlanner";
@Override
public String getName() {
return name;
}
public SimplePlanner(Level l) {
this.level = l;
rand = new Random();
}
public void makePlan() {
ArrayList<Desire> desires = findDesires();
findIntentions(desires);
decideCommands();
}
private ArrayList<Desire> findDesires() {
ArrayList<Desire> returnDesires = new ArrayList<Desire>();
for (Agent a : level.agents) {
if (!getToBoxDesireCompleted(a)) {
for (Box b : level.boxes) {
//System.err.println("adding box goal with " + b.getId());
if (a.getColor() == b.getColor()
&& !(b.getAtField() instanceof Goal && ((Goal) b
.getAtField()).getId() == b.getId())) {
returnDesires.add(new Desire(a, b));
}
}
} else {
for (Goal g : level.goals) {
// System.err.println("adding goal goal with " + g.getId());
if (g.getId() == a.desire.box.getId() && g.object == null) {
System.err.println("adding desire "+ g.x + "." + g.y);
returnDesires.add(new Desire(a, a.desire.box, g));
}
}
}
a.desire = null;
}
return returnDesires;
}
private void findIntentions(ArrayList<Desire> desires) {
ArrayList<Desire> chosenIntentions = new ArrayList<Desire>();
//Assign new intentions.
for (Agent a : level.agents) {
a.desire = null;
}
//Shuffle desires. Should be removed in later stages.
Collections.shuffle(desires);
for (Desire d : desires) {
boolean agentAlreadyInIntentions = false;
for (Desire desire : chosenIntentions) {
if (desire.agent == d.agent || desire.box == d.box
|| (desire.goal != null && desire.goal == d.goal)) {
agentAlreadyInIntentions = true;
}
}
if (!agentAlreadyInIntentions) {
d.agent.desire = d;
chosenIntentions.add(d);
}
}
}
// A-star to the goal field for each agent.
private void decideCommands() {
for (int i = 0; i < level.agents.size(); i++) {
Agent a = level.agents.get(i);
Field goal;
//TODO is this ok?
if (a.desire == null)
return;
if (a.desire.goal != null)
goal = a.desire.goal;
else
goal = a.desire.box.getAtField();
// This is the new, incomplete code Andreas and Johan are making for
// branching.
if (a.desire.goal != null) {
Box b = null;
while (!findBranchingRoute(a, b))
moveObstacle(a, b);
continue;
}
//
HashMap<AStarField, AStarField> cameFrom = new HashMap<AStarField, AStarField>();
PriorityQueue<AStarField> openSet = new PriorityQueue<AStarField>();
Set<AStarField> closedSet = new HashSet<AStarField>();
AStarField start = new AStarField(a.getAtField());
start.g = 0;
start.f = start.g + heuristicEstimate(start.field, goal);
openSet.add(start);
AStarField curField = null;
outerloop: while (!openSet.isEmpty()) {
curField = openSet.poll();
// Check if we are next to the goal.
for (dir d : dir.values()) {
if (curField.field.neighbours[d.ordinal()] != null
&& curField.field.neighbours[d.ordinal()]
.equals(goal)) {
break outerloop;
}
}
closedSet.add(curField);
for (dir d : dir.values()) {
if (a.neighbourFree(curField.field, d)) {
int tentativeGScore = curField.g + 1;
AStarField neighbourInClosedSet = null;
for (AStarField aClosed : closedSet) {
if (aClosed.field
.equals(curField.field.neighbours[d
.ordinal()]))
neighbourInClosedSet = aClosed;
}
if (neighbourInClosedSet != null
&& tentativeGScore >= neighbourInClosedSet.g) {
continue;
}
AStarField neighbourInOpenSet = null;
for (AStarField aOpen : openSet) {
if (aOpen.field.equals(curField.field.neighbours[d
.ordinal()]))
neighbourInClosedSet = aOpen;
}
boolean nInOpenSet = (neighbourInOpenSet != null);
if (neighbourInOpenSet == null
|| tentativeGScore < neighbourInOpenSet.g) {
neighbourInOpenSet = new AStarField(
curField.field.neighbours[d.ordinal()]);
neighbourInOpenSet.g = tentativeGScore;
neighbourInOpenSet.f = neighbourInOpenSet.g
+ heuristicEstimate(
neighbourInOpenSet.field, goal);
neighbourInOpenSet.c = new Command(d);
cameFrom.put(neighbourInOpenSet, curField);
if (!nInOpenSet)
openSet.add(neighbourInOpenSet);
}
}
}
}
ArrayList<Command> commands = new ArrayList<Command>();
while (cameFrom.get(curField) != null) {
commands.add(curField.c);
curField = cameFrom.get(curField);
}
while (!commands.isEmpty()) {
a.commandQueue.add(commands.remove(commands.size() - 1));
}
}
}
private int heuristicEstimate(Field a, Field goal) {
return heuristicEstimateManhattan(a, goal);
}
private int heuristicEstimateEuclid(Field a, Field goal) {
int h = (int) Math.sqrt(Math.pow(Math.abs(a.x - goal.x), 2)
+ Math.pow(Math.abs(a.y - goal.y), 2));
return h;
}
// Manhattan distance
private int heuristicEstimateManhattan(Field a, Field goal) {
int h = (int) Math.abs(a.x - goal.x)
+ Math.abs(a.y - goal.y);
return h;
}
// Determines if an agent had a goal of getting to a box and completed this
// goal.
private boolean getToBoxDesireCompleted(Agent a) {
for (dir d : dir.values()) {
if (a.desire != null
&& a.desire.goal == null
&& a.getAtField().neighbours[d.ordinal()] != null
&& a.getAtField().neighbours[d.ordinal()]
.equals(a.desire.box.getAtField()))
return true;
}
return false;
}
private boolean getBoxToGoalDesireCompleted(Agent a){
if (a.desire != null
&& a.desire.goal != null
&& a.desire.box.getAtField() == a.desire.goal)
return true;
return false;
}
// We know that the agent a has a box. Now we want to move the box to the
// goal.
private boolean findBranchingRoute(Agent a, Box obstacle) {
dir boxDir = null;
BacktrackTree root = new BacktrackTree(a.desire.box.getAtField(),
a.getAtField(), null);
BacktrackTree currentNode = null;
Set<BacktrackTree> closedSet = new HashSet<BacktrackTree>();
LinkedList<BacktrackTree> queue = new LinkedList<BacktrackTree>();
// prune looped states (if agent and box ends up in a state already explored)
HashMap<Field, ArrayList<Field>> exploredStates = new HashMap<Field, ArrayList<Field>>();
//adding initial state to list set of explored states:
ArrayList<Field> tempList = new ArrayList<Field>();
tempList.add(a.desire.box.getAtField());
exploredStates.put(a.getAtField(), tempList);
//Add a closed set.
queue.add(root);
currentNode = queue.pop();
while (currentNode.boxLocation != a.desire.goal) {
boxDir = Agent.getBoxDirection(currentNode.agentLocation,currentNode.boxLocation);
ArrayList<Command> foundCommands = a
.addPossibleCommandsForDirection(boxDir,
currentNode.agentLocation, currentNode.boxLocation);
for (Command command : foundCommands) {
Field boxLocation = null;
Field agentLocation = null;
if (command.cmd.equals("Push")) {
agentLocation = currentNode.boxLocation;
boxLocation = currentNode.boxLocation.neighbours[command.dir2
.ordinal()];
} else {
boxLocation = currentNode.agentLocation;
agentLocation = currentNode.agentLocation.neighbours[command.dir1
.ordinal()];
}
// Do we already have a way to get to this state?
if (exploredStates.containsKey(agentLocation)) {
if (exploredStates.get(agentLocation).contains(boxLocation))
continue;
else { // the agent has been here before but without the box in same location
exploredStates.get(agentLocation).add(boxLocation);
}
} else { // neither the agent or the box has been here before. Update DS and create node in BTtree:
ArrayList<Field> tempListe = new ArrayList<Field>();
tempListe.add(boxLocation);
exploredStates.put(agentLocation, tempListe);
}
BacktrackTree bt = new BacktrackTree(boxLocation,
agentLocation, command);
bt.parent = currentNode;
boolean setupInClosedSet = false;
for (BacktrackTree closedTree : closedSet) {
if (closedTree.agentLocation.x == bt.agentLocation.x
&& closedTree.agentLocation.y == bt.agentLocation.y
&& closedTree.boxLocation.x == bt.boxLocation.x
&& closedTree.boxLocation.y == bt.boxLocation.y) {
setupInClosedSet = true;
}
}
if (!setupInClosedSet) {
queue.add(bt);
closedSet.add(bt);
}
}
if (queue.isEmpty()) { //TODO: we have searched to the end without finding a solution. Move boxes to get access to goals
return false;
}
currentNode = queue.pop();
}
ArrayList<Command> commands = new ArrayList<Command>();
while (currentNode.parent != null) {
commands.add(currentNode.action);
currentNode = currentNode.parent;
}
Collections.reverse(commands);
for (Command command : commands) {
a.commandQueue.add(command);
}
return true;
}
/*
* find the route with fewest obstacles first, but consider all routes
*/
private void moveObstacle(Agent a, Box b) {
// 1. By using a* find routes to the goal ignoring, but counting boxes (that the agent can move)
// 2. queue the routes to goal and save then along with the boxes required to be removed (PriorityQueue on count(Boxes))
// 3. while there is no solution: take the top element in the queue and move the obstacles using "findFreeField" and "findBranchingRoute"
}
/*
* Find a field where a box not ready for goal can be put.
* We need to consider the current plan (route to goal for last desire's box) and choose a field not on that route
* If there are less "free" fields than required we are f*ed
*/
private Field findFreeField(Agent a) {
return null;
}
private class BacktrackTree {
public BacktrackTree parent;
public Field boxLocation;
public Field agentLocation;
Command action;
public BacktrackTree(Field boxLocation, Field agentLocation,
Command action) {
super();
this.boxLocation = boxLocation;
this.agentLocation = agentLocation;
this.action = action;
}
}
}
| Java |
package client.planners;
import java.util.Random;
import constants.Constants.dir;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Field;
import LevelObjects.Goal;
import LevelObjects.Level;
import aStar.Pathfinding;
public class AStarPlanner implements Planner {
Level level;
Random rand = new Random();
private static final String name = "AStarPlanner";
@Override
public String getName() {
return name;
}
public AStarPlanner(Level l) {
this.level = l;
}
public void makePlan() {
// assign each agent (in this case 1) some goals (to begin with 1 box to 1 goal)
Agent agent = level.agents.get(0);
//Box box = level.boxes.get(0);
Goal goal = level.goals.get(0);
// set agent cmd queue
agent.commandQueue = Pathfinding.commandsForAgentToField(level, agent, goal); // should make agent walk to goal...
}
// functions to deal with conflicts among agents...
} | Java |
package client;
import LevelObjects.Agent;
import LevelObjects.Box;
import LevelObjects.Goal;
public class Desire {
public Agent agent;
public Box box;
public Goal goal;
boolean completed;
public Desire(Agent a, Box b) {
this.agent = a;
this.box = b;
}
public Desire(Agent a, Box b, Goal g) {
this.agent = a;
this.box = b;
this.goal = g;
}
}
| Java |
package client.messages;
import java.util.List;
import LevelObjects.Field;
public class MoveRequest extends Message {
// when can the agent move again
public int WaitUntil;
// what fields are blocked in the period
public List<Field> blokedFields;
}
| Java |
package client.messages;
public class Response extends Message {
// Is the agent able to help?
public boolean Acknowledged;
// The original message
public Message OriginalRequest;
}
| Java |
package client.messages;
import LevelObjects.Agent;
public abstract class Message {
public Agent fromAgent;
public Agent toAgent;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.