Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Java didn't report the same OS name as Cmake for Windows platform, force it to be...
[simgrid.git] / src / bindings / java / org / simgrid / msg / Msg.java
1 /*
2  * JNI interface to C code for MSG.
3  * 
4  * Copyright 2006-2012 The SimGrid Team.           
5  * All right reserved. 
6  *
7  * This program is free software; you can redistribute 
8  * it and/or modify it under the terms of the license 
9  * (GNU LGPL) which comes with this package.
10  */
11
12 package org.simgrid.msg;
13
14 import java.io.FileOutputStream;
15 import java.io.InputStream;
16 import java.io.OutputStream;
17 import java.io.File;
18
19
20 public final class Msg {
21         /* Statically load the library which contains all native functions used in here */
22         static private boolean isNativeInited = false;
23         public static void nativeInit() {
24                 if (isNativeInited)
25                         return;
26                 try {
27                         /* prefer the version on disk, if existing */
28                         System.loadLibrary("SG_java");
29                 } catch (UnsatisfiedLinkError e) {
30                         /* If not found, unpack the one bundled into the jar file and use it */
31                         loadLib("simgrid");
32                         loadLib("SG_java");
33                 }
34                 isNativeInited = true;
35         }
36         static {
37                 nativeInit();
38         }
39         private static void loadLib (String name) {
40           String Os = System.getProperty("os.name");
41           //Windows may report its name in java differently from cmake, which generated the path
42                 if(Os.toLowerCase().indexOf("win") >= 0) Os = "Windows";
43                 String Path = "NATIVE/"+Os+"/"+System.getProperty("os.arch")+"/";
44                                 System.out.println("loading from " +Path);
45
46                 String filename=name;
47                 InputStream in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
48                 
49                 if (in == null) {
50                         filename = "lib"+name+".so";
51                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
52                 } 
53                 if (in == null) {
54                         filename = name+".dll";
55                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
56                 }  
57                 if (in == null) {
58                         filename = "lib"+name+".dll";
59                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
60                 }  
61                 if (in == null) {
62                         filename = "lib"+name+".dylib";
63                         in = Msg.class.getClassLoader().getResourceAsStream(Path+filename);
64                 }  
65                 if (in == null) {
66                         throw new RuntimeException("Cannot find library "+name+" in path "+Path+". Sorry, but this jar does not seem to be usable on your machine.");
67                 }
68 // Caching the file on disk: desactivated because it could fool the users               
69 //              if (new File(filename).isFile()) {
70 //                      // file was already unpacked -- use it directly
71 //                      System.load(new File(".").getAbsolutePath()+File.separator+filename);
72 //                      return;
73 //              }
74                 try {
75                         // We must write the lib onto the disk before loading it -- stupid operating systems
76                         File fileOut = new File(filename);
77 //                      if (!new File(".").canWrite()) {
78 //                              System.out.println("Cannot write in ."+File.separator+filename+"; unpacking the library into a temporary file instead");
79                                 fileOut = File.createTempFile("simgrid-", ".tmp");
80                                 // don't leak the file on disk, but remove it on JVM shutdown
81                                 Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(fileOut.getAbsolutePath())));
82 //                      }
83 //                      System.out.println("Unpacking SimGrid native library to " + fileOut.getAbsolutePath());
84                         OutputStream out = new FileOutputStream(fileOut);
85                         
86                         /* copy the library in position */  
87                         byte[] buffer = new byte[4096]; 
88                         int bytes_read; 
89                         while ((bytes_read = in.read(buffer)) != -1)     // Read until EOF
90                                 out.write(buffer, 0, bytes_read); 
91                       
92                         /* close all file descriptors, and load that shit */
93                         in.close();
94                         out.close();
95                         System.load(fileOut.getAbsolutePath());
96                 } catch (Exception e) {
97                         System.err.println("Cannot load the bindings to the simgrid library: ");
98                         e.printStackTrace();
99                         System.err.println("This jar file does not seem to fit your system, sorry");
100                         System.exit(1);
101                 }
102         }               
103         /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
104         private static class FileCleaner implements Runnable {
105                 private String target;
106                 public FileCleaner(String name) {
107                         target = name;
108                 }
109         public void run() {
110             try {
111                 new File(target).delete();
112             } catch(Exception e) {
113                 System.out.println("Unable to clean temporary file "+target+" during shutdown.");
114                 e.printStackTrace();
115             }
116         }    
117         }
118
119     /** Retrieve the simulation time
120      * @return The simulation time.
121      */
122         public final static native double getClock();
123         /**
124          * Issue a debug logging message.
125          * @param s message to log.
126          */
127         public final static native void debug(String s);
128         /**
129          * Issue an verbose logging message.
130          * @param s message to log.
131          */
132         public final static native void verb(String s);
133
134         /** Issue an information logging message
135      * @param s
136      */
137         public final static native void info(String s);
138         /**
139          * Issue an warning logging message.
140          * @param s message to log.
141          */
142         public final static native void warn(String s);
143         /**
144          * Issue an error logging message.
145          * @param s message to log.
146          */
147         public final static native void error(String s);
148         /**
149          * Issue an critical logging message.
150          * @param s message to log.
151          */
152         public final static native void critical(String s);
153
154         /*********************************************************************************
155          * Deployment and initialization related functions                               *
156          *********************************************************************************/
157
158         /**
159          * The natively implemented method to initialize a MSG simulation.
160          *
161          * @param args            The arguments of the command line of the simulation.
162          */
163         public final static native void init(String[]args);
164
165         /**
166          * Run the MSG simulation.
167          *
168          * The simulation is not cleaned afterward (see  
169          * {@link #clean()} if you really insist on cleaning the C side), so you can freely 
170          * retrieve the informations that you want from the simulation. In particular, retrieving the status 
171          * of a process or the current date is perfectly ok. 
172          */
173         public final static native void run() ;
174         
175         /** This function is useless nowadays, just stop calling it. */
176         @Deprecated
177         public final static void clean(){}
178
179         /**
180          * The native implemented method to create the environment of the simulation.
181          *
182          * @param platformFile    The XML file which contains the description of the environment of the simulation
183          *
184          */
185         public final static native void createEnvironment(String platformFile);
186
187         /**
188          * The method to deploy the simulation.
189          *
190      *
191      * @param deploymentFile
192      */
193         public final static native void deployApplication(String deploymentFile);
194
195     /** Example launcher. You can use it or provide your own launcher, as you wish
196      * @param args
197      * @throws MsgException
198      */
199         static public void main(String[]args) throws MsgException {
200                 /* initialize the MSG simulation. Must be done before anything else (even logging). */
201                 Msg.init(args);
202
203                 if (args.length < 2) {
204                         Msg.info("Usage: Msg platform_file deployment_file");
205                         System.exit(1);
206                 }
207
208                 /* Load the platform and deploy the application */
209                 Msg.createEnvironment(args[0]);
210                 Msg.deployApplication(args[1]);
211                 /* Execute the simulation */
212                 Msg.run();
213         }
214 }