001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package chapters.mdc; 015 016import java.io.BufferedReader; 017import java.io.InputStreamReader; 018import java.rmi.Naming; 019import java.rmi.RemoteException; 020 021/** 022 * NumberCruncherClient is a simple client for factoring integers. A 023 * remote NumberCruncher is contacted and asked to factor an 024 * integer. The factors returned by the {@link NumberCruncherServer} 025 * are displayed on the screen. 026 * */ 027public class NumberCruncherClient { 028 public static void main(String[] args) { 029 if (args.length == 1) { 030 try { 031 String url = "rmi://" + args[0] + "/Factor"; 032 NumberCruncher nc = (NumberCruncher) Naming.lookup(url); 033 loop(nc); 034 } catch (Exception e) { 035 e.printStackTrace(); 036 } 037 } else { 038 usage("Wrong number of arguments."); 039 } 040 } 041 042 static void usage(String msg) { 043 System.err.println(msg); 044 System.err.println("Usage: java chapters.mdc.NumberCruncherClient HOST\n" + " where HOST is the machine where the NumberCruncherServer is running."); 045 System.exit(1); 046 } 047 048 static void loop(NumberCruncher nc) { 049 BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 050 int i = 0; 051 052 while (true) { 053 System.out.print("Enter a number to factor, '-1' to quit: "); 054 055 try { 056 i = Integer.parseInt(in.readLine()); 057 } catch (Exception e) { 058 e.printStackTrace(); 059 } 060 061 if (i == -1) { 062 System.out.print("Exiting loop."); 063 064 return; 065 } else { 066 try { 067 System.out.println("Will attempt to factor " + i); 068 069 int[] factors = nc.factor(i); 070 System.out.print("The factors of " + i + " are"); 071 072 for (int k = 0; k < factors.length; k++) { 073 System.out.print(" " + factors[k]); 074 } 075 076 System.out.println("."); 077 } catch (RemoteException e) { 078 System.err.println("Could not factor " + i); 079 e.printStackTrace(); 080 } 081 } 082 } 083 } 084}