/** * Fetch participants of TaskUpdate. Is called on creation of a new instance of TaskUpdate. * * @param repoUid the specified repository's identifier. * @return new Object[] with length of 2. The first item is a vector of Links that content is * containing ComputerRemotes that are online and participating at the specified repository. * <p>The second entry contains a link between the local computer and the specified * repository. */ private Object[] fetchTaskupdateParticipants(String repoUid) { Vector<Link> vec_parti = new Vector<Link>(); Link ownRepoLink = null; for (int j = 0; j < combination.size(); j++) { final Link secondLnk = getCombination().get(j); if (secondLnk.getRepository().getUid().equals(repoUid)) { // inform the specified computer about the // changes final Computer currentComputer = secondLnk.getComputer(); if (!currentComputer.matches(ComputerLocal.this) && currentComputer instanceof ComputerRemote) { vec_parti.addElement(secondLnk); } else if (currentComputer.getUid().equals(getUid())) { ownRepoLink = secondLnk; } } } return new Object[] {vec_parti, ownRepoLink}; }
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST) public String update( @PathVariable Long id, @RequestParam(required = false) String name, @RequestParam(required = false) String introduced, @RequestParam(required = false) String discontinued, @RequestParam(required = false) String company, ModelMap model, RedirectAttributes redirectAttributes) { ComputerForm form = new ComputerForm(); form.setId(id); form.setName(name); form.setIntroduced(introduced); form.setDiscontinued(discontinued); form.setCompany(company); if (!form.isValid()) { model.addAttribute("form", form); model.addAttribute("companies", companyService.findAll()); return "/edit"; } else { Computer computer = form.toComputer(); computer = computerService.update(computer); redirectAttributes.addFlashAttribute( "success", "Computer with id " + computer.getId() + " has been updated"); return "redirect:/computers"; } }
public void testQueryComputers() throws Exception { String[] classNames = { "ctf.jdo.tc9x.Laptop", "ctf.jdo.tc9x.Laptop", "ctf.jdo.tc9x.Server", "ctf.jdo.tc9x.Server" }; Database database = _category.getDatabase(); database.begin(); OQLQuery query = database.getOQLQuery( "select computer from " + Computer.class.getName() + " as computer order by computer.id"); QueryResults results = query.execute(); if (results.hasMore()) { int counter = 1; while (results.hasMore()) { Computer computer = (Computer) results.next(); assertNotNull(computer); assertEquals(counter, computer.getId()); assertEquals(classNames[counter - 1], computer.getClass().getName()); counter += 1; } } else { fail("Query does not return any Computer instances."); } database.commit(); database.close(); }
public static void main(String[] args) { Computer computer = new Desktop(new Dell()); computer.sale(); computer = new Pad(new Dell()); computer.sale(); computer = new Notebook(new Dell()); computer.sale(); }
/** * Adds an all-in-one computer (combined with four freely customizable parts) to the cart. * * @param article requested all-in-one computer * @param number the amount of requested articles * @param cart contains a fresh initialized cart * @param success notification about adding an article to the cart * @return redirect to template "allinone" */ @RequestMapping(value = "/cart2", method = RequestMethod.POST) public String addcomp( @RequestParam("pid") Computer article, @RequestParam("number") int number, @ModelAttribute Cart cart, RedirectAttributes success) { Optional<InventoryItem> item = inventory.findByProductIdentifier(article.getIdentifier()); Quantity quantity = item.map(InventoryItem::getQuantity).orElse(NONE); BigDecimal amount1 = quantity.getAmount(); int i = amount1.intValue(); int amount = number; if (number <= 0) { amount = 1; } if (number >= i) { amount = i; } cart.addOrUpdateItem(article, Quantity.of(amount)); cart.addOrUpdateItem(article.getProzessor().get(0), Quantity.of(amount)); cart.addOrUpdateItem(article.getGraka().get(0), Quantity.of(amount)); cart.addOrUpdateItem(article.getHdd().get(0), Quantity.of(amount)); cart.addOrUpdateItem(article.getRam().get(0), Quantity.of(amount)); article.getGraka().clear(); article.getHdd().clear(); article.getProzessor().clear(); article.getRam().clear(); success.addFlashAttribute( "success", "Der Artikel wurde erfolgreich Ihrem Warenkorb hinzugefügt."); return "redirect:allinone"; }
public void testCreateAndLoadComputer() throws Exception { Database database = _category.getDatabase(); database.begin(); Order order = new Order(); order.setId(12); order.setName("order 12"); database.create(order); database.commit(); database.begin(); ProductDetail detail = new ProductDetail(); detail.setId(12); detail.setCategory("category 12"); detail.setLocation("location 12"); database.create(detail); database.commit(); database.begin(); Laptop laptop = new Laptop(); laptop.setId(12); laptop.setName("laptop 12"); laptop.setCpu("centrino"); laptop.setResolution("1600"); laptop.setWeight(2450); laptop.setDetail((ProductDetail) database.load(ProductDetail.class, new Integer(12))); database.create(laptop); Collection orders = new LinkedList(); orders.add(database.load(Order.class, new Integer(12))); laptop.setOrders(orders); database.commit(); database.begin(); Computer computer = (Computer) database.load(Computer.class, new Integer(12)); database.commit(); assertNotNull(computer); assertEquals("ctf.jdo.tc9x.Laptop", computer.getClass().getName()); assertEquals(12, computer.getId()); assertEquals("laptop 12", computer.getName()); database.begin(); computer = (Computer) database.load(Computer.class, new Integer(12)); database.remove(computer); database.remove(database.load(ProductDetail.class, new Integer(12))); database.remove(database.load(Order.class, new Integer(12))); database.commit(); database.close(); }
public void testLoadComputer() throws Exception { Database database = _category.getDatabase(); database.begin(); Computer computer = (Computer) database.load(Computer.class, new Integer(2)); database.commit(); assertNotNull(computer); assertEquals("ctf.jdo.tc9x.Laptop", computer.getClass().getName()); assertEquals(2, computer.getId()); assertEquals("laptop 2", computer.getName()); database.close(); }
private Connection connectToSsh(Computer computer, PrintStream logger) throws RequestUnsuccessfulException, DigitalOceanException { final long timeout = TimeUnit2.MINUTES.toMillis(computer.getCloud().getTimeoutMinutes()); final long startTime = System.currentTimeMillis(); final int sleepTime = 10; long waitTime; while ((waitTime = System.currentTimeMillis() - startTime) < timeout) { // Hack to fetch this each time through the loop to get the latest information. final Droplet droplet = DigitalOcean.getDroplet( computer.getCloud().getAuthToken(), computer.getNode().getDropletId()); if (isDropletStarting(droplet)) { logger.println( "Waiting for droplet to enter ACTIVE state. Sleeping " + sleepTime + " seconds."); } else { try { final String host = getIpAddress(computer); if (Strings.isNullOrEmpty(host) || "0.0.0.0".equals(host)) { logger.println( "No ip address yet, your host is most likely waiting for an ip address."); } else { int port = computer.getSshPort(); Connection conn = getDropletConnection(host, port, logger); if (conn != null) { return conn; } } } catch (IOException e) { // Ignore, we'll retry. } logger.println("Waiting for SSH to come up. Sleeping " + sleepTime + " seconds."); } sleep(sleepTime); } throw new RuntimeException( format( "Timed out after %d seconds of waiting for ssh to become available (max timeout configured is %s)", waitTime / 1000, timeout / 1000)); }
/** * Creates the Peripherals frame. * * @param computer the computer control object * @param computerHardware the computer hardware object */ public PeripheralsFrame(final Computer computer, final ComputerHardware computerHardware) { super( Application.getString(PeripheralsFrame.class, "peripherals.frameTitle"), computer.getIconLayout().getIcon(IconLayout.ICON_POSITION_CABLE)); log.fine("New PeripheralsFrame creation started"); assert computerHardware != null; peripherals = new Peripheral[] { new IOPanel(computerHardware), new LEDMatrix(), new ColorLEDMatrix(), new SiSDMatrix(), new PCKeyboard(), new ADC(), new DACAnalog(), new DACDigital(), new Counter(), new DebugOutput() }; peripheralsPanel = new PeripheralsPanel(this, peripherals); add(peripheralsPanel); setUp(); pack(); log.fine("PeripheralsFrame set up"); }
@RequestMapping(value = "/save", method = RequestMethod.POST) public String save( @ModelAttribute Computer computer, BindingResult result, SessionStatus status, ModelMap model, RedirectAttributes redirectAttributes) { computerValidator.validate(computer, result); if (result.hasErrors()) { model.addAttribute("computer", computer); model.addAttribute("companies", companyService.findAll()); model.addAttribute("result", result); return "/create"; } else { computer = computerService.create(computer); status.setComplete(); redirectAttributes.addFlashAttribute( "success", "Computer named " + computer.getName() + " has been created"); return "redirect:/computers"; } }
protected boolean execute(int address, String expectedOutput) { boolean isSuccess = false; Cpu cpu = computer.getCpu(); cpu.writeRegister(false, Cpu.PC, address); long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < MAX_EXECUTION_TIME || terminal.getWrittenData().length() > Terminal.MAX_DATA_LENGTH) { try { cpu.executeNextOperation(); if (cpu.isHaltMode()) { throw new IllegalStateException("HALT mode"); } } catch (Exception e) { e.printStackTrace(); fail( "can't execute operation, PC: 0" + Integer.toOctalString(cpu.readRegister(false, Cpu.PC))); } if (expectedOutput.equals(terminal.getWrittenData())) { isSuccess = true; break; } } return isSuccess; }
public void createTables(DatabaseSession session) { dropTableConstraints(session); new InheritanceTableCreator().replaceTables(session); SchemaManager schemaManager = new SchemaManager(session); if (session.getLogin().getPlatform().isOracle()) { schemaManager.replaceObject(Computer.oracleView()); schemaManager.replaceObject(Vehicle.oracleView()); } else if (session.getLogin().getPlatform().isSybase()) { schemaManager.replaceObject(Computer.sybaseView()); schemaManager.replaceObject(Vehicle.sybaseView()); // CREATE VIEW statement was added in MySQL 5.0.1. Uncomment it when we support MySQL 5 // } else if (session.getLogin().getPlatform().isMySQL()) { // schemaManager.replaceObject(Computer.sybaseView()); // schemaManager.replaceObject(Vehicle.mySQLView()); } }
public static Request classes(Computer computer, Class<?>... classes) { try { return runner(computer.getSuite(new AllDefaultPossibilitiesBuilder(true), classes)); } catch (InitializationError e) { throw new RuntimeException( "Bug in saff's brain: Suite constructor, called as above, should always complete"); } }
/** * Create a <code>Request</code> that, when processed, will run all the tests in a set of classes. * * @param computer Helps construct Runners from classes * @param classes the classes containing the tests * @return a <code>Request</code> that will cause all tests in the classes to be run */ public static Request classes(Computer computer, Class<?>... classes) { try { AllDefaultPossibilitiesBuilder builder = new AllDefaultPossibilitiesBuilder(true); Runner suite = computer.getSuite(builder, classes); return runner(suite); } catch (InitializationError e) { return runner(new ErrorReportingRunner(e, classes)); } }
/** * In addition to the usual observer behavior, the addObserver fires a notify event on startup. * * <p>{@inheritDoc}. * * @param xo the observer that is to be set. * @author Julius Huelsmann * @version %I%, %U% * @since 1.0 */ public final void addObserver(final Observer xo) { super.addObserver(xo); setChanged(); notifyObservers(new Object[] {View.ID_UPDATE_LINK, combination}); setChanged(); notifyObservers(new Object[] {View.ID_UPDATE_REPO, repositories}); setChanged(); notifyObservers(new Object[] {View.ID_UPDATE_COMPUTER, computer}); }
private static String getIpAddress(Computer computer) throws RequestUnsuccessfulException, DigitalOceanException { Droplet instance = computer.updateInstanceDescription(); for (final Network network : instance.getNetworks().getVersion4Networks()) { String host = network.getIpAddress(); if (host != null) { return host; } } return null; }
/** * The player with "theSeed" makes one move, with input validation. Update cell's content, board's * currentRow and currentCol. */ public void playerMove(Seed theSeed) { boolean validInput = false; // for validating input boolean loop = true; int row = -1; int col = -1; do { if (theSeed == Seed.NOUGHT) { System.out.println("Your turn"); do { System.out.print("Enter your move (row[0-2] column[0-2]): "); String r = in.next(); String c = in.next(); try { row = Integer.parseInt(r); col = Integer.parseInt(c); loop = false; } catch (NumberFormatException e) { System.out.println("Invalid input"); } } while (loop); if (row >= 0 && row < Board.ROWS && col >= 0 && col < Board.COLS && board.cells[row][col].content == Seed.EMPTY) { board.cells[row][col].content = theSeed; board.currentRow = row; board.currentCol = col; validInput = true; // input okay, exit loop } else { System.out.println( "This move at (" + (row) + "," + (col) + ") is not valid. Try again..."); } } else { row = comp.move(); col = comp.move(); if (row >= 0 && row < Board.ROWS && col >= 0 && col < Board.COLS && board.cells[row][col].content == Seed.EMPTY) { board.cells[row][col].content = theSeed; board.currentRow = row; board.currentCol = col; validInput = true; // input okay, exit loop } } } while (!validInput); // repeat until input is valid }
private void execute() { if (sourceFile == null) { printError("-i : No source file specified"); } if (assembler == null || computer == null) { printError("-f : No format specified"); } if (assembler.hasErrors()) { printError("Unable to execute file due to errors"); } print("...preparing to execute program"); if (trace) { print("...opening computer trace files"); addTraceListeners(); } computer.setExecutionSpeed(ExecutionSpeed.FULL); computer.setInstructions(assembler.getInstructions()); computer.addComputerListener( new ComputerAdapter() { public void computerStarted(Computer computer) { print("...Execution started"); } public void computerStopped(Computer computer) { print("...Execution complete"); } }); computer.execute(); }
/** @param args */ public static void main(String[] args) { Computer computer = new Computer(); Component component = new Component(1, "dell"); computer.setComponent(component); computer.setType("D630"); try { Computer computer2 = (Computer) computer.clone(); System.out.println(computer2.toString()); component.setName("Lenovo"); System.out.println(computer2.toString()); System.out.println(computer == computer2); } catch (CloneNotSupportedException e) { e.printStackTrace(); } }
/** @throws java.lang.Exception */ @Before public void setUp() throws Exception { computer = new Computer(); computer.setClockFrequency(Computer.CLOCK_FREQUENCY_BK0010); workMemory = new RandomAccessMemory("TestWorkMemory", 0, 020000); computer.addMemory(workMemory); RandomAccessMemory videoMemory = new RandomAccessMemory("TestVideoMemory", 040000, 020000); computer.addMemory(videoMemory); computer.addMemory(new ReadOnlyMemory("TestReadOnlyMemory", 0100000, new byte[010000])); terminal = new Terminal(); computer.addDevice(terminal); computer.getCpu().setPswState(0); computer.getCpu().writeRegister(false, Cpu.SP, 020000); computer.getCpu().writeRegister(false, Cpu.PC, 4); }
@Test @SuppressWarnings("unchecked") public void shouldIncludeParents() { deleteFromTable("computers"); deleteFromTable("motherboards"); deleteFromTable("keyboards"); populateTable("motherboards"); populateTable("keyboards"); populateTable("computers"); String json = Computer.findAll().include(Motherboard.class, Keyboard.class).toJson(true); List list = org.javalite.common.JsonHelper.toList(json); Map m = (Map) list.get(0); Map parents = (Map) m.get("parents"); List motherboards = (List) parents.get("motherboards"); List keyboards = (List) parents.get("keyboards"); the(motherboards.size()).shouldBeEqual(1); the(keyboards.size()).shouldBeEqual(1); }
private boolean runInitScript( final Computer computer, final PrintStream logger, final Connection conn, final SCPClient scp) throws IOException, InterruptedException { String initScript = Util.fixEmptyAndTrim(computer.getNode().getInitScript()); if (initScript == null) { return true; } if (conn.exec("test -e ~/.hudson-run-init", logger) == 0) { return true; } logger.println("Executing init script"); scp.put(initScript.getBytes("UTF-8"), "init.sh", "/tmp", "0700"); Session session = conn.openSession(); session.requestDumbPTY(); // so that the remote side bundles stdout and stderr session.execCommand(buildUpCommand(computer, "/tmp/init.sh")); session.getStdin().close(); // nothing to write here session.getStderr().close(); // we are not supposed to get anything from stderr IOUtils.copy(session.getStdout(), logger); int exitStatus = waitCompletion(session); if (exitStatus != 0) { logger.println("init script failed: exit code=" + exitStatus); return false; } session.close(); // Needs a tty to run sudo. session = conn.openSession(); session.requestDumbPTY(); // so that the remote side bundles stdout and stderr session.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init")); session.close(); return true; }
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("step04/application-context02.xml"); Computer c1 = (Computer) context.getBean("c1"); Computer c2 = (Computer) context.getBean("c2"); Computer c3 = (Computer) context.getBean("c3"); System.out.println(c1); System.out.println(c2); System.out.println(c3); System.out.println(c1.getMonitor().hashCode()); System.out.println(c3.getMonitor().hashCode()); if (c1.getMonitor() == c3.getMonitor()) { System.out.println("c1의 모니터 == c3의 모니터"); } }
private static void printSpecs(ArrayList<Computer> computerList) { // print specs for reference DecimalFormat price = new DecimalFormat("$0.00"); DecimalFormat speed = new DecimalFormat("0.0 GHz"); DecimalFormat memory = new DecimalFormat("0.0 GB"); for (Computer c : computerList) { System.out.println( "Model: " + c.getModel() + " | Memory: " + memory.format(c.getMemory()) + " | Speed: " + speed.format(c.getSpeed()) + " | GraphicsCard: " + c.getCard() + " | Price: " + price.format(c.getPrice())); System.out.println(); } }
public void populate(DatabaseSession session) { PopulationManager manager = PopulationManager.getDefaultManager(); Cat cat = Cat.example1(); session.writeObject(cat); manager.registerObject(cat, "catExample1"); Dog dog = Dog.example1(); session.writeObject(dog); manager.registerObject(dog, "dogExample1"); cat = Cat.example2(); session.writeObject(cat); manager.registerObject(cat, "catExample2"); dog = Dog.example2(); session.writeObject(dog); manager.registerObject(dog, "dogExample2"); cat = Cat.example3(); session.writeObject(cat); manager.registerObject(cat, "catExample3"); dog = Dog.example3(); session.writeObject(dog); manager.registerObject(dog, "dogExample3"); Company company = Company.example1(); session.writeObject(company); manager.registerObject(company, "example1"); manager.registerObject(((Vector) company.getVehicles().getValue()).firstElement(), "example1"); company = Company.example2(); session.writeObject(company); manager.registerObject(company, "example2"); company = Company.example3(); session.writeObject(company); manager.registerObject(company, "example3"); Person person = Person.example1(); session.writeObject(person); manager.registerObject(person, "example1"); // populate the data for duplicate field testing session.writeObject(A_King2.exp1()); session.writeObject(A_King2.exp2()); session.writeObject(A_1_King2.exp3()); session.writeObject(A_2_King2.exp4()); session.writeObject(A_2_1_King2.exp5()); UnitOfWork unitOfWork = session.acquireUnitOfWork(); person = Person.example2(); unitOfWork.registerObject(person); unitOfWork.commit(); manager.registerObject(person, "example2"); manager.registerObject(person.bestFriend, "example5"); manager.registerObject(person.representitive, "example4"); person = Person.example3(); session.writeObject(person); manager.registerObject(person, "example3"); Computer computer = Computer.example1(); session.writeObject(computer); manager.registerObject(computer, "example1"); computer = Computer.example2(); session.writeObject(computer); manager.registerObject(computer, "example2"); computer = Computer.example3(); session.writeObject(computer); manager.registerObject(computer, "example3"); computer = Computer.example4(); session.writeObject(computer); manager.registerObject(computer, "example4"); computer = Computer.example5(); session.writeObject(computer); manager.registerObject(computer, "example5"); JavaProgrammer JP = JavaProgrammer.example1(); session.writeObject(JP); manager.registerObject(JP, "example1"); JP = JavaProgrammer.example2(); session.writeObject(JP); manager.registerObject(JP, "example2"); // Added to test bug 3019934. unitOfWork = session.acquireUnitOfWork(); Alligator alligator = new Alligator(); alligator.setFavoriteSwamp("Florida"); alligator.setLatestVictim(JavaProgrammer.steve()); unitOfWork.registerObject(alligator); manager.registerObject(alligator, "example1"); unitOfWork.commit(); // Added to test bug 6111278 unitOfWork = session.acquireUnitOfWork(); Entomologist bugguy = new Entomologist(); bugguy.setId((int) System.currentTimeMillis()); bugguy.setName("Gary"); bugguy = (Entomologist) unitOfWork.registerObject(bugguy); Insect insect = new GrassHopper(); insect.setIn_numberOfLegs(4); insect.setEntomologist(bugguy); bugguy.getInsectCollection().add(insect); unitOfWork.commit(); }
@Override public String description() { return comp.description() + "and disk"; }
protected void perform(Computer computer) { computer.getRegisters().getCx().set(computer.getOperandValue(1)); }
public static void main(String[] args) { Computer facade = new Computer(); facade.start(); }
/** * Connects to the given {@link Computer} via SSH and installs Java/Jenkins agent if necessary. */ @Override public void launch(SlaveComputer _computer, TaskListener listener) { Computer computer = (Computer) _computer; PrintStream logger = listener.getLogger(); Date startDate = new Date(); logger.println("Start time: " + getUtcDate(startDate)); final Connection conn; Connection cleanupConn = null; boolean successful = false; try { conn = connectToSsh(computer, logger); cleanupConn = conn; logger.println("Authenticating as " + computer.getRemoteAdmin()); if (!conn.authenticateWithPublicKey( computer.getRemoteAdmin(), computer.getNode().getPrivateKey().toCharArray(), "")) { logger.println("Authentication failed"); throw new Exception("Authentication failed"); } final SCPClient scp = conn.createSCPClient(); if (!runInitScript(computer, logger, conn, scp)) { return; } if (!installJava(logger, conn)) { return; } logger.println("Copying slave.jar"); scp.put(Jenkins.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar", "/tmp"); String jvmOpts = Util.fixNull(computer.getNode().getJvmOpts()); String launchString = "java " + jvmOpts + " -jar /tmp/slave.jar"; logger.println("Launching slave agent: " + launchString); final Session sess = conn.openSession(); sess.execCommand(launchString); computer.setChannel( sess.getStdout(), sess.getStdin(), logger, new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { sess.close(); conn.close(); } }); successful = true; } catch (Exception e) { LOGGER.log(Level.WARNING, e.getMessage(), e); try { Jenkins.getInstance().removeNode(computer.getNode()); } catch (Exception ee) { ee.printStackTrace(logger); } e.printStackTrace(logger); } finally { Date endDate = new Date(); logger.println("Done setting up at: " + getUtcDate(endDate)); logger.println( "Done in " + TimeUnit2.MILLISECONDS.toSeconds(endDate.getTime() - startDate.getTime()) + " seconds"); if (cleanupConn != null && !successful) { cleanupConn.close(); } } }
protected String buildUpCommand(Computer computer, String command) { if (!computer.getRemoteAdmin().equals("root")) { // command = computer.getRootCommandPrefix() + " " + command; } return command; }