package blockchain.utility; import blockchain.user.UserContext; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import java.io.*; public class Util { private static Logger logger = Logger.getLogger(Util.class); public static void writeUserContext(UserContext userContext) { BasicConfigurator.configure(); ObjectOutputStream out = null; FileOutputStream fileOutputStream = null; try { logger.info("Write user "+userContext.getName()+" of "+userContext.getAffiliation()); String directoryPath = "msp/" + userContext.getAffiliation(); String filePath = directoryPath + "/" + userContext.getName() + ".context"; File directory = new File(directoryPath); if (!directory.exists()){ logger.info("Create directory at path "+directoryPath); directory.mkdirs(); } File file = new File(filePath); fileOutputStream = new FileOutputStream(file); out = new ObjectOutputStream(fileOutputStream); logger.info("Try write object for user "+userContext.getName()); out.writeObject(userContext); } catch (IOException e) { logger.error("1st IOException"); e.printStackTrace(); } finally { try { if (out != null){ logger.info("Close ObjectOutputStream"); out.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (fileOutputStream != null) { logger.info("Close fileOutputStream"); fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static UserContext readUserContext(String affiliation, String username) { UserContext userContext = null; FileInputStream fileStream = null; ObjectInputStream in = null; try { String filePath = "msp/" + affiliation + "/" + username + ".context"; File file = new File(filePath); if (file.exists()) { fileStream = new FileInputStream(filePath); in = new ObjectInputStream(fileStream); userContext = (UserContext) in.readObject(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fileStream != null) fileStream.close(); } catch (IOException e) { e.printStackTrace(); } return userContext; } } }