id
stringlengths
36
36
text
stringlengths
1
1.25M
cd408202-f713-4856-8ce2-2861b49c46e0
public String getGender() { return gender; }
ae8bc279-5623-4732-9b52-72f367fc6224
public void setGender(String gender) { this.gender = gender; }
95ecf272-64cf-4a9f-861d-8f7104289af8
public String getRole() { return role; }
438549c8-c9b5-4193-b25f-87da1866dfaa
public void setRole(String role) { this.role = role; }
97f4d105-4988-4792-8bc8-380a8696da04
public boolean validate() { if(email == null || username == null || password == null || role == null) return false; if(confirmPwd == null || !password.equals(confirmPwd)) return false; return true; }
1713cc4e-4f4c-4122-a625-b546c2f7f555
public long getId() { return id; }
acc10e89-b2a3-4665-b2da-8566cddbd280
public void setId(long id) { this.id = id; }
3aef3797-6bae-4fd1-ac1a-7f6c12cc5ab3
public Date getTime() { return time; }
28c425ee-28ee-4396-bbed-22e43f391604
public void setTime(Date time) { this.time = time; }
9b67b7ed-c2fb-4e36-89bb-7137b0f7abeb
public int getBg() { return bg; }
516bd56b-1709-4347-8257-6375cc33d8b3
public void setBg(int bg) { this.bg = bg; }
c776c544-ce83-4bee-bebd-2772ecbd6637
public int getInsulin() { return insulin; }
f32a5d02-40a9-45c8-96a2-874728da655c
public void setInsulin(int insulin) { this.insulin = insulin; }
ba11f4c2-48da-4c65-ae4c-cf0a426d5c57
public long getUserId() { return userId; }
66e55973-bce2-4faf-8a6a-96a1ce881198
public void setUserId(long userId) { this.userId = userId; }
f2ffbd3c-a3a8-4064-9b8e-ffdcd8cc0dca
public int getChatId() { return chatId; }
cb021f9f-259b-4068-adbe-a909c9accdf6
public void setChatId(int chatId) { this.chatId = chatId; }
ea5554e7-8d05-4402-9725-324f28ed67c2
public TidepoolDatabase() { URL = "jdbc:mysql://localhost:3306/tidepool"; driver = "com.mysql.jdbc.Driver"; user = "root"; passwd = "1111"; adapter = new JDBCadapter(URL, driver, user, passwd); }
3b525d34-6fc5-417f-b56a-d8ff4055c1ef
public User getUser(String email) { return adapter.selectUser(email); }
530f84e2-f9ef-42f8-b4b1-65cf41b8963e
public User getUser(long uid) { return adapter.selectUser(uid); }
e556ce98-f666-4379-8ed1-43ff9ea78b0d
public ArrayList<Data> getData(User user) { if(user.getRole().equalsIgnoreCase("patient")) return adapter.selectData(user.getId()); // Get the data of the patients associated with the parent ArrayList<User> friends = adapter.selectFriends((int)user.getId()); ArrayList<Data> data = new ArrayList<Data>(); for(User friend: friends) { data.addAll(adapter.selectData((int)friend.getId())); } return data; }
74db2f0b-763b-4fb4-b4c2-17935efe8144
public ArrayList<Data> getData(long user_id) { return adapter.selectData(user_id); }
bd967945-a569-4055-a3e8-3cf0b14fb899
public ArrayList<User> getFriends(long id) { return adapter.selectFriends(id); }
be98ffb5-eda3-4bb5-87c9-5abde0c2f210
public int addUser(User user) { return adapter.insertUser(user); }
aae3a12f-cbef-4ad6-9d84-cb1733462737
public int updateUser(User user) { return adapter.updateUser(user); }
30a48b35-a499-41cf-90e3-74073c214f3c
public void addFriend(long user_id, long friend_id) { adapter.insertFriends(user_id, friend_id); }
49612630-71ce-4048-bf89-1d54e42b1de2
public void deleteFriends(long id1, long id2) { adapter.deleteFriends(id1, id2); }
e52069fa-ef09-432c-8240-ff5627bb9b27
public int sendRequest(long sId, long rId) { return adapter.insertContact(sId, rId); }
37a848ed-db99-4275-a312-f204f06443fb
public ArrayList<User> getRequest(long rId) { return adapter.selectSender( rId ); }
7c218905-14cc-4c00-89a4-374ff9820b4e
public int setRespond(long sId, long rId, String status) { return adapter.updateContact(sId, rId, status); }
cba60125-145d-4631-8090-963945a4f16a
public ArrayList<User> getRespond(long sId) { return adapter.selectReceiver( sId ); }
b4aabb86-385c-49b9-b804-b4562ea0a230
public void close() throws SQLException { adapter.close(); }
d14ad5e7-055a-4fac-9644-e06be242014b
public JDBCadapter(String url, String driverName, String user, String passwd) { try { Class.forName(driverName); System.out.println("Opening db connection"); connection = DriverManager.getConnection(url, user, passwd); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } }
7011764a-60a5-46bd-9610-b2fbfb6f1447
public void close() throws SQLException { System.out.println("Closing db connection"); preparedStatement.close(); connection.close(); }
a4c7082a-6cdd-4a78-8888-d13fb78c8c98
public User selectUser( String email ) { User user = new User(); String query = "select * from myUser " + "where email = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, email); ResultSet rs = preparedStatement.executeQuery(); if( rs.next() ) { user.setId(rs.getInt("id")); user.setEmail(rs.getString("email")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("pwd")); user.setPhoneNo(rs.getString("phone")); user.setDateOfBirth(rs.getDate("birth")); user.setGender(rs.getString("gender")); user.setRole(rs.getString("role")); user.setLocation_lat(rs.getDouble("location_lat")); user.setLocation_lng(rs.getDouble("location_lng")); System.out.print("Reading user " + user.getUsername() + " success!" ); System.out.println(" Birthday is: " + user.getDateOfBirth()); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } return user; }
10c063e1-480d-4f62-9448-d1b17513b3da
public User selectUser(long uid) { User user = new User(); String query = "select * from myUser " + "where id = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, uid); ResultSet rs = preparedStatement.executeQuery(); if( rs.next() ) { user.setId(rs.getInt("id")); user.setEmail(rs.getString("email")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("pwd")); user.setPhoneNo(rs.getString("phone")); user.setDateOfBirth(rs.getDate("birth")); user.setGender(rs.getString("gender")); user.setRole(rs.getString("role")); user.setLocation_lat(rs.getDouble("location_lat")); user.setLocation_lng(rs.getDouble("location_lng")); System.out.print("Reading user " + user.getUsername() + " success!" ); System.out.println(" Birthday is: " + user.getDateOfBirth()); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } return user; }
04eb8aab-786b-4b63-91b0-49b93fcdeb73
public ArrayList<Data> selectData( long user_id ) { ArrayList<Data> dataList = new ArrayList<Data>(); String query = "select * from myData " + "where uid = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, user_id); ResultSet rs = preparedStatement.executeQuery(); while( rs.next() ) { Data data = new Data(); data.setId(rs.getInt("id")); data.setTime(rs.getTimestamp("theTime")); data.setBg(rs.getInt("BG")); data.setInsulin(rs.getInt("insulin")); data.setUserId(user_id); System.out.println("Time " + data.getTime() + " BG " + data.getBg() ); dataList.add(data); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } return dataList; }
3b0097f9-f1c0-439a-9411-41fd57314a63
public ArrayList<User> selectFriends( long id ) { ArrayList<User> friends = new ArrayList<User>(); friends.addAll( selectFriends(id, true) ); friends.addAll( selectFriends(id, false) ); return friends; }
7e1a1097-3a91-4627-964f-6018011f1d6b
private ArrayList<User> selectFriends( long user_id, boolean right ) { ArrayList<User> userList = new ArrayList<User>(); String query1 = "select * from myUser a " + "inner join friends b on a.id=b.uid1 " + "where b.uid2 = ?"; String query2 = "select * from myUser a " + "inner join friends b on a.id=b.uid2 " + "where b.uid1 = ?"; try { if(right) preparedStatement = connection.prepareStatement(query1); else preparedStatement = connection.prepareStatement(query2); preparedStatement.setLong(1, user_id); ResultSet rs = preparedStatement.executeQuery(); while( rs.next() ) { User user = new User(); user.setId(rs.getInt("id")); user.setEmail(rs.getString("email")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("pwd")); user.setPhoneNo(rs.getString("phone")); user.setDateOfBirth(rs.getDate("birth")); user.setGender(rs.getString("gender")); user.setRole(rs.getString("role")); System.out.print("Reading friend " + user.getUsername() + " success!" ); System.out.println(" Birthday is: " + user.getDateOfBirth()); userList.add(user); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } return userList; }
4209e953-b4fa-4897-a85a-1c7f21d9feef
public ArrayList<User> selectReceiver( long sender_id ) { ArrayList<User> userList = new ArrayList<User>(); String query = "select * from myUser a " + "inner join contact b on a.id=b.receiver " + "where not b.theStatus=\'wait\' and b.sender = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, sender_id); ResultSet rs = preparedStatement.executeQuery(); while( rs.next() ) { User user = new User(); String status = rs.getString("theStatus"); // Handle different respond if(status.equals("admit") ) { user.setId(rs.getInt("id")); user.setEmail(rs.getString("email")); user.setUsername(rs.getString("username")); user.setPhoneNo(rs.getString("phone")); user.setDateOfBirth(rs.getDate("birth")); user.setGender(rs.getString("gender")); user.setRole(rs.getString("role")); // Add to friends table insertFriends(sender_id, user.getId()); } else { user.setUsername(rs.getString("username")); } // Delete the handling request int contact_id = rs.getInt("contact_id"); deleteContact(contact_id); // For debug System.out.print("Reading contact " + user.getUsername() + " success!" ); System.out.println(" status is: " + status); userList.add(user); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } return userList; }
e64f3c2f-a86e-4a7a-8e6d-989be242c0dd
public ArrayList<User> selectSender( long receiver_id ) { ArrayList<User> userList = new ArrayList<User>(); String query = "select * from myUser a " + "inner join contact b on a.id=b.sender " + "where b.theStatus=\'wait\' and b.receiver = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, receiver_id); ResultSet rs = preparedStatement.executeQuery(); while( rs.next() ) { User user = new User(); String status = rs.getString("theStatus"); user.setId(rs.getInt("id")); user.setEmail(rs.getString("email")); user.setUsername(rs.getString("username")); user.setPhoneNo(rs.getString("phone")); user.setDateOfBirth(rs.getDate("birth")); user.setGender(rs.getString("gender")); user.setRole(rs.getString("role")); System.out.print("Reading contact " + user.getUsername() + " success!" ); System.out.println(" status is: " + status); userList.add(user); } rs.close(); } catch (SQLException ex) { ex.printStackTrace(); } return userList; }
090bcdac-9b56-4561-b2a1-77e5ef4c21f3
public int insertUser(User user) { int id = -1; String query = "INSERT IGNORE INTO myUser" + "(email, username, pwd, phone, birth, gender, role) VALUES" + "(?,?,?,?,?,?,?)"; try { preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); preparedStatement.setString(1, user.getEmail()); preparedStatement.setString(2, user.getUsername()); preparedStatement.setString(3, user.getPassword()); preparedStatement.setString(4, user.getPhoneNo()); preparedStatement.setDate(5, convertToSqlDate(user.getDateOfBirth())); preparedStatement.setString(6, user.getGender()); preparedStatement.setString(7, user.getRole()); // execute insert SQL statement preparedStatement.executeUpdate(); // return the auto generated key ResultSet rs = preparedStatement.getGeneratedKeys(); if(rs.next()){ id = rs.getInt(1); System.out.println("Record is inserted into myUser table!"); } else System.out.println("Fail to inserted record into myUser table!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return id; }
b60d2187-07bc-4d15-8a35-752f8bed63ad
public int insertFriends(long id1, long id2) { int id = -1; String query = "INSERT IGNORE INTO friends" + "(uid1, uid2) VALUES" + "(?,?)"; try { preparedStatement = connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); preparedStatement.setLong(1, (id1<id2? id1:id2)); preparedStatement.setLong(2, (id1>id2? id1:id2)); // execute insert SQL statement preparedStatement.executeUpdate(); // return the auto generated key ResultSet rs = preparedStatement.getGeneratedKeys(); if(rs.next()) id = rs.getInt(1); System.out.println("Record is inserted into friends table!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return id; }
337b6501-f890-4d9a-9591-5c06b3f90b4b
public int insertContact(long sId, long rId) { int count = -1; String query = "INSERT IGNORE INTO contact" + "(sender, receiver, theStatus) VALUES" + "(?,?,?)"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, sId); preparedStatement.setLong(2, rId); preparedStatement.setString(3, "wait"); // execute insert SQL statement count = preparedStatement.executeUpdate(); System.out.println("Add friends request is inserted into contact table!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; }
3614b86b-6918-48bf-b2cc-92bb79463242
public int updateUser(User user) { int ps = -1; String query = "UPDATE myUser SET " + "email = ?, username = ?, pwd = ?, phone = ?, birth = ?, gender = ?, role =?, " + "location_lat = ?, location_lng = ? " + "WHERE id = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, user.getEmail()); preparedStatement.setString(2, user.getUsername()); preparedStatement.setString(3, user.getPassword()); preparedStatement.setString(4, user.getPhoneNo()); preparedStatement.setDate(5, convertToSqlDate(user.getDateOfBirth())); preparedStatement.setString(6, user.getGender()); preparedStatement.setString(7, user.getRole()); preparedStatement.setDouble(8, user.getLocation_lat()); preparedStatement.setDouble(9, user.getLocation_lng()); preparedStatement.setLong(10, user.getId()); // execute insert SQL statement ps = preparedStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ps; }
f2e7596a-d18e-4184-9dce-0de516ff1204
public int updateContact(long sId, long rId, String status) { int ps = -1; String query = "UPDATE contact SET " + "theStatus = ? " + "WHERE sender = ? and receiver = ?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, status); preparedStatement.setLong(2, sId); preparedStatement.setLong(3, rId); // execute insert SQL statement ps = preparedStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ps; }
5f15ba0e-f2d6-46fb-8ad1-b291e5909b61
public void deleteFriends(long id1, long id2) { String query = "DELETE FROM friends WHERE uid1=? AND uid2=?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, (id1<id2? id1:id2)); preparedStatement.setLong(2, (id1>id2? id1:id2)); // execute insert SQL statement preparedStatement.executeUpdate(); System.out.println("Delete one data in friends table!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
b12518d0-62cc-49ef-b031-ef5ad2bbdbb0
public void deleteContact(long id) { String query = "DELETE FROM contact WHERE contact_id=?"; try { preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1, id); // execute insert SQL statement preparedStatement.executeUpdate(); System.out.println("Delete one data in contact table!"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
2e0b088b-f415-4a2c-a197-a5dcd61884e6
private java.sql.Date convertToSqlDate(java.util.Date date) { return new java.sql.Date(date.getTime()); }
0d05cd88-bcd0-4f78-99bf-76f1b015095e
public static Map<String, String> extractFrom(Document document) { collect(document); return contentItems; }
2dea9d07-11f5-433b-a056-2807037e745b
private static void collect(Node node) { if (node == null) return; if (node.getNodeName().equals("td")) { Node classAttribute = node.getAttributes().getNamedItem("class"); if (classAttribute == null) return; if (contentItems.containsKey(classAttribute.getNodeValue())) contentItems.put(classAttribute.getNodeValue(), node.getTextContent().trim()); } for (int i = 0; i < node.getChildNodes().getLength(); i++ ) collect(node.getChildNodes().item(i)); }
71b1214e-c83f-4c98-871a-49a062ea3012
public static void printRetrievedItems() { log.info("------------------------------------------------------------------------"); for (String key : contentItems.keySet()) if (contentItems.get(key) != null) log.info(key + " - " + contentItems.get(key)); log.info("------------------------------------------------------------------------"); }
b9799975-ae51-44fd-a14f-ef956f17daaf
public static boolean containsRepository(String name) throws ClassNotFoundException { return archives.containsKey(name); }
8f87539a-0652-4bf8-a66a-87fb95ba1256
public static String getDescriptionFor(String name) throws ClassNotFoundException { return (String) (archives.containsKey(name) ? archives.get(name) : null); }
6061db28-932a-4109-9a71-f3a51b5d18ae
public static void printArchiveList() { log.info("------------------------------------------------------------------------"); for (Object key : archives.keySet()) log.info(key + " - " + archives.get(key)); log.info("------------------------------------------------------------------------"); }
07036e04-6ea9-4df9-a1c6-36f81fd0ba62
public static OntModel createOntModel(URL url, Map<String, String> contentItems, Dataset dataset) { RDFBuilder.contentItems = contentItems; ontModel = dataset == null ? ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM) : ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, dataset.getDefaultModel()); ontModel.addSubModel(ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM) .read("http://erlangen-crm.org/onto/ecrm/ecrm_current.owl")); Individual image = createInformationCarrier(url); Individual endurant = createEndurant(image); createSpatials(endurant); createTemporals(endurant); return ontModel; }
3a2f2cd2-8d30-433e-9633-e8ef43c2d8eb
private static Individual createInformationCarrier(URL url) { Individual carrier = ontModel.getOntClass(CidocCRM.E84_Information_Carrier) .createIndividual(url.toExternalForm()); if (contentItems.get("rights_reproduction-field") != null) { Individual right = ontModel.getOntClass(CidocCRM.E30_Right) .createIndividual(contentItems.get("rights_reproduction-field")); carrier.addProperty(ontModel.getProperty(CidocCRM.P104_is_subject_to), right); right.addProperty(ontModel.getProperty(CidocCRM.P104i_applies_to), carrier); } if (contentItems.get("source-field") != null) addNote(carrier, "Database: " + contentItems.get("source-field")); if (contentItems.get("image_code-field") != null) addNote(carrier, "Image Code: " + contentItems.get("image_code-field")); if (contentItems.get("technique-field") != null || contentItems.get("artist-field") != null) { Individual production = ontModel.getOntClass(CidocCRM.E12_Production) .createIndividual(); if (contentItems.get("technique-field") != null) { Individual technique = ontModel.getOntClass(CidocCRM.E29_Design_or_Procedure) .createIndividual(contentItems.get("technique-field")); production.addProperty(ontModel.getProperty(CidocCRM.P33_used_specific_technique), technique); technique.addProperty(ontModel.getProperty(CidocCRM.P33i_was_used_by), production); } if (contentItems.get("artist-field") != null) { Individual artist = ontModel.getOntClass(CidocCRM.E39_Actor) .createIndividual(contentItems.get("artist-field")); production.addProperty(ontModel.getProperty(CidocCRM.P14_carried_out_by), artist); artist.addProperty(ontModel.getProperty(CidocCRM.P14i_performed), production); } } Individual image = ontModel.getOntClass(CidocCRM.E38_Image) .createIndividual("Image of " + contentItems.get("title-field")); carrier.addProperty(ontModel.getProperty(CidocCRM.P128_carries), image); image.addProperty(ontModel.getProperty(CidocCRM.P128i_is_carried_by), carrier); if (contentItems.get("keyword-field") != null) addNote(image, "Keyword: " + contentItems.get("keyword-field")); if (contentItems.get("description-field") != null) addNote(image, "Description: " + contentItems.get("description-field")); return image; }
56bbcc44-e2d3-4a5b-a23d-2ff5b161ba7b
private static Individual createEndurant(Individual image) { Individual endurant = ontModel.getOntClass(CidocCRM.E77_Persistent_Item) .createIndividual(contentItems.get("title-field")); image.addProperty(ontModel.getProperty(CidocCRM.P138_represents), endurant); endurant.addProperty(ontModel.getProperty(CidocCRM.P138i_has_representation), image); if (contentItems.get("material-field") != null) { Individual material = ontModel.getOntClass(CidocCRM.E57_Material) .createIndividual(contentItems.get("material-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P45_consists_of), material); material.addProperty(ontModel.getProperty(CidocCRM.P45i_is_incorporated_in), endurant); } if (contentItems.get("size-field") != null) { Individual size = ontModel.getOntClass(CidocCRM.E54_Dimension) .createIndividual(contentItems.get("size-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P43_has_dimension), size); size.addProperty(ontModel.getProperty(CidocCRM.P43i_is_dimension_of), endurant); } if (contentItems.get("credits-field") != null) addNote(endurant, "Credits: " + contentItems.get("credits-field")); if (contentItems.get("discoverycontext-field") != null) addNote(endurant, "Discoverycontext: " + contentItems.get("discoverycontext-field")); if (contentItems.get("inventory_no-field") != null) addNote(endurant, "Inventory No: " + contentItems.get("inventory_no-field")); if (contentItems.get("inscription-field") != null) addNote(endurant, "Inscription: " + contentItems.get("inscription-field")); if (contentItems.get("beneficiary_of_charter-field") != null) addNote(endurant, "Beneficiary Of Charter: " + contentItems.get("beneficiary_of_charter-field")); if (contentItems.get("edition-field") != null) addNote(endurant, "Edition: " + contentItems.get("edition-field")); if (contentItems.get("issuer_of_charter-field") != null) addNote(endurant, "Issuer Of Charter: " + contentItems.get("issuer_of_charter-field")); if (contentItems.get("negative_id-field") != null) addNote(endurant, "Negative: " + contentItems.get("negative_id-field")); if (contentItems.get("number_of_preserved_seals-field") != null) addNote(endurant, "Number Of Preserved Seals: " + contentItems.get("number_of_preserved_seals-field")); if (contentItems.get("original_number_of_seals-field") != null) addNote(endurant, "Original Number Of Seals: " + contentItems.get("original_number_of_seals-field")); if (contentItems.get("record_id-field") != null) addNote(endurant, "Record: " + contentItems.get("record_id-field")); if (contentItems.get("tradition-field") != null) addNote(endurant, "Tradition: " + contentItems.get("tradition-field")); if (contentItems.get("annotation-field") != null) addNote(endurant, "Annotation: " + contentItems.get("annotation-field")); if (contentItems.get("subtitle-field") != null) addNote(endurant, "Subtitle: " + contentItems.get("subtitle-field")); if (contentItems.get("description_source-field") != null) addNote(endurant, "Description Source: " + contentItems.get("description_source-field")); if (contentItems.get("caption-field") != null) addNote(endurant, "Caption: " + contentItems.get("caption-field")); if (contentItems.get("keyword_general-field") != null) addNote(endurant, "Keyword General: " + contentItems.get("keyword_general-field")); if (contentItems.get("pattern-field") != null) addNote(endurant, "Pattern: " + contentItems.get("pattern-field")); return endurant; }
ac47f8a1-1edb-4f1f-a289-842154f964a9
private static void createSpatials(Individual endurant) { if (contentItems.get("location-field") != null) { Individual location = ontModel.getOntClass(CidocCRM.E53_Place) .createIndividual(contentItems.get("location-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P53_has_former_or_current_location), location); location.addProperty(ontModel.getProperty(CidocCRM.P53i_is_former_or_current_location_of), endurant); Individual type = ontModel.getOntClass(CidocCRM.E55_Type) .createIndividual("location"); location.addProperty(ontModel.getProperty(CidocCRM.P2_has_type), type); type.addProperty(ontModel.getProperty(CidocCRM.P2i_is_type_of), location); } if (contentItems.get("location_building-field") != null) { Individual location_building = ontModel.getOntClass(CidocCRM.E53_Place) .createIndividual(contentItems.get("location_building-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P53_has_former_or_current_location), location_building); location_building.addProperty(ontModel.getProperty(CidocCRM.P53i_is_former_or_current_location_of), endurant); Individual type = ontModel.getOntClass(CidocCRM.E55_Type) .createIndividual("location building"); location_building.addProperty(ontModel.getProperty(CidocCRM.P2_has_type), type); type.addProperty(ontModel.getProperty(CidocCRM.P2i_is_type_of), location_building); } if (contentItems.get("depository-field") != null) { Individual depository = ontModel.getOntClass(CidocCRM.E53_Place) .createIndividual(contentItems.get("depository-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P53_has_former_or_current_location), depository); depository.addProperty(ontModel.getProperty(CidocCRM.P53i_is_former_or_current_location_of), endurant); Individual type = ontModel.getOntClass(CidocCRM.E55_Type) .createIndividual("depository"); depository.addProperty(ontModel.getProperty(CidocCRM.P2_has_type), type); type.addProperty(ontModel.getProperty(CidocCRM.P2i_is_type_of), depository); } if (contentItems.get("discoveryplace-field") != null) { Individual discoveryplace = ontModel.getOntClass(CidocCRM.E53_Place) .createIndividual(contentItems.get("discoveryplace-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P53_has_former_or_current_location), discoveryplace); discoveryplace.addProperty(ontModel.getProperty(CidocCRM.P53i_is_former_or_current_location_of), endurant); Individual type = ontModel.getOntClass(CidocCRM.E55_Type) .createIndividual("discoveryplace"); discoveryplace.addProperty(ontModel.getProperty(CidocCRM.P2_has_type), type); type.addProperty(ontModel.getProperty(CidocCRM.P2i_is_type_of), discoveryplace); } }
09a7f1f8-2000-43c5-917a-c56bd323e745
private static void createTemporals(Individual endurant) { if (contentItems.get("manufacture_place-field") != null || contentItems.get("epoch-field") != null || contentItems.get("date-field") != null) { Individual beginningOfExistence = ontModel.getOntClass(CidocCRM.E63_Beginning_of_Existence) .createIndividual(); beginningOfExistence.addProperty(ontModel.getProperty(CidocCRM.P92_brought_into_existence), endurant); endurant.addProperty(ontModel.getProperty(CidocCRM.P92i_was_brought_into_existence_by), beginningOfExistence); if (contentItems.get("manufacture_place-field") != null) { Individual manufacture_place = ontModel.getOntClass(CidocCRM.E53_Place) .createIndividual(contentItems.get("manufacture_place-field")); endurant.addProperty(ontModel.getProperty(CidocCRM.P53_has_former_or_current_location), manufacture_place); manufacture_place.addProperty(ontModel.getProperty(CidocCRM.P53i_is_former_or_current_location_of), endurant); } if (contentItems.get("epoch-field") != null || contentItems.get("date-field") != null) { Individual timespan = ontModel.getOntClass(CidocCRM.E52_Time_Span) .createIndividual(); beginningOfExistence.addProperty(ontModel.getProperty(CidocCRM.P4_has_time_span), timespan); timespan.addProperty(ontModel.getProperty(CidocCRM.P4i_is_time_span_of), beginningOfExistence); if (contentItems.get("epoch-field") != null) { Individual epoch = ontModel.getOntClass(CidocCRM.E49_Time_Appellation) .createIndividual(contentItems.get("epoch-field")); timespan.addProperty(ontModel.getProperty(CidocCRM.P78_is_identified_by), epoch); epoch.addProperty(ontModel.getProperty(CidocCRM.P78i_identifies), timespan); } if (contentItems.get("date-field") != null) { Individual date = ontModel.getOntClass(CidocCRM.E50_Date) .createIndividual(contentItems.get("date-field")); timespan.addProperty(ontModel.getProperty(CidocCRM.P78_is_identified_by), date); date.addProperty(ontModel.getProperty(CidocCRM.P78i_identifies), timespan); } } } }
76e66faf-f8e2-418c-9fd6-aeb2dd4c523b
private static void addNote(Individual individual, String text) { individual.addProperty(ontModel.getProperty(CidocCRM.P3_has_note), ontModel.createLiteral(text)); }
91c6c616-f176-46e8-84a3-fbd4c3b2efe2
public static void main( String[] args ) { Dataset dataset = null; try { if (args.length == 0 || args.length % 2 == 1) printUsage(); URL url = null; String archiveId = null; String itemId = null; String tdb = null; String file = null; try { for (int i = 0; i < args.length; i=i+2) { if (args[i].equals("-u") || args[i].equals("--url")) url = new URL(args[i+1]); else if (args[i].equals("-a") || args[i].equals("--archiveId")) archiveId = args[i+1]; else if (args[i].equals("-i") || args[i].equals("--itemId")) itemId = args[i+1]; else if (args[i].equals("-t") || args[i].equals("--tdb")) tdb = args[i+1]; else if (args[i].equals("-f") || args[i].equals("--file")) file = args[i+1]; else throw new Exception("Illegal option"); } } catch (Exception e) { printUsage(); } // if url given, no archiveId or itemId may be given // if url not given, both archiveId and itemId must be given if ((url != null && (archiveId != null || itemId != null)) || (url == null && (archiveId == null || itemId == null))) printUsage(); if (archiveId != null) if (!SourceManager.containsRepository(archiveId)) { log.error("For <archiveId> select one of:"); SourceManager.printArchiveList(); return; } else { url = new URL(baseUri + archiveId + "-" + itemId); } if (file != null) try { File f = new File(file); if (f.exists()) { log.error("The <file> " + file + " already exists"); return; } } catch (Exception e) { log.error("Error creating file " + file, e); printUsage(); } if (tdb != null) try { dataset = tdb.endsWith(".ttl") ? TDBFactory.assembleDataset(tdb) : TDBFactory.createDataset(tdb); } catch (Exception e) { log.error("Error creating tdb store " + tdb, e); printUsage(); } log.info("Requesting " + url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { log.info("Status OK: " + connection.getResponseCode()); } else { log.error(connection.getResponseCode() + ": Failed to fetch content for URL " + url); System.exit(-1); } log.info("Parsing content"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // retrieve the document first as a byte array InputStream is = connection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int next = is.read(); while (next > -1) { bos.write(next); next = is.read(); } bos.flush(); // we have the document as a byte array // now we can make a string with the content and replace invalid characters // needed because the document may not be valid xml and the sax parser demands it so DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse( new InputSource(new StringReader( new String(bos.toByteArray()).replaceAll( "&", "&amp;" )))); log.info("Extracting information"); Map<String, String> contentItems = InformationRetriever.extractFrom(document); log.info("Building RDF data"); if (dataset != null) { log.info("Writing RDF data to tdb " + tdb); RDFBuilder.createOntModel(url, contentItems, dataset).close(); dataset.close(); } OntModel model = null; if (file != null || dataset == null) model = RDFBuilder.createOntModel(url, contentItems, null); if (file != null) { FileWriter fileWriter = null; try { log.info("Writing RDF data to file " + file); fileWriter = new FileWriter(file); model.write(fileWriter, "N3"); } catch (Exception e) { log.error("Error creating file", e); printUsage(); } finally { try { if (file != null) fileWriter.close(); } catch (Exception ignore) {} } } if (file == null && dataset == null) model.write(System.out, "N3"); if (model != null) model.close(); log.info("Done"); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (dataset != null) dataset.close(); } }
5558575d-1920-40e7-a053-66b300522c6b
private static void printUsage() { log.info("------------------------------------------------------------------------"); log.info("Usage: ./run.sh (URL|IDS>) [OPTIONS]"); log.info(""); log.info("URL"); log.info(" -u (--url) <url>"); log.info(" retrieve the information from the url"); log.info(" For example: ./run.sh -u http://prometheus.uni-koeln.de/pandora/image/show/heidicon_aa-030fe7e5ee5b0ddcc11687e484a044d6181914f8"); log.info(" If url is given, none of archiveId or itemId may be specified"); log.info(""); log.info("IDS"); log.info(" -a (--archiveId) <archiveId>"); log.info(" specify a Prometheus image archive"); log.info(" -i (--itemId) <itemId>"); log.info(" specify an item within the given image archive"); log.info(" For example: ./run.sh -a heidicon_aa -i 030fe7e5ee5b0ddcc11687e484a044d6181914f8"); log.info(" Both archiveId and itemId must be given together, and no url may be specified"); log.info(""); log.info("OPTIONS"); log.info(" -t (--tdb) <tdb>"); log.info(" specify a tdb dataset to store the retrieved information"); log.info(" tdb is taken as a pathname. If it ends with .ttl, it is used as a tdb assembler filename"); log.info(" -f (--file) <filename>"); log.info(" specify a file to store the retrieved information"); log.info("------------------------------------------------------------------------"); System.exit(0); }
e730779d-b362-4d1a-835d-d4f40a5385b4
public void onSuccess(SearchResult result) { logger.debug("search keyword:{} found:{} totalTime:{}ms", new Object[] { result.getKeyword(), result.getRecords(), result.getTotalTime() }); }
49473393-946c-4ee1-9691-ebbe23f77be0
public void onFailure(Throwable thrown) { logger.warn(thrown.getMessage()); }
f695d69e-7516-4f09-b82c-ce4c8f1aa79f
public void runWithFutureCallback() { // asynchronous execution ListenableFuture<SearchResult> future1 = (ListenableFuture<SearchResult>) searchService.search("Joshua Bloch"); // !!! the keyword 'Martin Fowler' does not exist in the database ListenableFuture<SearchResult> future2 = (ListenableFuture<SearchResult>) searchService.search("Martin Fowler"); // try callback without polling Futures.addCallback(future1, showResult); Futures.addCallback(future2, showResult); asyncCountDown(future1, future2); }
57584870-a98f-4627-980e-25e562e7235d
public void runWithAsyncFunction() { // scatter-gather search List<String> terms = Arrays.asList(new String[] { "Joshua Bloch", "Martin Odersky", "Brian Goetz", "Bruce Eckel", "Martin Fowler" }); List<ListenableFuture<SearchResult>> futures = new ArrayList<ListenableFuture<SearchResult>>(); for (String term : terms) { futures.add((ListenableFuture<SearchResult>) searchService.search(term)); } // collect all of successful search results and merge AsyncFunction<List<SearchResult>, SearchResult> flattenFunction = new AsyncFunction<List<SearchResult>, SearchResult>() { public ListenableFuture<SearchResult> apply(List<SearchResult> results) { StringBuilder keywords = new StringBuilder(); Set<String> records = new HashSet<String>(); long startTime = Long.MAX_VALUE; long endTime = 0; for (SearchResult result : results) { if (result != null) { keywords.append(result.getKeyword()); records.addAll(result.getRecords()); startTime = Math.min(startTime, result.getStartTime()); endTime = Math.max(endTime, result.getEndTime()); } } SettableFuture<SearchResult> constFuture = SettableFuture.create(); constFuture.set(new SearchResult(keywords.toString(), new ArrayList<String>(records), startTime, endTime)); return constFuture; } }; ListenableFuture<List<SearchResult>> collectedResults = Futures.successfulAsList(futures); ListenableFuture<SearchResult> mergedResult = Futures.transform(collectedResults, flattenFunction); Futures.addCallback(mergedResult, showResult); asyncCountDown(mergedResult); }
7614535b-872f-4cc5-8c03-fc56dc7f99db
public ListenableFuture<SearchResult> apply(List<SearchResult> results) { StringBuilder keywords = new StringBuilder(); Set<String> records = new HashSet<String>(); long startTime = Long.MAX_VALUE; long endTime = 0; for (SearchResult result : results) { if (result != null) { keywords.append(result.getKeyword()); records.addAll(result.getRecords()); startTime = Math.min(startTime, result.getStartTime()); endTime = Math.max(endTime, result.getEndTime()); } } SettableFuture<SearchResult> constFuture = SettableFuture.create(); constFuture.set(new SearchResult(keywords.toString(), new ArrayList<String>(records), startTime, endTime)); return constFuture; }
489a60cd-7d5a-44cd-9f4e-0795ffc7323a
public void await() throws InterruptedException { countDownLatch.await(); }
8b467945-efbe-4bc4-8f0a-92c322649234
public <V> void asyncCountDown(ListenableFuture<? extends V>... futures) { Futures.successfulAsList(futures).addListener(new Runnable() { public void run() { countDownLatch.countDown(); } }, MoreExecutors.sameThreadExecutor()); }
2467cdd9-4f11-4eb0-a5e1-30f0d7293605
public void run() { countDownLatch.countDown(); }
0aa6bf24-d608-44ae-afbc-9bde95959e54
public static void main(String[] args) { logger.info("starting application"); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "application-context.xml" }); SearchApplication application = (SearchApplication) context.getBean("searchApplication"); application.runWithFutureCallback(); application.runWithAsyncFunction(); // waiting for all asynchronous execution to complete try { application.await(); logger.info("leaving application"); context.destroy(); } catch (InterruptedException e) { // nothing special } }
e957c971-e30d-4a0b-b0c7-de0fe453b291
SearchService() { database.put("Joshua Bloch", Arrays.asList("Effective Java", "Java Concurrency in Practice", "JavaTM Puzzlers", "Java Concurrency in Practice")); database.put("Martin Odersky", Arrays.asList("Programming in Scala")); database.put("Brian Goetz", Arrays.asList("Java Concurrency in Practice")); database.put("Bruce Eckel", Arrays.asList("Thinking in Java", "Thinking in C++")); }
9df43adc-9be3-461e-a78c-44ad55efcae7
@Async public Future<SearchResult> search(String keyword) { logger.debug("search keyword:{}", keyword); long startTime = System.currentTimeMillis(); try { // simulate network latency Thread.sleep(ThreadLocalRandom.current().nextInt(10) * 1000); } catch (InterruptedException e) { e.printStackTrace(); } List<String> records = database.get(keyword); long endTime = System.currentTimeMillis(); if (records != null) { return new AsyncResult<SearchResult>(new SearchResult(keyword, records, startTime, endTime)); } else { throw new NotFound("the keyword '" + keyword + "'did not match any records"); } }
0594bdea-cf74-404a-8511-4b9b127fb033
SearchResult(String keyword, List<String> records, long startTime, long endTime) { this.keyword = keyword; this.records = records; this.startTime = startTime; this.endTime = endTime; }
ec16d456-68f3-4a73-8a78-163f34174dec
public String getKeyword() { return keyword; }
9cb9eca6-cfec-425a-a458-9a68e6a6cfe9
public List<String> getRecords() { return records; }
902f7950-51c7-44ef-9388-c6d039c29086
public long getStartTime() { return startTime; }
702116e2-037c-4ec9-bd7f-f773ac2ab886
public long getEndTime() { return endTime; }
1312eec9-fbbb-4c1a-8930-0b7991ba0849
public long getTotalTime() { return endTime - startTime; }
1011de43-3386-4d8a-9129-6b0ab7a556b8
NotFound(String msg) { super(msg); }
80715402-01ca-4bcf-95cb-ca054f204e65
@Override public Future<?> submit(Runnable task) { ListeningExecutorService executor = MoreExecutors.listeningDecorator(getThreadPoolExecutor()); try { return executor.submit(task); } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex); } }
8cc3c4c9-7ca7-4a0c-9ba6-e58b63366dce
@Override public <T> Future<T> submit(Callable<T> task) { ListeningExecutorService executor = MoreExecutors.listeningDecorator(getThreadPoolExecutor()); try { return executor.submit(task); } catch (RejectedExecutionException ex) { throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex); } }
ef9eb2a4-dd13-4882-8931-e816eca6adf9
@Test public void testReturnListenableFuture() { Future<String> pong = service.ping(); assertThat(pong, instanceOf(ListenableFuture.class)); }
6608ebd1-5af7-4b99-9f27-5ec3ac675dda
@Test public void testSuccessfulResult() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ListenableFuture<String> pong = (ListenableFuture<String>) service.ping(); final AtomicReference<String> deferredResult = new AtomicReference<String>(); FutureCallback<String> callback = new FutureCallback<String>() { public void onSuccess(String result) { deferredResult.set(result); latch.countDown(); } public void onFailure(Throwable t) { // ignored } }; Futures.addCallback(pong, callback); latch.await(2, TimeUnit.SECONDS); assertThat(deferredResult.get(), is("pong")); }
9e8b8d59-1f56-4f8f-a07f-3f73bf4064fd
public void onSuccess(String result) { deferredResult.set(result); latch.countDown(); }
36498d7b-7696-4b54-baff-d9b0e0f22e9b
public void onFailure(Throwable t) { // ignored }
a422255f-6400-4c5d-ad97-a998877fa4a4
@Test public void testFailureResult() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ListenableFuture<String> boom = (ListenableFuture<String>) service.bang(); final AtomicReference<String> deferredResult = new AtomicReference<String>(); FutureCallback<String> callback = new FutureCallback<String>() { public void onSuccess(String result) { // ignored } public void onFailure(Throwable t) { latch.countDown(); } }; Futures.addCallback(boom, callback); latch.await(2, TimeUnit.SECONDS); assertThat(deferredResult.get(), is(nullValue())); Exception rootCause = null; try { boom.get(); fail("should throw the boom excpetion"); } catch (ExecutionException e) { rootCause = (Exception) e.getCause(); } assertThat(rootCause, not(nullValue())); assertThat(rootCause, instanceOf(RuntimeException.class)); assertThat(rootCause.getMessage(), is("boom!")); }
a6b32c3f-7c93-4561-819e-a6aa7a61cd1f
public void onSuccess(String result) { // ignored }
a2b8b751-cbbb-4181-a811-085c86c143b1
public void onFailure(Throwable t) { latch.countDown(); }
92f9d959-3927-42aa-8c92-220623cef70b
@Async public Future<String> ping() { return new AsyncResult<String>("pong"); }
8813003e-748d-4c11-b814-48649815cbdb
@Async public Future<String> bang() { throw new RuntimeException("boom!"); }
6c2ab1ba-868c-431e-801c-7fa22079a8ca
public void accumulate(String expr) { try { int value = evaluator.eval(expr); if (value < 0) { //Ignore we don't care about negative values. return; } expressionReductions.add(value); } catch (ArithmeticException e) { //Ignore Divide by zero Error } }
76d3badf-2363-4c07-96a3-bd40a7db4f59
public Set<Integer> getReductions() { return expressionReductions; }
61b8e3fa-4f0b-4c2a-a57e-2e62d61600a0
public Integer getFirstMinimumImpossibleNumber() { if (this.expressionReductions.isEmpty()) { return 0; } if (this.expressionReductions.size() == 1) { return expressionReductions.first() + 1; } int index = 0, seqLen = this.expressionReductions.size(); Integer[] values = this.expressionReductions.toArray(new Integer[0]); int currNum, nextNum; while (index < seqLen) { currNum = values[index]; nextNum = values[index + 1]; if (nextNum - currNum != 1) { return currNum + 1; } index++; } return values[index - 1] + 1; }
c3fd2d0e-9b15-4fbb-9f6f-2f49db676be5
public AssociationGenrator(String... tokens) { tokenStrings = new ArrayList<>(); tokenStrings.addAll(Arrays.asList(tokens)); }
3c73f3e2-1d57-462e-b6f9-bf6d371fa17d
public List<String> getAssociations() { return getAssociations_(tokenStrings); }
777e5977-3be2-4c88-b4f2-d0b7e0b31f3b
protected List<String> getAssociations_(List<String> tokens) { List<String> res = new ArrayList<>(); if (1 == tokens.size()) { res.add(tokens.get(0)); } else { for (int i = 0; i < tokens.size(); ++i) { List<String> left = tokens.subList(0, i), right = tokens.subList(i, tokens.size()); for (String l : getAssociations_(left)) { for (String r : getAssociations_(right)) { res.add("(".concat(l).concat(" %s ").concat(r).concat(")")); } } } } return res; }
ec71c8bc-85a6-4fcf-a08e-4b3a7d35fb76
public OperatorSequenceGenrator(int operatorBoxCount) { if (operatorBoxCount < 0) { throw new IllegalArgumentException("count can't be negative!"); } this.operatorBoxCount = operatorBoxCount; }
b5e8e1c6-51d6-44f5-90fd-0e8139e0b0d0
List<String> getSequence() { List<String> sequence = new ArrayList<>(); /** * Maintain index for each box and initialize to zero. */ List<Integer> indicies = new ArrayList<>(operatorBoxCount); for (int i = 0; i < operatorBoxCount; ++i) { indicies.add(0); } boolean stopFlag = false; while (true) { stopFlag = true; for (int index : indicies) { stopFlag &= index == OPERATORS_LEN - 1; } StringBuilder builder = new StringBuilder(); for (int index : indicies) { builder.append(OPERATORS.charAt(index)); } sequence.add(builder.toString()); if (stopFlag) { break; } int iix = 0; while (this.operatorBoxCount > iix) { indicies.set(iix, (indicies.get(iix) + 1) % OPERATORS_LEN); if (indicies.get(iix) > 0) { break; } iix++; } } return sequence; }