file_id
int64
1
250k
content
stringlengths
0
562k
repo
stringlengths
6
115
path
stringlengths
1
147
248,588
package models; import play.db.ebean.Model; import javax.persistence.*; import java.util.Date; import java.util.List; @Entity public class Contest extends Model { @Id public Long id; public String title; public String description; public Date beginTime; public int duration; // minutes public boolean isPublic; public String password; @ManyToOne public User manager; public int status = 1; // 0 normal; 1 editing; 2 pending; 3 view only; 4 deleted; @OneToMany(mappedBy = "contest") public List<ContestParticipant> participants; @OneToMany(mappedBy = "contest") public List<ContestProblem> problems; @OneToMany(mappedBy = "contest") public List<Solution> solutions; @OneToMany(mappedBy = "contest") public List<Discussion> discussions; public Date createTime = new Date(); public static Finder<Long, Contest> find = new Finder<>(Long.class, Contest.class); }
OrangeJudge/oj_web
app/models/Contest.java
248,589
package com.yixun.manager; public class Contact { public String number,name,sex,words,isContact,discussions; public Contact(String num,String na,String se,String words,String is,String dis){ number=num; name=na; sex=se; this.words=words; isContact=is; discussions=dis; } public Contact(){ } }
mingyangShang/YiXun
manager/Contact.java
248,591
/* * The MIT License * * Copyright (c) 2008-2011, Sun Microsystems, Inc., Alan Harder, Jerome Lacoste, Kohsuke Kawaguchi, * bap2000, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package executable; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UncheckedIOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.MissingResourceException; import java.util.NavigableSet; import java.util.TreeSet; import java.util.UUID; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * Launcher class for stand-alone execution of Jenkins as * {@code java -jar jenkins.war}. * * <p>On a high-level architectural note, this class is intended to be a very thin wrapper whose * primary purpose is to extract Winstone and delegate to Winstone's own initialization mechanism. * The logic in this class should only perform Jenkins-specific argument and environment validation * and Jenkins-specific Winstone customization prior to delegating to Winstone. * * <p>In particular, managing the logging subsystem is completely delegated to Winstone, and this * class should neither assume that logging has been initialized nor take advantage of the logging * subsystem. In the event that this class needs to print information to the user, it should do so * via the standard output (stdout) and standard error (stderr) streams rather than via the logging * subsystem. Such messages should generally be avoided except for fatal scenarios, such as an * inappropriate Java Virtual Machine (JVM) or some other serious failure that would preclude * starting Winstone. * * @author Kohsuke Kawaguchi */ public class Main { /** * This list must remain synchronized with the one in {@code * JavaVersionRecommendationAdminMonitor}. */ private static final NavigableSet<Integer> SUPPORTED_JAVA_VERSIONS = new TreeSet<>(List.of(17, 21)); /** * Sets custom session cookie name. * It may be used to prevent randomization of JSESSIONID cookies and issues like * <a href="https://issues.jenkins-ci.org/browse/JENKINS-25046">JENKINS-25046</a>. * @since 2.66 */ private static final String JSESSIONID_COOKIE_NAME = System.getProperty("executableWar.jetty.sessionIdCookieName"); /** * Disables usage of the custom cookie names when starting the WAR file. * If the flag is specified, the session ID will be defined by the internal Jetty logic. * In such case it becomes configurable via * <a href="http://www.eclipse.org/jetty/documentation/9.4.x/jetty-xml-config.html">Jetty XML Config file</a>> * or via system properties. * @since 2.66 */ private static final boolean DISABLE_CUSTOM_JSESSIONID_COOKIE_NAME = Boolean.getBoolean("executableWar.jetty.disableCustomSessionIdCookieName"); /** * Flag to bypass the Java version check when starting. */ private static final String ENABLE_FUTURE_JAVA_CLI_SWITCH = "--enable-future-java"; /*package*/ static void verifyJavaVersion(int releaseVersion, boolean enableFutureJava) { if (SUPPORTED_JAVA_VERSIONS.contains(releaseVersion)) { // Great! } else if (releaseVersion >= SUPPORTED_JAVA_VERSIONS.first()) { if (enableFutureJava) { System.err.printf( "Running with Java %d from %s, which is not fully supported. " + "Continuing because %s is set. " + "Supported Java versions are: %s. " + "See https://jenkins.io/redirect/java-support/ for more information.%n", releaseVersion, System.getProperty("java.home"), ENABLE_FUTURE_JAVA_CLI_SWITCH, SUPPORTED_JAVA_VERSIONS); } else if (releaseVersion > SUPPORTED_JAVA_VERSIONS.last()) { throw new UnsupportedClassVersionError( String.format( "Running with Java %d from %s, which is not yet fully supported.%n" + "Run the command again with the %s flag to enable preview support for future Java versions.%n" + "Supported Java versions are: %s", releaseVersion, System.getProperty("java.home"), ENABLE_FUTURE_JAVA_CLI_SWITCH, SUPPORTED_JAVA_VERSIONS)); } else { throw new UnsupportedClassVersionError( String.format( "Running with Java %d from %s, which is not fully supported.%n" + "Run the command again with the %s flag to bypass this error.%n" + "Supported Java versions are: %s", releaseVersion, System.getProperty("java.home"), ENABLE_FUTURE_JAVA_CLI_SWITCH, SUPPORTED_JAVA_VERSIONS)); } } else { throw new UnsupportedClassVersionError( String.format( "Running with Java %d from %s, which is older than the minimum required version (Java %d).%n" + "Supported Java versions are: %s", releaseVersion, System.getProperty("java.home"), SUPPORTED_JAVA_VERSIONS.first(), SUPPORTED_JAVA_VERSIONS)); } } /** * Returns true if the Java runtime version check should not be done, and any version allowed. * * @see #ENABLE_FUTURE_JAVA_CLI_SWITCH */ private static boolean isFutureJavaEnabled(String[] args) { return hasArgument(ENABLE_FUTURE_JAVA_CLI_SWITCH, args) || Boolean.parseBoolean(System.getenv("JENKINS_ENABLE_FUTURE_JAVA")); } // TODO: Rework everything to use List private static boolean hasArgument(@NonNull String argument, @NonNull String[] args) { for (String arg : args) { if (argument.equals(arg)) { return true; } } return false; } @SuppressFBWarnings( value = "PATH_TRAVERSAL_IN", justification = "User provided values for running the program") public static void main(String[] args) throws IllegalAccessException { try { verifyJavaVersion(Runtime.version().feature(), isFutureJavaEnabled(args)); } catch (UnsupportedClassVersionError e) { System.err.println(e.getMessage()); System.err.println("See https://jenkins.io/redirect/java-support/ for more information."); System.exit(1); } //Allows to pass arguments through stdin to "hide" sensitive parameters like httpsKeyStorePassword //to achieve this use --paramsFromStdIn if (hasArgument("--paramsFromStdIn", args)) { System.out.println("--paramsFromStdIn detected. Parameters are going to be read from stdin. Other parameters passed directly will be ignored."); String argsInStdIn; try { argsInStdIn = new String(System.in.readNBytes(131072), StandardCharsets.UTF_8).trim(); } catch (IOException e) { throw new UncheckedIOException(e); } args = argsInStdIn.split(" +"); } // If someone just wants to know the version, print it out as soon as possible, with no extraneous file or webroot info. // This makes it easier to grab the version from a script final List<String> arguments = new ArrayList<>(List.of(args)); if (arguments.contains("--version")) { System.out.println(getVersion("?")); return; } File extractedFilesFolder = null; for (String arg : args) { if (arg.startsWith("--extractedFilesFolder=")) { extractedFilesFolder = new File(arg.substring("--extractedFilesFolder=".length())); if (!extractedFilesFolder.isDirectory()) { System.err.println("The extractedFilesFolder value is not a directory. Ignoring."); extractedFilesFolder = null; } } } for (String arg : args) { if (arg.startsWith("--pluginroot=")) { System.setProperty("hudson.PluginManager.workDir", new File(arg.substring("--pluginroot=".length())).getAbsolutePath()); // if specified multiple times, the first one wins break; } } // this is so that JFreeChart can work nicely even if we are launched as a daemon System.setProperty("java.awt.headless", "true"); File me = whoAmI(extractedFilesFolder); System.out.println("Running from: " + me); System.setProperty("executable-war", me.getAbsolutePath()); // remember the location so that we can access it from within webapp // figure out the arguments trimOffOurOptions(arguments); arguments.add(0, "--warfile=" + me.getAbsolutePath()); if (!hasOption(arguments, "--webroot=")) { // defaults to ~/.jenkins/war since many users reported that cron job attempts to clean up // the contents in the temporary directory. final File jenkinsHome = getJenkinsHome(); final File webRoot = new File(jenkinsHome, "war"); System.out.println("webroot: " + webRoot); arguments.add("--webroot=" + webRoot); } // only do a cleanup if you set the extractedFilesFolder property. if (extractedFilesFolder != null) { deleteContentsFromFolder(extractedFilesFolder, "winstone.*\\.jar"); } // put winstone jar in a file system so that we can load jars from there File tmpJar = extractFromJar("winstone.jar", "winstone", ".jar", extractedFilesFolder); tmpJar.deleteOnExit(); // clean up any previously extracted copy, since // winstone doesn't do so and that causes problems when newer version of Jenkins // is deployed. File tempFile; try { tempFile = File.createTempFile("dummy", "dummy"); } catch (IOException e) { throw new UncheckedIOException(e); } deleteWinstoneTempContents(new File(tempFile.getParent(), "winstone/" + me.getName())); if (!tempFile.delete()) { System.err.println("Failed to delete temporary file: " + tempFile); } // locate the Winstone launcher ClassLoader cl; try { cl = new URLClassLoader("Jenkins Main ClassLoader", new URL[] {tmpJar.toURI().toURL()}, ClassLoader.getSystemClassLoader()); } catch (MalformedURLException e) { throw new UncheckedIOException(e); } Class<?> launcher; Method mainMethod; try { launcher = cl.loadClass("winstone.Launcher"); mainMethod = launcher.getMethod("main", String[].class); } catch (ClassNotFoundException | NoSuchMethodException e) { throw new AssertionError(e); } // override the usage screen Field usage; try { usage = launcher.getField("USAGE"); } catch (NoSuchFieldException e) { throw new AssertionError(e); } usage.set(null, "Jenkins Automation Server Engine " + getVersion("") + "\n" + "Usage: java -jar jenkins.war [--option=value] [--option=value]\n" + "\n" + "Options:\n" + " --webroot = folder where the WAR file is expanded into. Default is ${JENKINS_HOME}/war\n" + " --pluginroot = folder where the plugin archives are expanded into. Default is ${JENKINS_HOME}/plugins\n" + " (NOTE: this option does not change the directory where the plugin archives are stored)\n" + " --extractedFilesFolder = folder where extracted files are to be located. Default is the temp folder\n" + " " + ENABLE_FUTURE_JAVA_CLI_SWITCH + " = allows running with Java versions which are not fully supported\n" + " --paramsFromStdIn = Read parameters from standard input (stdin)\n" + " --version = Print version to standard output (stdout) and exit\n" + "{OPTIONS}"); if (!DISABLE_CUSTOM_JSESSIONID_COOKIE_NAME) { /* Set an unique cookie name. As can be seen in discussions like http://stackoverflow.com/questions/1146112/jsessionid-collision-between-two-servers-on-same-ip-but-different-ports and http://stackoverflow.com/questions/1612177/are-http-cookies-port-specific, RFC 2965 says cookies from one port of one host may be sent to a different port of the same host. This means if someone runs multiple Jenkins on different ports of the same host, their sessions get mixed up. To fix the problem, use unique session cookie name. This change breaks the cluster mode of Winstone, as all nodes in the cluster must share the same session cookie name. Jenkins doesn't support clustered operation anyway, so we need to do this here, and not in Winstone. */ try { Field f = cl.loadClass("winstone.WinstoneSession").getField("SESSION_COOKIE_NAME"); f.setAccessible(true); if (JSESSIONID_COOKIE_NAME != null) { // Use the user-defined cookie name f.set(null, JSESSIONID_COOKIE_NAME); } else { // Randomize session names by default to prevent collisions when running multiple Jenkins instances on the same host. f.set(null, "JSESSIONID." + UUID.randomUUID().toString().replace("-", "").substring(0, 8)); } } catch (ClassNotFoundException | NoSuchFieldException e) { throw new AssertionError(e); } } // run Thread.currentThread().setContextClassLoader(cl); try { mainMethod.invoke(null, new Object[] {arguments.toArray(new String[0])}); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else if (t instanceof IOException) { throw new UncheckedIOException((IOException) t); } else if (t instanceof Exception) { throw new RuntimeException(t); } else if (t instanceof Error) { throw (Error) t; } else { throw new RuntimeException(e); } } } private static void trimOffOurOptions(List<String> arguments) { arguments.removeIf(arg -> arg.startsWith("--extractedFilesFolder") || arg.startsWith("--pluginroot") || arg.startsWith(ENABLE_FUTURE_JAVA_CLI_SWITCH)); } /** * Figures out the version from the manifest. */ private static String getVersion(String fallback) { try { Enumeration<URL> manifests = Main.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL res = manifests.nextElement(); Manifest manifest = new Manifest(res.openStream()); String v = manifest.getMainAttributes().getValue("Jenkins-Version"); if (v != null) { return v; } } } catch (IOException e) { throw new UncheckedIOException(e); } return fallback; } private static boolean hasOption(List<String> args, String prefix) { for (String s : args) { if (s.startsWith(prefix)) { return true; } } return false; } /** * Figures out the URL of {@code jenkins.war}. */ @SuppressFBWarnings(value = {"PATH_TRAVERSAL_IN", "URLCONNECTION_SSRF_FD"}, justification = "User provided values for running the program.") public static File whoAmI(File directory) { // JNLP returns the URL where the jar was originally placed (like http://jenkins-ci.org/...) // not the local cached file. So we need a rather round about approach to get to // the local file name. // There is no portable way to find where the locally cached copy // of jenkins.war/jar is; JDK 6 is too smart. (See JENKINS-2326.) try { URL classFile = Main.class.getClassLoader().getResource("executable/Main.class"); JarFile jf = ((JarURLConnection) classFile.openConnection()).getJarFile(); return new File(jf.getName()); } catch (Exception x) { System.err.println("ZipFile.name trick did not work, using fallback: " + x); } File myself; try { myself = File.createTempFile("jenkins", ".jar", directory); } catch (IOException e) { throw new UncheckedIOException(e); } myself.deleteOnExit(); try (InputStream is = Main.class.getProtectionDomain().getCodeSource().getLocation().openStream(); OutputStream os = new FileOutputStream(myself)) { is.transferTo(os); } catch (IOException e) { throw new UncheckedIOException(e); } return myself; } /** * Extract a resource from jar, mark it for deletion upon exit, and return its location. */ @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "User provided values for running the program.") private static File extractFromJar(String resource, String fileName, String suffix, File directory) { URL res = Main.class.getResource(resource); if (res == null) { throw new MissingResourceException("Unable to find the resource: " + resource, Main.class.getName(), resource); } // put this jar in a file system so that we can load jars from there File tmp; try { tmp = File.createTempFile(fileName, suffix, directory); } catch (IOException e) { String tmpdir = directory == null ? System.getProperty("java.io.tmpdir") : directory.getAbsolutePath(); throw new UncheckedIOException("Jenkins failed to create a temporary file in " + tmpdir + ": " + e, e); } try (InputStream is = res.openStream(); OutputStream os = new FileOutputStream(tmp)) { is.transferTo(os); } catch (IOException e) { throw new UncheckedIOException(e); } tmp.deleteOnExit(); return tmp; } /** * Search contents to delete in a folder that match with some patterns. * * @param folder folder where the contents are. * @param patterns patterns that identifies the contents to search. */ private static void deleteContentsFromFolder(File folder, final String... patterns) { File[] files = folder.listFiles(); if (files != null) { for (File file : files) { for (String pattern : patterns) { if (file.getName().matches(pattern)) { deleteWinstoneTempContents(file); } } } } } private static void deleteWinstoneTempContents(File file) { if (!file.exists()) { return; } if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { // be defensive for (File value : files) { deleteWinstoneTempContents(value); } } } if (!file.delete()) { System.err.println("Failed to delete temporary Winstone file: " + file); } } /** * Determines the home directory for Jenkins. * <p> * People makes configuration mistakes, so we are trying to be nice * with those by doing {@link String#trim()}. */ @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "User provided values for running the program.") private static File getJenkinsHome() { // check the system property for the home directory first for (String name : HOME_NAMES) { String sysProp = System.getProperty(name); if (sysProp != null) { return new File(sysProp.trim()); } } // look at the env var next for (String name : HOME_NAMES) { String env = System.getenv(name); if (env != null) { return new File(env.trim()); } } // otherwise pick a place by ourselves File legacyHome = new File(new File(System.getProperty("user.home")), ".hudson"); if (legacyHome.exists()) { return legacyHome; // before rename, this is where it was stored } return new File(new File(System.getProperty("user.home")), ".jenkins"); } private static final String[] HOME_NAMES = {"JENKINS_HOME", "HUDSON_HOME"}; }
jenkinsci/jenkins
war/src/main/java/executable/Main.java
248,592
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package workshopdbPI.services; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import workshopdbPI.entities.Discussion; import workshopdbPI.utils.Mydb1; /** * * @author Hajbi */ public class DiscussionService { Connection connexion; public DiscussionService() { connexion = Mydb1.getInstance().getConnection(); } public void ajouterDiscussion(Discussion d) throws SQLException { String req=" INSERT INTO `Discussion` (`nom`,`sujet`) VALUES ('"+d.getNom()+"','"+d.getSujet()+"')"; Statement stm= connexion.createStatement(); stm.executeUpdate(req); } public List<Discussion> getAllDiscussions() throws SQLException { List<Discussion> discussions = new ArrayList <>(); String req="select * from Discussion"; Statement stm= connexion.createStatement(); ResultSet rst = stm.executeQuery(req); while(rst.next()){ Discussion d =new Discussion(rst.getInt("idD"),rst.getString("nom"),rst.getString("sujet")); discussions.add(d); } return discussions; } public void modifierDiscussion(int i,Discussion d) throws SQLException{ String req=" update discussion set nom=? ,sujet=? WHERE idD=?"; String query=" select * from discussion WHERE idD="+i; PreparedStatement ps=connexion.prepareStatement(req); Statement stm=connexion.createStatement(); ResultSet res=stm.executeQuery(query); if(res.next()) { ps.setString(1,d.getNom()); ps.setString(2,d.getSujet()); ps.setInt(3,i); ps.executeUpdate(); System.out.println("update terminé "); } else System.out.println("discussion inexistante"); } public void modifierDiscussion1(int i, String s1) throws SQLException{ String req=" update discussion set nom=? WHERE idD=? "; String query=" select * from discussion WHERE idD="+i; PreparedStatement ps=connexion.prepareStatement(req); Statement stm=connexion.createStatement(); ResultSet res=stm.executeQuery(query); if(res.next()) { ps.setString(1,s1); ps.setInt(2,i); ps.executeUpdate(); System.out.println("nom modifié"); } else System.out.println("discussion inexistante"); } public void modifierDiscussion2(int i, String s2) throws SQLException{ String req=" update discussion set sujet=? WHERE idD=? "; String query=" select * from discussion WHERE idD="+i; PreparedStatement ps=connexion.prepareStatement(req); Statement stm=connexion.createStatement(); ResultSet res=stm.executeQuery(query); if(res.next()) { ps.setString(1,s2); ps.setInt(2,i); ps.executeUpdate(); System.out.println("sujet modifié"); } else System.out.println("discussion inexistante"); } public void supprimerDiscussion(int i) throws SQLException{ String req = "DELETE FROM discussion WHERE idD=?"; PreparedStatement ps = connexion.prepareStatement(req); ps.setInt(1,i); ps.executeUpdate(); System.out.println("Discussion supprimée !"); } }
OnsBellazreg/Esprit-Entre-aide
DiscussionService.java
248,593
package cnvtgTelnet; /* * Copyright (C) 2017 zephray * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * * @author zephray */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; public class FlarumInterface { private Connection dbConnect = null; private Statement dbStatement = null; private ResultSet dbResultSet = null; private final String serverAddr; private final String serverUser; private final String serverPass; private final String dbName; public FlarumInterface(String serverAddr, String serverUser, String serverPass, String dbName) { this.serverAddr = serverAddr; this.serverUser = serverUser; this.serverPass = serverPass; this.dbName = dbName; } private void connectDB() throws Exception { Class.forName("com.mysql.jdbc.Driver"); dbConnect = DriverManager.getConnection( "jdbc:mysql://"+serverAddr+"/"+dbName, serverUser, serverPass ); dbStatement = dbConnect.createStatement(); } private void closeDB() { try { if (dbResultSet != null) { dbResultSet.close(); } if (dbStatement != null) { dbStatement.close(); } if (dbConnect != null) { dbConnect.close(); } } catch (Exception e) { } } public String[] verifyIP(String ip) throws Exception { if ((ip.indexOf(' ')!=-1) || (ip.indexOf(';')!=-1) || (ip.indexOf('\"')!=-1) || (ip.indexOf('\'')!=-1)) return null; this.connectDB(); try { String sql = "SELECT fl_telnet_access_tokens.access_token, fl_users.username FROM fl_telnet_access_tokens " + "INNER JOIN fl_users " + "ON fl_users.id = fl_telnet_access_tokens.user_id " + "WHERE fl_telnet_access_tokens.remote_addr = \"" + ip +"\""; dbResultSet = dbStatement.executeQuery(sql); if (dbResultSet.next()) { String token = dbResultSet.getString("access_token"); String username = dbResultSet.getString("username"); this.closeDB(); String[] cred = new String[2]; cred[0] = username; cred[1] = token; return cred; } else { this.closeDB(); return null; } } catch(SQLException se) { this.closeDB(); throw se; } } public Discussion[] getDiscussions() throws Exception { Discussion[] discussionSet; this.connectDB(); try { String sql; int discussionCount; sql = "SELECT fl_discussions.id, fl_discussions.title, " + " fl_discussions.comments_count, fl_discussions.last_time, " + " fl_discussions.start_user_id, fl_discussions.last_user_id, " + " fl_discussions.is_sticky, " + " user1.username as start_user_name, " + " user2.username as last_user_name " + "FROM fl_discussions " + "INNER JOIN fl_users user1 " + " ON user1.id = start_user_id " + "INNER JOIN fl_users user2 " + " ON user2.id = last_user_id " + "WHERE fl_discussions.comments_count != 0 " + "ORDER BY fl_discussions.last_time DESC"; dbResultSet = dbStatement.executeQuery(sql); dbResultSet.last(); discussionCount = dbResultSet.getRow(); System.out.print(discussionCount); System.out.println(" discussions in total."); discussionSet = new Discussion[discussionCount]; dbResultSet.first(); for (int i = 0; i < discussionCount; i++) { discussionSet[i] = new Discussion(); discussionSet[i].id = dbResultSet.getInt("id"); discussionSet[i].isSticky = dbResultSet.getBoolean("is_sticky"); discussionSet[i].lastTime = dbResultSet.getDate("last_time"); discussionSet[i].lastUserId = dbResultSet.getInt("last_user_id"); discussionSet[i].lastUserName = dbResultSet.getString("last_user_name"); discussionSet[i].startUserId = dbResultSet.getInt("start_user_id"); discussionSet[i].startUserName = dbResultSet.getString("start_user_name"); discussionSet[i].title = dbResultSet.getString("title"); dbResultSet.next(); } this.closeDB(); return discussionSet; } catch(SQLException se) { this.closeDB(); throw se; } } public Post[] getPosts(int discussionId) throws Exception { Post[] postSet; this.connectDB(); try { String sql; int postCount; sql = "SELECT fl_posts.content, fl_posts.time, fl_posts.user_id, " + " fl_discussions.title, " + " fl_users.username " + "FROM fl_posts " + "INNER JOIN fl_users " + "ON fl_users.id = fl_posts.user_id " + "INNER JOIN fl_discussions " + "ON fl_discussions.id = discussion_id " + "WHERE fl_discussions.id = "+ discussionId + " AND fl_posts.hide_user_id IS NULL AND fl_posts.type = 'comment';"; dbResultSet = dbStatement.executeQuery(sql); dbResultSet.last(); postCount = dbResultSet.getRow(); System.out.print(postCount); System.out.println(" posts in total."); postSet = new Post[postCount]; dbResultSet.first(); for (int i = 0; i < postCount; i++) { postSet[i] = new Post(); postSet[i].title = dbResultSet.getString("title"); postSet[i].content = dbResultSet.getString("content"); postSet[i].date = dbResultSet.getDate("time"); postSet[i].userId = dbResultSet.getInt("user_id"); postSet[i].userName = dbResultSet.getString("username"); dbResultSet.next(); } this.closeDB(); return postSet; } catch(SQLException se) { this.closeDB(); throw se; } } }
cnVintage/cnVintage-Telnet
src/cnvtgTelnet/FlarumInterface.java
248,594
/* * KeyTo Bean */ package xml.old.beans; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * * @author iychoi */ public class KeyTo { private String filename; private KeyHeading heading; private List<KeyDiscussion> discussions; private List<KeyStatement> statements; public KeyTo() { this.discussions = new ArrayList<KeyDiscussion>(); this.statements = new ArrayList<KeyStatement>(); } public void setFilename(String filename) { this.filename = filename; } public String getFilename() { return this.filename; } public void setHeading(KeyHeading heading) { this.heading = heading; } public KeyHeading getHeading() { return this.heading; } public void addDiscussion(KeyDiscussion discuss) { this.discussions.add(discuss); } public List<KeyDiscussion> getDiscussions() { return this.discussions; } public void addStatement(KeyStatement statement) { this.statements.add(statement); } public List<KeyStatement> getStatements() { return this.statements; } public void toXML(File file) throws Exception { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); toXML(doc); // write xml to file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); } public void toXML(Document doc) { Element key = doc.createElement("key"); doc.appendChild(key); if(this.heading != null) { this.heading.toXML(doc, key); } if(this.discussions != null) { for(KeyDiscussion discuss : this.discussions) { discuss.toXML(doc, key); } } if(this.statements != null) { for(KeyStatement statement : this.statements) { statement.toXML(doc, key); } } } }
biosemantics/TaxonXMLConverter
src/xml/old/beans/KeyTo.java
248,595
/* * Parser for CSV file * * Author: Shixuan Fan, Yuting Liu * */ import java.io.BufferedReader; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class CSVParser { // attribute list ArrayList<String> attributes = new ArrayList<>(); // info stored in HashMaps HashMap<Integer, String> firstnames = new HashMap<>(); HashMap<Integer, String> lastnames = new HashMap<>(); // Discussion information HashMap<Integer, List<Assignment>> discussions = new HashMap<>(); HashMap<Integer, List<Assignment>> seekfinds = new HashMap<>(); private int num_disc = 0, num_sf = 0; /* Constructor */ public CSVParser(BufferedReader buff) { String line = null; int count = 0; try { // read the file line by line while((line = buff.readLine()) != null) { // comma separated // ignore commas between quotes String[] words = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1); // first line: attribute names if(count == 0) { attributes.addAll(Arrays.asList(words)); for(String word : words) { if(word.startsWith("Disc")) { num_disc++; } else if(word.startsWith("Seek")) { num_sf++; } } } // other lines: tuples else { // name String subword = words[0].substring(1, words[0].length() - 1); String[] names = subword.split(","); String firstName = names[1].substring(1); String lastName = names[0]; // id int id = Integer.parseInt(words[1]); // add all information into maps firstnames.put(id, firstName); lastnames.put(id, lastName); discussions.put(id, new ArrayList<Assignment>()); seekfinds.put(id, new ArrayList<Assignment>()); // discussions and seek and finds for(int i = 2; i < words.length; ++i) { // Discussion assignment String type = attributes.get(i).startsWith("Disc") ? "discussion" : "seekfind"; // split string with commas // ignore commas between [] subword = words[i].substring(2, words[i].length() - 2); String[] numbers = subword.split(",(?=(?:[^\\[\\]]*\\[[^\\[\\]]*\\])*[^\\[\\]]*$)", -1); // trim the spaces int grade = Integer.parseInt(numbers[0].trim()); int time = Integer.parseInt(numbers[1].trim()); // different posts are wrapped in pairs // split by commas // ignore commas between () String trim_number = numbers[2].trim(); trim_number = trim_number.substring(1, trim_number.length() - 1); String[] pairs = trim_number.split(",(?=(?:[^\\(\\)]*\\([^\\(\\)]*\\))*[^\\(\\)]*$)", -1); Assignment assignment = new Assignment(type, grade, time); // process every pair // add into the assignment for(String pair : pairs) { pair = pair.trim(); // empty if(pair.length() == 0) { continue; } // split the pair String[] stats = pair.split(","); // trim spaces and remove '(' String trim_stat0 = stats[0].trim(); int length = Integer.parseInt(trim_stat0.substring(1, trim_stat0.length())); // trim spaces and remobe ')' String trim_stat1 = stats[1].trim(); int link_image = Integer.parseInt(trim_stat1.substring(0, trim_stat1.length() - 1)); assignment.add_pair(length, link_image); } if(type.equals("discussion")) { discussions.get(id).add(assignment); } else { seekfinds.get(id).add(assignment); } } } count++; } } catch (IOException e) { System.err.println("File reader fails!"); System.exit(1); } } public int get_discussion_num() { return num_disc; } public int get_seekandfind_num() { return num_sf; } public void print() { for(int id : discussions.keySet()) { List<Assignment> list = discussions.get(id); for(int i = 0; i < list.size(); ++i) { System.out.println(list.get(i).get_link_images().toString()); } } } }
yuting-liu/CS765-Design-Challenge-3
Analysis/CSVParser.java
248,596
package autoenroller; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; /** * The constants that identify {@link org.openqa.selenium.WebElement}s * throughout SPIRE. */ public class UMass { // General public static final int TRUE = 1; public static final int FALSE = 0; public static final int NOT_FOUND = -1; public static final String CHECKBOX_CLASS = "PSCHECKBOX"; public static final String RADIO_BUTTON_CLASS = "PSRADIOBUTTON"; public static final String CONFIRM_BUTTON_CLASS = "SSSBUTTON_CONFIRMLINK"; public static final String HYPERLINK_CLASS_HTML = "class=\"PSHYPERLINK\""; public static final String HYPERLINKDISABLED_CLASS_HTML = "class=\"PSHYPERLINKDISABLED\""; public static final String HYPERLINK_CLASS = "PSHYPERLINK"; public static final String NEXT_BUTTON_SELECTOR = "#DERIVED_CLS_DTL_NEXT_PB"; public static final String FINISH_BUTTON_SELECTOR = "#DERIVED_REGFRM1_SSR_PB_SUBMIT"; public static final String RESULT_ICON_SELECTOR = "#trSSR_SS_ERD_ER\\24 0_row1 > td:nth-child(3)"; public static final String SUCCESS_ICON_HTML = "alt=\"Success\""; public static final String OPEN_ICON_HTML = "alt=\"Open\""; // SPIRE Logon public static final String LOGIN_URL = "https://spire.umass.edu/"; public static final String USERNAME_ID = "userid"; public static final String PASSWORD_ID = "pwd"; public static final String LOGIN_BUTTON_SELECTOR = "#login > p:nth-child(5) > input[type=\"submit\"]"; // Student Center public static final String ENROLLMENT_LINK_SELECTOR = "#DERIVED_SSS_SCR_SSS_LINK_ANCHOR1"; // Shopping Cart public static final String CART_SCHEDULE_SELECTOR = "#STDNT_ENRL_SSVW\\24 scroll\\24 0"; public static final String CART_SHOPPING_SELECTOR = "#SSR_REGFORM_VW\\24 scroll\\24 0"; public static final String ENROLLED_IMAGE = "UM_PS_ENROLLED_ICN_1.gif"; public static final String CART_CHECKBOX_HTML = "class=\"PSCHECKBOX\""; public static final String LECTURE_DESC_SELECTOR = "#DERIVED_CLS_DTL_DESCR50"; public static final String DISCUSSIONS_TABLE_SELECTOR = "#SSR_CLS_TBL_R1\\24 scroll\\24 0 > tbody > tr:nth-child(2) > td > table"; // Add Classes public static final String ADD_CART_FIELD_SELECTOR = "#DERIVED_REGFRM1_CLASS_NBR"; public static final String ADD_CART_ENTER_SELECTOR = "#DERIVED_REGFRM1_SSR_PB_ADDTOLIST2\\24 9\\24"; public static final String ADD_DISC_TABLE_SELECTOR = "#SSR_CLS_TBL_R1\\24 scroll\\24 0"; public static final String CONFIRM_ADD_CART_SELECTOR = "#DERIVED_CLS_DTL_NEXT_PB\\24 280\\24"; public static final String ENROLL_BUTTON_SELECTOR = "#DERIVED_REGFRM1_LINK_ADD_ENRL\\24 291\\24"; public static final String ADD_MORE_CLASS_SELECTOR = "#DERIVED_REGFRM1_SSR_LINK_STARTOVER"; // Drop Classes public static final String DROP_TABLE_SELECTOR = "#STDNT_ENRL_SSV1\\24 scroll\\24 0"; // Swap Classes public static final String SWAP_SCHEDULE_MENU_SELECTOR = "#DERIVED_REGFRM1_DESCR50\\24 225\\24"; public static final String SWAP_CART_ID_SELECTOR = "#DERIVED_REGFRM1_CLASS_NBR"; public static final String SWAP_ENTER_ID_SELECTOR = "#DERIVED_REGFRM1_SSR_PB_ADDTOLIST2\\24 106\\24"; // Edit Classes public static final String ENROLLED_DROPDOWN_SELECTOR = "#DERIVED_REGFRM1_DESCR50\\24 225\\24"; public static final String EDIT_CONFIRM_STEP_1_SELECTOR = "#DERIVED_REGFRM1_LINK_UPDATE_ENRL"; // Returns elements of the shopping cart table on the shopping cart page. public static WebElement findElementShoppingCart(WebDriver driver, int row, int col) { return waitForElement(driver, By.cssSelector("#trSSR_REGFORM_VW\\24 0_row"+row+" > td:nth-child("+col+")")); } // Returns elements of the current schedule table on the shopping cart page. public static WebElement findElementCartSchedule(WebDriver driver, int row, int col) { return waitForElement(driver, By.cssSelector("#trSTDNT_ENRL_SSVW\\24 0_row"+row+" > td:nth-child("+col+")")); } // Returns elements of the current Lecture's table of all existing Discussions. public static WebElement findElementDiscussionTable(WebDriver driver, int row, int col) { return waitForElement(driver, By.cssSelector("#trSSR_CLS_TBL_R1\\24 0_row"+row+" > td:nth-child("+col+")")); } public static WebElement findElementDropTable(WebDriver driver, int row, int col) { return waitForElement(driver, By.cssSelector("#trSTDNT_ENRL_SSV1\\24 0_row"+row+" > td:nth-child("+col+")")); } public static WebElement findElementAddTable(WebDriver driver, int row, int col) { return waitForElement(driver, By.cssSelector("#trSSR_CLS_TBL_R1\\24 0_row"+row+" > td:nth-child("+col+")")); } public static WebElement findElementTab(WebDriver driver, String tabName) { WebElement tabFound = null; // This table has many inactive/invisible rows, but they will not match any text so they can be ignored. for(WebElement tab : waitForElement(driver, By.cssSelector( "#win0divDERIVED_SSTSNAV_SSTS_NAV_SUBTABS > div > table > tbody > tr:nth-child(2)")).findElements(By.tagName("td"))) { if(tab.getText().toLowerCase().equals(tabName.toLowerCase())) { tabFound = tab; break; } } return tabFound; } /** * Wait for a {@link WebElement} to load. * Refreshes every 200 milliseconds and times out after 10 seconds. * @param driver {@link WebDriver} running the browser. * @param by The element being checked for. * @return The {@link WebElement} once it has been found. */ public static WebElement waitForElement(WebDriver driver, By by) { // This may be a good place to check if SPIRE asks to select a semester. // Debatable as to whether this is too low-level and should be handled // situationally rather than for every Wait instance. // When they happen, semester selections come up for very many actions. return (new WebDriverWait(driver, 10, 200)).until(ExpectedConditions.presenceOfElementLocated(by)); } /** * Wait for a {@link WebElement} to load. * Refreshes every 200 milliseconds and times out after a given number of seconds. * @param driver {@link WebDriver} running the browser. * @param timeoutSeconds Number of seconds to spend refreshing before timing out. * @param by The element being checked for. * @return The {@link WebElement} once it has been found. */ public static WebElement waitForElement(WebDriver driver, int timeoutSeconds, By by) { return (new WebDriverWait(driver, timeoutSeconds, 200)).until(ExpectedConditions.presenceOfElementLocated(by)); } public static void sleep(int millis) { try { Thread.sleep(millis); } catch(InterruptedException e) { e.printStackTrace(); } } }
AlexDFischer/autoenroller
src/autoenroller/UMass.java
248,597
package conf; import models.contributions.Contribution; import play.Logger; import play.Play; import java.util.*; /** * Singleton contenant la configuration de l'application * * Les clés sont préfixées de "herbonautes." et sont présentes dans * le fichier de configuration conf/application.conf */ public class Herbonautes { public static final Herbonautes INSTANCE = new Herbonautes(); public Integer timezoneOffset; public Integer specimenFileLimit; public String tilesRootURL; public Integer tilesDefaultZoom; public boolean forceTiled; public Integer specimenMarkedSeenDelay; public Integer pageLength; // public Integer quickSearchLength; public Integer searchResultLength; public Integer contributionValidationMin; public String title; public String titleSep; public Integer explorerBadgeThreshold; public Integer podiumBadgeThreshold; public Integer nightBadgeHourStart; public Integer nightBadgeHourEnd; public Integer activityTimeBuffer; public Integer maxLevel = 6; public Integer avatarSize = 239; public String imageMimeType = "image/jpeg"; public Integer geolocalisationConflictDistance; public Integer missionsCountOnIndex; public Map<Integer, Integer> unlockLevelAt; public Map<String, Integer> quickSearchLengthByCategory; public Map<String, Integer> contributionValidationMinByType; public String mailsFrom; public String fbAppID; public String fbSecretKey; public String fbChannelURL; public String uploadDir; public String recolnatApiEndpoint; public String recolnatApiKey; public boolean recolnatEnabled; public boolean recolnatMenuShow; public String recolnatMenuUrl; public Integer pageLengthUserContributions; public Integer pageLengthSpecimenList; public List<String> contributionTypes; public Integer specimenPerMissionLimit; public Integer classifierMinDiscussions; public Integer pedagogueMinMessages; public Integer solidaryMinMessages; public Integer writerMinMessageLength; public Integer animatorMinMessages; public Integer animatorMinDiscussions; public Integer missionProposalMinLevel; public Integer discussionTagsMinLevel; public Integer saveTagsElementMinLevel; public Integer lastMessagesMaxResults; public Integer nbDiscussionsToLoadPerCall; public Integer elasticReadTimeout; public String baseUrl; public String logoUrl; public List<String> luckyBadgeFamilyList; public List<String> luckyBadgeGenusList; public List<String> luckyBadgeSpecificEpithetList; private Herbonautes() { baseUrl = getString("application.baseUrl",""); logoUrl = getString("herbonautes.logoUrl",""); specimenFileLimit = getInteger("specimen.file.limit", 1000); elasticReadTimeout = getInteger("elastic.proxy.timeout", 3000); specimenPerMissionLimit = getInteger("specimens.per.mission.limit", 100); recolnatApiEndpoint = getString("recolnat.api.endpoint", ""); recolnatApiKey = getString("recolnat.api.key", ""); recolnatMenuShow = getBoolean("recolnat.menu.show", false); recolnatMenuUrl = getString("recolnat.menu.url", ""); recolnatEnabled = getBoolean("recolnat.enabled", false); tilesRootURL = getString("herbonautes.tiles.root.url", ""); forceTiled = getBoolean("herbonautes.force.tiled", false); tilesDefaultZoom = getInteger("herbonautes.tiles.default.zoom", 0); specimenMarkedSeenDelay = getInteger("herbonautes.specimen.marked.seen.delay", 3000); pageLength = getInteger("herbonautes.page.length", 3); quickSearchLength = getInteger("herbonautes.quick.search.limit", 4); searchResultLength = getInteger("herbonautes.search.result.length", 10); contributionValidationMin = getInteger("herbonautes.contribution.validation.min", 3); title = getString("herbonautes.title", "Les herbonautes"); titleSep = " " + getString("herbonautes.title.separator", "-") + " "; explorerBadgeThreshold = getInteger("herbonautes.explorer.badge.threshold", 10); podiumBadgeThreshold = getInteger("herbonautes.podium.badge.threshold", 20); activityTimeBuffer = getInteger("herbonautes.activity.time.buffer", 10); nightBadgeHourStart = getInteger("herbonautes.night.badge.hour.start", 0); nightBadgeHourEnd = getInteger("herbonautes.night.badge.hour.end", 6); mailsFrom = getString("herbonautes.mails.from", "Les herbonautes <[email protected]>"); missionsCountOnIndex = getInteger("herbonautes.missions.on.index", 2); fbAppID = getString("herbonautes.fb.app.id", null); fbSecretKey = getString("herbonautes.fb.secret.key", null); fbChannelURL = getString("herbonautes.fb.channel.url", null); uploadDir = getString("herbonautes.upload.dir", Play.applicationPath + "/uploads"); unlockLevelAt = new HashMap<Integer, Integer>(); for (Integer level : new Integer[] { 2, 3, 4, 5, 6, 7, 8 }) { unlockLevelAt.put(level, getInteger("herbonautes.unlock.level." + level + ".at", 0)); } specimenMarkedSeenDelay = getInteger("herbonautes.specimen.marked.seen.delay", 2000); geolocalisationConflictDistance = getInteger("herbonautes.geolocalisation.conflict.distance", 20000); Contribution.Type[] allContributionTypes = Contribution.Type.values(); this.contributionTypes = new ArrayList<String>(); for (Contribution.Type type : allContributionTypes) { this.contributionTypes.add(type.toString()); } this.quickSearchLengthByCategory = new HashMap(); for (Category category : Category.values()) { String cat = category.toString().toLowerCase(); quickSearchLengthByCategory.put(cat, getInteger("herbonautes.quick.search.limit." + cat, 5)); } this.contributionValidationMinByType = new HashMap<String, Integer>(); for (Contribution.Type ctype : allContributionTypes) { String type = ctype.toString().toLowerCase(); contributionValidationMinByType.put(type, getInteger("herbonautes.contribution.validation.limit." + type, contributionValidationMin)); } classifierMinDiscussions = getInteger("herbonautes.badge.classifier.minimum.discussions", 20); pedagogueMinMessages = getInteger("herbonautes.badge.pedagogue.minimum.messages", 5); solidaryMinMessages = getInteger("herbonautes.badge.solidary.minimum.sos.resolutions", 5); writerMinMessageLength = getInteger("herbonautes.badge.writer.minimum.message.length", 1000); animatorMinMessages = getInteger("herbonautes.badge.animator.minimum.messages", 10); animatorMinDiscussions = getInteger("herbonautes.badge.animator.minimum.discussions", 30); missionProposalMinLevel = getInteger("herbonautes.mission.proposition.minimum.level", 6); discussionTagsMinLevel = getInteger("herbonautes.discussion.tags.minimum.level", 6); saveTagsElementMinLevel = getInteger("herbonautes.elements.tags.save.minimum.level", 6); lastMessagesMaxResults = getInteger("herbonautes.last.messages.max.results", 3); nbDiscussionsToLoadPerCall = getInteger("herbonautes.discussion.call.nb.loads", 3); pageLengthUserContributions = getInteger("herbonautes.page.length.user.contributions", 30); pageLengthSpecimenList = getInteger("herbonautes.page.length.specimens.list", 30); timezoneOffset = getInteger("herbonautes.timezone.offset", -60); // Lucky badge luckyBadgeFamilyList = toLowerCase(getStringList("herbonautes.badge.lucky.familyList")); luckyBadgeGenusList = toLowerCase(getStringList("herbonautes.badge.lucky.genusList")); luckyBadgeSpecificEpithetList = toLowerCase(getStringList("herbonautes.badge.lucky.specificEpithetList")); } public static final Herbonautes get() { return INSTANCE; } /** * Récupère la chaine ou retourne la valeur par défaut */ private static List<String> getStringList(String key) { String val = Play.configuration.getProperty(key); if (val != null) { Logger.info("%s : %s", key, val); ArrayList<String> l = new ArrayList<String>(); for (String i : val.split(",")) { l.add(i.trim()); } return l; } else { Logger.warn("%s (defaut) : empty list", key); return Collections.emptyList(); } } private static List<String> toLowerCase(List<String> l) { List<String> lowerCaseList = new ArrayList<String>(); for (String s : l) { lowerCaseList.add(s.toLowerCase()); } return lowerCaseList; } /** * Récupère la chaine ou retourne la valeur par défaut */ private static String getString(String key, String defaultValue) { String val = Play.configuration.getProperty(key); if (val != null) { Logger.info("%s : %s", key, val); return val; } else { Logger.warn("%s (defaut) : %s", key, defaultValue); return defaultValue; } } /** * Récupère le booleen ou retourne la valeur par défaut */ private static boolean getBoolean(String key, boolean defaultValue) { String val = Play.configuration.getProperty(key); if (val != null) { Logger.info("%s : %s", key, val); return Boolean.valueOf(val); } else { Logger.warn("%s (defaut) : %s", key, defaultValue); return defaultValue; } } /** * retourne l'entier ou la valeur par défaut */ private static Integer getInteger(String key, Integer defaultValue) { Integer val = null; try { val = Integer.valueOf(Play.configuration.getProperty(key)); } catch(Exception e) { Logger.error("%s non numerique", key); } if (val != null) { Logger.info("%s : %s", key, val); return val; } else { Logger.warn("%s (defaut) : %s", key, defaultValue); return defaultValue; } } public Integer contributionValidationMinByType(String type) { return contributionValidationMinByType.get(type.toLowerCase()); } public Integer quickSearchLengthByCategory(Category category) { return quickSearchLengthByCategory.get(category.toString().toLowerCase()); } public Integer unlockContributionCount(Integer level) { Integer count = unlockLevelAt.get(level); if (count == null) { count = -1; } return count; } public enum Category { MISSIONS, BOTANISTS, SPECIMENS, HERBONAUTES, DISCUSSIONS, SCIENTIFICNAMES, TAGS } }
DiSSCo/herbonauts
web/app/conf/Herbonautes.java
248,598
package db; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import discussion.Discussion; import discussion.DiscussionGroupe; import message.Message; import ui.WindowError; import user.User; import ui.NewDiscussionUI; import ui.UserMainUI; public class DatabaseDiscussion { private ArrayList<Discussion> users_discussions; private static DatabaseDiscussion db_disc_singleton=null; // singleton pattern private DatabaseDiscussion(){ users_discussions = new ArrayList<Discussion>(); } //create singleton DatabaseDiscussion public static synchronized DatabaseDiscussion getInstance() { if (db_disc_singleton == null) db_disc_singleton = new DatabaseDiscussion(); return db_disc_singleton; } public void create_discussion(UserMainUI userMainUI,String framename,int sizex,int sizey,User current_user,DatabaseUsers users_db){ if (current_user.get_liste_contact().isEmpty()){ new WindowError("Error", "you need friends if you want to create a discussion",null); return; } NewDiscussionUI disc_ui = new NewDiscussionUI(userMainUI,"New Discussion",650,350,current_user,this,users_db); } //return list of all username with current user inside public ArrayList<String> find_all_disc(User current_user,DatabaseUsers users_db){ ArrayList<String> discs= new ArrayList<>(); for (Discussion discussion:users_discussions){ if (discussion.getmembers_id().contains(current_user.get_userid())){ String members=""; for (Integer id: discussion.getmembers_id()){ if (id != current_user.get_userid()){ members = members + users_db.get_user("id",String.valueOf(id)).get_username() + ","; } } discs.add(members.substring(0, members.length() - 1)); // remove last "," } } return discs; } //returns true if a discussion can be create public boolean verify_disc_creation(String messageinitial,String list_users,User current_user,DatabaseUsers users_db){ if (list_users.equals(messageinitial)){ new WindowError("Error","Please add at least one person to the discussion",null); return false; } String[] users_array = (list_users + ',' + current_user.get_username()).split(","); ArrayList<Integer> users_id = get_members_id(users_db, users_array); if (users_id == null){ return false; } // si il y a 2 ou get_userid() dans users_id c que user a essayé de se message lui meme if (users_id.stream().filter(x->x.equals(current_user.get_userid())).count() > 1){ new WindowError("Error","you can't send message to yourself", null); return false; } // try to find if a current_discussion exist if (get_discussion(users_id)!= null){ new WindowError("Error","The discussion already exist", null); return false; } Discussion current_discussion; for (int user_id:users_id){ if (user_id == current_user.get_userid()){ continue; } if (!current_user.get_liste_contact().contains(user_id)){ new WindowError("Error", users_db.get_user("id", String.valueOf(user_id)).get_username() + " is not your friend so you can't message him",null); return false; } } if (users_id.size() > 2){ current_discussion = new DiscussionGroupe(users_id,current_user.get_userid()); } else{ current_discussion = new Discussion(users_id,true); } users_discussions.add(current_discussion); return true; } public String find_message(String message,DatabaseUsers users_db,String[] members_username){ ArrayList<Integer> members_id = get_members_id(users_db, members_username); Discussion discussion = get_discussion(members_id); if (discussion != null){ for (Message current_message:discussion.getmessages()){ if (current_message.get_contenu().equals(message)){ return current_message.see_details(users_db); } } } return "No message found !"; } public void exclude_member(String exclude_member,ArrayList<String> members_username,DatabaseUsers users_db,User current_user){ if (exclude_member.equals(current_user.get_username())){ System.out.println("you can't exclude yourself from a conversation."); } int current_user_id = current_user.get_userid(); if (!members_username.contains(exclude_member)){ System.out.println(exclude_member + " is not part of the group"); return; } if (members_username.size() == 2){ System.out.println("you can't exclude someone from a private conversation but you can block this person"); return; } ArrayList<Integer> members_id = new ArrayList<Integer>(); for (String member:members_username){ User member_user = users_db.IsUserinDb(member,null); members_id.add(member_user.get_userid()); } Collections.sort(members_id); Discussion discussion = get_discussion(members_id); if (discussion instanceof DiscussionGroupe){ DiscussionGroupe discussionGroupe = (DiscussionGroupe) discussion; if (discussionGroupe.get_admin_id() == current_user_id){ discussion.remove_member(users_db.get_user("username", exclude_member).get_userid()); System.out.println(exclude_member + " was successfully excluded"); } else{ System.out.println("you are not the admin of the discussion and thus cannot exclude someone"); } if (discussion.getmembers_id().size() == 2){ users_discussions.remove(discussionGroupe); } return; } System.out.println("there is no discussion available with all the members you describe"); } public boolean date_equal(Date date1,Date date2){ Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); // Attribution des dates aux instances de Calendar cal1.setTime(date1); cal2.setTime(date2); // Comparaison des années, des mois et des jours return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH) && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH); } // conversion username->id public ArrayList<Integer> get_members_id(DatabaseUsers users_db,String[] members_username){ ArrayList<Integer> members_id = new ArrayList<Integer>(); for (String member:members_username){ User member_user = users_db.IsUserinDb(member,null); if (member_user == null){ return null;//error throwed } members_id.add(member_user.get_userid()); } Collections.sort(members_id); // sort the array so that we can compare with the db_discussions return members_id; } public String find_messages_date(String dateString,DatabaseUsers users_db,String[] members_username){ ArrayList<Integer> members_id = get_members_id(users_db, members_username); String all_messages=""; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); sdf.setLenient(false); // Pour rendre la validation stricte Date date=null; try { date = sdf.parse(dateString); } catch (ParseException e) { System.out.println("Invalid date"); } Discussion discussion = get_discussion(members_id); for (Message current_message:discussion.getmessages()){ if (date_equal(date, current_message.get_date())){ all_messages += current_message.see_details(users_db); all_messages += "\n"; } } if (all_messages == ""){ return "No message found !"; } return all_messages; } // retourne la discussion qui concerne tout les users_id // discussion == null signifie qu aucune discussion existe pour ces utilisateurs public Discussion get_discussion(ArrayList<Integer> users_id){ for (Discussion discussion:users_discussions){ if (discussion.getmembers_id().equals(users_id)){ return discussion; } } return null; } public Discussion get_discussion(DatabaseUsers users_db,String[] usernames){ ArrayList<Integer> users_id = get_members_id(users_db,usernames); for (Discussion discussion:users_discussions){ if (discussion.getmembers_id().equals(users_id)){ return discussion; } } return null; } public void resetDatabase() { users_discussions.clear(); } }
floflopi/Mission2
db/DatabaseDiscussion.java
248,600
package api; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import util.RDFBuilder; /** * DiscussionsTracker is used to query Twitter for the statuses * of a specific user. * * @author Tudor-Daniel Sirbu * @author Claudiu Tarta * @author Florin-Cristian Gavrila */ public class DiscussionsTracker { Twitter twitterConnection = null; public DiscussionsTracker(){ // create a twitter connection try { twitterConnection = (new TwitterManager()).init(); } catch (Exception e) { System.out.println("DiscussionsTracker: A connection to Twitter API could not be established."); e.printStackTrace(); } } /** * The method gets the tweets for the provided ids and indexes them * * @param twitter the twitter api connection * @param ids the ids of the users that are being queried */ public void usersQuery(long[] ids){ RDFBuilder rdfBuilder = new RDFBuilder(); // for each user id for(long id : ids){ // get the user's statuses ResponseList<Status> statuses = getTweets(id); // add the statuses to the RDF rdfBuilder.addTweets(statuses); } rdfBuilder.save(); rdfBuilder.close(); } /** * The method retrieves all the statuses of a user * * @param twitter the twitter connection to the api * @param id the id of the user for which the statuses are retrieved * @return the retrieved statuses */ public ResponseList<Status> getTweets(long id){ // list of statuses ResponseList<Status> statuses = null; // get the user's timeline try { statuses = twitterConnection.getUserTimeline(id, new Paging(1,100)); } catch (TwitterException e) { System.out.println("Could not retrieve user's (" + id + ") timeline."); e.printStackTrace(); } finally { twitterConnection.shutdown(); } return statuses; } }
tudorsirbu/intelligent-web
src/api/DiscussionsTracker.java
248,601
package client; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import util.ClientState; import util.NetworkUtil; import util.Question; import util.UserInfo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; public class HomePageController { private ShowGui main; private NetworkUtil util; static ReceiveListThread receiveListThread; public NetworkUtil getUtil() { return util; } private UserInfo userInfo; LinkedList<Question> questionLinkedList; ObservableList<Question> questions; HashMap<String,ArrayList<Integer>> likesTrack; private HomePageController homePageController = this; public void load(ShowGui main, NetworkUtil util, UserInfo userInfo) { this.main = main; this.util = util; this.userInfo = userInfo; likesTrack = userInfo.getLikesTrack(); userName.setText(util.getUserName()); email.setText(userInfo.getUpEmail()); questionLinkedList = new LinkedList<>(); questionOnList(); receiveListThread = new ReceiveListThread(this,util); new InitialiseDiscussionListThread(util, questionLinkedList, homePageController); questionListView.refresh(); } @FXML public BorderPane mainLayout; @FXML protected TabPane tabPane; @FXML private AnchorPane anchorPane; @FXML public Tab learn; @FXML private Button cpp; @FXML private Button java; @FXML private Label userName; @FXML private Label email; @FXML protected ListView questionListView; @FXML private Button python; @FXML private Button csharp; @FXML protected Tab discussions; @FXML protected Tab notifications; @FXML protected Tab profile; @FXML private Button newQuestion; @FXML private ImageView myImage; @FXML void imageDragOver(DragEvent event) { Dragboard board = event.getDragboard(); if (board.hasFiles()) { event.acceptTransferModes(TransferMode.ANY); } } @FXML void imageDropped(DragEvent event) { Dragboard dragboard = event.getDragboard(); List<File> file = dragboard.getFiles(); try { FileInputStream fis = new FileInputStream(file.get(0)); Image image = new Image(fis); myImage.setImage(image); } catch (FileNotFoundException e) { e.printStackTrace(); } } @FXML void openCPP(ActionEvent event) { try { main.showCppTutorial(this, util); } catch (IOException e) { e.printStackTrace(); } } @FXML void openCsharp(ActionEvent event) { try { main.showCSharpTutorial(this, util); } catch (IOException e) { e.printStackTrace(); } } @FXML void openJava(ActionEvent event) { try { main.showJavaTutorial(this, util); } catch (IOException e) { e.printStackTrace(); } } @FXML void openPython(ActionEvent event) { try { main.showPythonTutorial(this, util); } catch (IOException e) { e.printStackTrace(); } } @FXML void signOut(ActionEvent event) { try { new StopThread(util, ClientState.STOP_THREAD); main.showStartUp(); } catch (IOException e) { e.printStackTrace(); } } void loadCPP() { } @FXML void openNewQuestion(ActionEvent event) { try { main.showNewDiscussion(this, util); } catch (IOException e) { e.printStackTrace(); } } void changeListView(ListView<Question> questionListView, ObservableList<Question> questions) { questionListView.setItems(questions); questionListView.setCellFactory((list) -> { return new ListCell<Question>() { Label vote = new Label("Votes :"); Label question = new Label(); Label answer = new Label("Answers"); Label voteNumber = new Label(); Label answerNumber = new Label(); Label name = new Label(); Label time = new Label(); VBox v1 = new VBox(voteNumber, vote, answerNumber, answer); HBox hBox = new HBox(v1, question); VBox vBox = new VBox(hBox, name, time); @Override protected void updateItem(Question item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); } else { //setText("\t"+item.getTitle()+"\n\n\t"+item.getMessage()); question.setText(item.getTitle()); //label2.setText(item.getMessage()); vBox.setSpacing(10); hBox.setSpacing(50); vBox.setPadding(new Insets(10, 10, 10, 10)); setPadding(new Insets(10, 10, 50, 10)); setGraphic(vBox); } } }; }); questionListView.getSelectionModel().selectedItemProperty().addListener((observable, oldvalue, newValue) -> { System.out.println("ListView Selection Changed (selected: \" + newValue.toString() + \")"); }); } void questionOnList() { questionListView.setItems(questions); questionListView.setCellFactory(list -> new ListCell<Question>() { Node root; ListCellController cellController; { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("fxmlFiles/listCell.fxml")); root = loader.load(); cellController = loader.getController(); cellController.load(main, util, homePageController); } catch (IOException e) { e.printStackTrace(); } } @Override protected void updateItem(Question item, boolean empty) { //don't do anything here super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); } else { //use your logic as your needs on the the new list cell cellController.question.setText(item.getTitle()); cellController.time.setText(item.getDate()); cellController.name.setText(item.getPostedBy()); cellController.voteNumber.setText(item.getLikeNumber()); cellController.answerNumber.setText(item.getAnswerNumber()); cellController.thisQuestion = item; setGraphic(root); } } }); } public UserInfo getUserInfo() { return userInfo; } }
ARTushar/CS-Community-Based-Learning
src/client/HomePageController.java
248,602
package indexes; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import json.JSONArray; import json.JSONException; import json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import structures.Post; import utils.Utils; /** * Represent an index of discussions. * @author whh8b * @version 0.1 * @category Index */ public abstract class IndexBase { public IndexBase(String indexTitle, String index) { m_index = index; m_title = indexTitle; m_discussionBaseURL = getDiscussionBaseURL(); m_discussions = new ArrayList<Integer>(); } /** * An integer list of discussion IDs under * this Index. */ ArrayList<Integer> m_discussions; /** * A string for the index URL. */ String m_index; /** * A string for the base URL of all discussions. */ String m_discussionBaseURL; /** * The title for this index. */ String m_title; /** * Get the base URL for any discussions * in this index. * * @return a string for the base URL of any * discussions referenced in this index. */ abstract String getDiscussionBaseURL(); /** * Parse an index file from its Document * representation. * * @param title The title of the index being parsed. * @param doc A Document of the index page. * @return A boolean (true or false) depending * upon the success or failure of parsing the * Document doc. */ abstract protected boolean parseIndex(String title, Document doc); /** * Parse an index file from its source. * * @return A boolean (true or false) depending * upon the success or failure of parsing the * page at m_index. */ public boolean parseIndex() { try { /* * For testing purposes, make .XXXX a special * syntax to indicate that m_index is a filename. * Otherwise, assume that it's a URL. */ if (m_index.charAt(0) == '.') { return parseIndex(m_title, Jsoup.parse(new File(m_index), "UTF-8")); } else { return parseIndex(m_title, Jsoup.parse(utils.Utils.getHTML(m_index))); } } catch (IOException e) { System.err.format("[Error]Failed to parse %s!\n", m_index); e.printStackTrace(); return false; } } }
hawkinsw/csir-mp1
src/indexes/IndexBase.java
248,603
// hand-crafted on 14-Jul-2019 -- probably all wrong // NOTE: module name differs from Maven (group) id due to Woodstox // having sort of legacy Java package, but more modern Maven group id. // Having to choose one over the other is partly due to discussions like: // https://blog.joda.org/2017/04/java-se-9-jpms-modules-are-not-artifacts.html // and partly since Automatic Module Name already used Java root package module com.ctc.wstx { requires transitive java.xml; // for SAX, JAXP, DOM requires transitive org.codehaus.stax2; // Need to export most Java packages, but may eventually want to close some exports com.ctc.wstx.api; exports com.ctc.wstx.cfg; exports com.ctc.wstx.dom; exports com.ctc.wstx.dtd; exports com.ctc.wstx.ent; exports com.ctc.wstx.evt; exports com.ctc.wstx.exc; exports com.ctc.wstx.io; // should this be exported? exports com.ctc.wstx.msv; exports com.ctc.wstx.sax; exports com.ctc.wstx.sr; exports com.ctc.wstx.stax; exports com.ctc.wstx.sw; exports com.ctc.wstx.util; provides javax.xml.stream.XMLEventFactory with com.ctc.wstx.stax.WstxEventFactory; provides javax.xml.stream.XMLInputFactory with com.ctc.wstx.stax.WstxInputFactory; provides javax.xml.stream.XMLOutputFactory with com.ctc.wstx.stax.WstxOutputFactory; //Include shaded in provisions // 26-Feb-2024, tatu: Seems like these are problematic; exclude //provides com.ctc.wstx.shaded.msv.relaxng_datatype.DatatypeLibraryFactory with com.ctc.wstx.shaded.msv_core.datatype.xsd.ngimpl.DataTypeLibraryImpl; //provides com.ctc.wstx.shaded.msv.org_isorelax.verifier.VerifierFactoryLoader with com.ctc.wstx.shaded.msv_core.verifier.jarv.FactoryLoaderImpl; provides org.codehaus.stax2.validation.XMLValidationSchemaFactory.dtd with com.ctc.wstx.dtd.DTDSchemaFactory; provides org.codehaus.stax2.validation.XMLValidationSchemaFactory.relaxng with com.ctc.wstx.msv.RelaxNGSchemaFactory; provides org.codehaus.stax2.validation.XMLValidationSchemaFactory.w3c with com.ctc.wstx.msv.W3CSchemaFactory; }
FasterXML/woodstox
src/moditect/module-info.java
248,604
package gui; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import domain.IDomainObject; import domain.enums.ECrud; import domain.enums.ERole; import gui.accounts.AccountsPanel; import gui.accounts.UpdateAccountFrame; import gui.discussions.DiscussionsPanel; import gui.login.LoginFrame; import gui.search.SearchPanel; import gui.waitingFriendships.WaitingFriendshipsFrame; import persistence.db.SingletonDB; import persistence.uow.Observer; import persistence.uow.UnitOfWork; import service.FriendshipService; import service.UserService; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; /** * Classe représentant la fenêtre principale de l'application. * * @author Laurent THIEBAULT & Ludovic LANDSCHOOT */ public class MainFrame extends AppFrame implements Observer { private JPanel navPanel; private JLabel titleLabel; private JButton deconnectButton; private JPanel mainPanel; private JLabel userLabel; private JPanel bodyPanel; private JPanel dashboardPanel; private JButton accountsButton; private JButton discussionsButton; private JPanel userPanel; private JPanel contentPanel; private JButton updateAccountButton; private JButton searchButton; private JButton waitingFriendshipsButton; private AccountsPanel accountsPanel; private DiscussionsPanel discussionsPanel; private SearchPanel searchPanel; private UserService userService; private FriendshipService friendshipService; private UnitOfWork unitOfWork; public MainFrame() { this.unitOfWork = UnitOfWork.getInstance(); this.userService = UserService.getInstance(); this.friendshipService = FriendshipService.getInstance(); this.setContentPane(this.mainPanel); initPanels(); cleanPanels(); initFrame(); initComponents(); configUpdateAccountButton(); configWaitingFriendshipButton(); configDeconnectButton(); configDashboard(); cleanButtons(); checkRole(); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { SingletonDB.getInstance().close(); } }); this.setVisible(true); } /** * Dynamise les composants à afficher en fonction du rôle de l'utilisateur connecté. */ private void checkRole() { if (userService.getConnectedUser().getRole().equals(ERole.USER_ADMIN)) { this.setTitle("Chatbook - Admin"); this.titleLabel.setText("chatbook - admin"); cleanPanels(); cleanButtons(); accountsButton.setFont(new Font("Lucida Grande", Font.BOLD, 16)); accountsButton.setForeground(new Color(59, 89, 152)); this.accountsPanel.setVisible(true); } else { this.setTitle("Chatbook - " + userService.getConnectedUser().getFirstname() + " " + userService.getConnectedUser().getLastname()); cleanPanels(); cleanButtons(); discussionsButton.setFont(new Font("Lucida Grande", Font.BOLD, 16)); discussionsButton.setForeground(new Color(59, 89, 152)); this.discussionsPanel.setVisible(true); } } /** * Initialise les panneaux. */ public void initPanels() { this.accountsPanel = new AccountsPanel(); contentPanel.add(accountsPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); this.discussionsPanel = new DiscussionsPanel(); contentPanel.add(discussionsPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); this.searchPanel = new SearchPanel(); contentPanel.add(searchPanel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); } /** * Rend invisible les panneaux. */ public void cleanPanels() { this.accountsPanel.setVisible(false); this.discussionsPanel.setVisible(false); this.searchPanel.setVisible(false); } @Override public void initComponents() { titleLabel.setBorder(new EmptyBorder(10, 10, 10, 10)); userLabel.setBorder(new EmptyBorder(10, 10, 10, 10)); userLabel.setText(userService.getConnectedUser().getFirstname() + " " + userService.getConnectedUser().getLastname()); dashboardPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); userPanel.setBorder(new EmptyBorder(0, 0, 0, 14)); checkComponentRoles(); initImages(); configWaitingFriendshipImage(); } /** * Affiche ou non une notification s'il existe des demandes d'amitié en attente de confirmation. */ private void configWaitingFriendshipImage() { Image waitingFriendshipImg = null; try { if (friendshipService.findWaitingFriendships(UserService.getInstance().getConnectedUser()).size() != 0) { waitingFriendshipImg = ImageIO.read(MainFrame.class.getResource("../img/demandes_amis_new.png")); } else { waitingFriendshipImg = ImageIO.read(MainFrame.class.getResource("../img/demandes_amis.png")); } waitingFriendshipImg = waitingFriendshipImg.getScaledInstance(16, 16, Image.SCALE_DEFAULT); } catch (IOException e) { e.printStackTrace(); } waitingFriendshipsButton.setIcon(new ImageIcon(waitingFriendshipImg)); } /** * Initialise les images dans la barre de navigation. */ private void initImages() { Image updateAccountImg = null; Image logoutImg = null; try { updateAccountImg = ImageIO.read(MainFrame.class.getResource("../img/mon_compte.png")); updateAccountImg = updateAccountImg.getScaledInstance(16, 16, Image.SCALE_DEFAULT); logoutImg = ImageIO.read(MainFrame.class.getResource("../img/deconnexion.png")); logoutImg = logoutImg.getScaledInstance(16, 16, Image.SCALE_DEFAULT); } catch (IOException e) { e.printStackTrace(); } updateAccountButton.setIcon(new ImageIcon(updateAccountImg)); deconnectButton.setIcon(new ImageIcon(logoutImg)); } /** * Affiche ou non certains composants en fonction du rôle de l'utilisateur connecté. */ public void checkComponentRoles() { if (!ERole.USER_ADMIN.equals(userService.getConnectedUser().getRole())) { accountsButton.setVisible(false); } } /** * Configure les différents listeners des boutons du tableau de bord. */ public void configDashboard() { accountsButton.addActionListener((ActionEvent e) -> { cleanPanels(); cleanButtons(); accountsButton.setFont(new Font("Lucida Grande", Font.BOLD, 16)); accountsButton.setForeground(new Color(59, 89, 152)); this.accountsPanel.setVisible(true); }); discussionsButton.addActionListener((ActionEvent e) -> { cleanPanels(); cleanButtons(); discussionsButton.setFont(new Font("Lucida Grande", Font.BOLD, 16)); discussionsButton.setForeground(new Color(59, 89, 152)); this.discussionsPanel.setVisible(true); }); searchButton.addActionListener((ActionEvent e) -> { cleanPanels(); cleanButtons(); searchButton.setFont(new Font("Lucida Grande", Font.BOLD, 16)); searchButton.setForeground(new Color(59, 89, 152)); this.searchPanel.updateAccountsList(); this.searchPanel.setVisible(true); }); } /** * Configure le listener du bouton de déconnexion. */ public void configDeconnectButton() { deconnectButton.addActionListener(e -> { this.userService.setConnectedUser(null); this.setVisible(false); this.unitOfWork.rollback(); new LoginFrame(); }); } /** * Configure le listener de modification de compte. */ public void configUpdateAccountButton() { updateAccountButton.addActionListener(e -> { UpdateAccountFrame updateAccountFrame = new UpdateAccountFrame(); updateAccountFrame.addObserver(this); }); } /** * Configure le listener du bouton des demandes d'amitié en attente de confirmation. */ public void configWaitingFriendshipButton() { waitingFriendshipsButton.addActionListener(e -> { WaitingFriendshipsFrame waitingFriendshipsFrame = new WaitingFriendshipsFrame(); waitingFriendshipsFrame.addObserver(this); }); } /** * Rend les boutons non sélectionnés. */ public void cleanButtons() { accountsButton.setFont(new Font("Lucida Grande", Font.PLAIN, 16)); accountsButton.setForeground(Color.BLACK); discussionsButton.setFont(new Font("Lucida Grande", Font.PLAIN, 16)); discussionsButton.setForeground(Color.BLACK); searchButton.setFont(new Font("Lucida Grande", Font.PLAIN, 16)); searchButton.setForeground(Color.BLACK); } @Override public void action(IDomainObject o) { } @Override public void action(Object o) { ECrud crud = (ECrud) o; switch (crud) { case UPDATE: userLabel.setText(userService.getConnectedUser().getFirstname() + " " + userService.getConnectedUser().getLastname()); configWaitingFriendshipImage(); break; case DELETE: userService.setConnectedUser(null); this.setVisible(false); this.unitOfWork.rollback(); new LoginFrame(); break; } } @Override public void action(Object crud, Object element) { } { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout(0, 0)); navPanel = new JPanel(); navPanel.setLayout(new BorderLayout(0, 0)); navPanel.setBackground(new Color(-12887656)); navPanel.setForeground(new Color(-1771521)); mainPanel.add(navPanel, BorderLayout.NORTH); titleLabel = new JLabel(); titleLabel.setEnabled(true); titleLabel.setFont(new Font("Lucida Grande", Font.BOLD, 24)); titleLabel.setForeground(new Color(-1705985)); titleLabel.setHorizontalAlignment(2); titleLabel.setText("chatbook"); navPanel.add(titleLabel, BorderLayout.WEST); userPanel = new JPanel(); userPanel.setLayout(new GridLayoutManager(1, 4, new Insets(0, 0, 0, 0), -1, -1)); userPanel.setBackground(new Color(-12887656)); navPanel.add(userPanel, BorderLayout.EAST); userLabel = new JLabel(); userLabel.setForeground(new Color(-2561551)); userLabel.setText("Label"); userPanel.add(userLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); deconnectButton = new JButton(); deconnectButton.setText(""); deconnectButton.setToolTipText("Se déconnecter"); userPanel.add(deconnectButton, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(10, 10), null, 0, false)); updateAccountButton = new JButton(); updateAccountButton.setText(""); updateAccountButton.setToolTipText("Modifier mon compte"); userPanel.add(updateAccountButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); waitingFriendshipsButton = new JButton(); waitingFriendshipsButton.setFont(new Font(waitingFriendshipsButton.getFont().getName(), Font.BOLD, waitingFriendshipsButton.getFont().getSize())); waitingFriendshipsButton.setText(""); waitingFriendshipsButton.setToolTipText("Demandes d'amitié en attente"); userPanel.add(waitingFriendshipsButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); bodyPanel = new JPanel(); bodyPanel.setLayout(new BorderLayout(0, 0)); mainPanel.add(bodyPanel, BorderLayout.CENTER); dashboardPanel = new JPanel(); dashboardPanel.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1)); bodyPanel.add(dashboardPanel, BorderLayout.NORTH); accountsButton = new JButton(); accountsButton.setText("Utilisateurs"); dashboardPanel.add(accountsButton, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(204, 32), null, 0, false)); discussionsButton = new JButton(); discussionsButton.setText("Discussions"); dashboardPanel.add(discussionsButton, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); searchButton = new JButton(); searchButton.setText("Recherche d'amis"); dashboardPanel.add(searchButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); contentPanel = new JPanel(); contentPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1)); bodyPanel.add(contentPanel, BorderLayout.CENTER); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return mainPanel; } }
lauthieb/chat-book
src/main/java/gui/MainFrame.java
248,605
package controllers; //import jdk.nashorn.internal.ir.ObjectNode; import models.Event; import models.Question; import models.User; import models.UserStats; import models.UserEventStats; import models.ReportAnalytics; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import play.data.validation.Constraints; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import play.data.Form; import views.html.dashboard.*; import views.html.chatRoom; import views.html.exceptionLandingPage; import views.html.eventSequence.eventStage1; import views.html.instructorView; import java.util.Collections; import views.html.pastEvents.pastEventsForInstructors; import java.util.List; import java.util.ArrayList; import java.util.Set; import scala.collection.JavaConverters; import java.net.MalformedURLException; import models.utils.AppException; import play.Logger; import java.util.Date; import java.util.HashSet; import static play.data.Form.form; import java.text.*; @Security.Authenticated(Secured.class) public class Dashboard extends Controller { public static Result index() { try { User currentUser = User.findByEmail(request().username()); boolean isInstructor = currentUser.isInstructor; if(isInstructor){ return ok(instructorDashboard.render((User.findByEmail(request().username())), Event.findEvent())); } else { List<Event> eventList = currentUser.EventsParticipated; User user = User.findByEmail(request().username()); UserStats userStats = UserStats.findUserStatsByUser(user); return ok(index.render(user, userStats, eventList)); }} catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were trying to retrieve your dashboard")); } } public static Result manageEvents() { try { User currentUser = User.findByEmail(request().username()); Event eventSelected = Event.findEvent(); return ok(manageEvents.render(currentUser, eventSelected, form(CreateEventForm.class), User.findAllUsers(), Event.findAllEvents())); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were retrieving the manage events page")); } } public static Result listUserJs(String divID) { try { List<User> userList = User.findAllUsers(); String output = ""; for (User u : userList) { System.out.println(output); output += u.fullname + "|"; } return ok(views.js.listUser.render(divID, output)); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were retrieving the list of users")); } } public static Result listEventJs(String divID) { try { List<Event> eventList = Event.findAllEvents(); String output = ""; for (Event e : eventList) { System.out.println(output); output += e.eventName + "|"; } return ok(views.js.listEvent.render(divID, output)); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were retrieving the list of events")); } } public static Result createEvent() { User instructor = User.findByEmail(request().username()); Form<CreateEventForm> form2 = form(CreateEventForm.class); CreateEventForm f = form2.bindFromRequest().get(); System.out.println("Read event form!!" + f.eventName); try { initEventStage(f,instructor); } catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were saving the event")); } return ok(createEventConfirmation.render((User.findByEmail(request().username())), Event.findEvent())); } private static void initEventStage(Dashboard.CreateEventForm createEventForm,User instructorUser) throws AppException,MalformedURLException,ParseException { Event event = new Event(); //need to add the instructor event.instructor = instructorUser; //Adding event name event.eventName = createEventForm.eventName; //Converting string to date //todo form changes //Date date = new SimpleDateFormat("MM/dd/yyyy").parse(createEventForm.date); DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mmaa"); event.eventDateTime = formatter.parseDateTime(createEventForm.date + " " + createEventForm.startTime); //add durations for all the phases event.phase1Duration = Integer.valueOf(createEventForm.phaseDuration); event.phase2Duration = Integer.valueOf(createEventForm.phaseDuration); event.phase3Duration = Integer.valueOf(createEventForm.phaseDuration); //Start and end time event.startTime = createEventForm.startTime; //Calculate end time using phase duration event.endDateTime=event.eventDateTime.plusMinutes(event.phase1Duration*3); //Event Description event.description = createEventForm.eventDescription; System.out.println("hashtag :" + event.description); //Scripts for all stages event.scriptPhase1 = createEventForm.script1; event.scriptPhase2 = createEventForm.script2; event.scriptPhase3 = createEventForm.script3; event.scriptPhase4 = createEventForm.script4; //Split the event descriptions event.hashes = createEventForm.hashes; System.out.println("hashtag :" + event.hashes); String[] hashtags = event.getHashTags(); for (String s : hashtags) { System.out.println("hashtag element is:" + s); } //Add participants event.participants = new ArrayList<User>(); if (createEventForm.participants != null) { System.out.println("length ************************"+ createEventForm.participants.size()); createEventForm.participants.removeAll(Collections.singleton(null)); for (String t : createEventForm.participants) { System.out.println("participants are: " + t); User p = User.findByFullname(t); System.out.println("participants fullname: " + p.fullname); event.participants.add(p); } } //create question objects event.Questions = new ArrayList<Question>(); Question q = new Question(); q.questionString = createEventForm.question; q.Option1 = createEventForm.option1; q.Option2 = createEventForm.option2; q.Option3 = createEventForm.option3; q.Option4 = createEventForm.option4; q.Answer = createEventForm.answer; System.out.println("Answer for question 1" + q.Answer); q.save(); event.Questions.add(q); Question fq = new Question(); fq.questionString = createEventForm.fquestion; fq.Option1 = createEventForm.foption1; fq.Option2 = createEventForm.foption2; fq.Option3 = createEventForm.foption3; fq.Option4 = createEventForm.foption4; fq.Answer = createEventForm.fanswer; System.out.println("Answer for question 1" + fq.Answer); fq.save(); event.Questions.add(fq); //event active status event.active = 0; //save the event event.save(); } public static Result deleteEvent(){ try { User instructor = User.findByEmail(request().username()); Form<deleteEventForm> dform = form(deleteEventForm.class); deleteEventForm d = dform.bindFromRequest().get(); //Get the corresponding event Event e = Event.findByName(d.eventNameToBeDeleted); //Mark the event as deleted- status 3 e.active = 3; e.update(); return ok(deleteEventConfirmation.render((User.findByEmail(request().username())), e)); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were discarding the event")); } } public static Result updateEvent(){ return ok(updateEventConfirmation.render((User.findByEmail(request().username())), Event.findEvent())); } public static Result getEventstoActivate() { try { List<Event> eventList = Event.getAllEventsToActivate(); StringBuilder output = new StringBuilder(); output.append("["); for (int i = 0; i < eventList.size(); i++) { output.append("{"); output.append("\"eventId\":"); output.append("\""); output.append(eventList.get(i).eventId); output.append("\""); output.append(","); output.append("\"eventName\":"); output.append("\""); output.append(eventList.get(i).eventName); output.append("\""); output.append(","); output.append("\"Date\":"); output.append("\""); output.append(eventList.get(i).eventDateTime); output.append("\""); output.append("},"); } String response = output.toString(); response = response.substring(0, response.length() - 1); response = response + "]"; System.out.println(response); // String s = "[{\"eventId\":\"jhhj\",\"eventName\":\"hjkghsjk\",\"Date\":\"jkdghs jkhsg\"}]"; return ok(response); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were activating the event")); } } public static Result getEventSummary() { try { User reportUser = User.findByEmail(request().username()); // Event reportEvent = Event.findByName(name); Event reportEvent = Event.findEvent(); return ok(report.render(reportUser, reportEvent, Event.findAllEvents())); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were summarizing the event.")); } } public static Result help() { try { User reportUser = User.findByEmail(request().username()); return ok(help.render(reportUser)); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were retrieving the help page")); } } public static Result activateEvent(Long eventId){ try { //Update the status of the event to 1 to mark that the event is activated. //find event by eventID Event event = Event.findById(eventId); //Call function to mark the event as ongoing event.markEventStatusAsOngoing(); //update the action to the database. event.update(); return ok(eventId + " Activated"); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were activating the events")); } } public static Result generateIndividualEventSummary(String eventName) { try { //Report Analytics ReportAnalytics ra = new ReportAnalytics(); //Event e=Event.findByName(eventName); System.out.println("going to call report analytics function..."); ra.analyze(eventName); String maxPercentPhase = ra.getMaxPercentPhase(); String hashTagMsgs = ra.getHashMsgs(); String collabMsg = ra.getCollabMsg(); System.out.println("Report Analytics Max Percent Phase:" + maxPercentPhase); System.out.println("Report Analytics Hash Messages:" + hashTagMsgs); System.out.println("Report Analytics collabMsg:" + collabMsg); String output = ""; if (maxPercentPhase != null && hashTagMsgs != null && collabMsg != null) { output = ra.getMaxPercentPhase() + "|" + ra.getHashMsgs() + "|" + ra.getCollabMsg(); //System.out.println("Event name "+e.eventName); //Finding the user with highest upvotes List<UserEventStats> usrEventStatsList = UserEventStats.findAllUserEventStats(); System.out.println("The user event statistics..."); int maxUpvotes = Integer.MIN_VALUE; User mostUpvotedUser = new User(); for (int i = 0; i < usrEventStatsList.size(); i++) { int currentUserUpvoteCount = usrEventStatsList.get(i).noOfUpVotesReceivedForEvent; System.out.println("current user upvotes... " + currentUserUpvoteCount); System.out.println("Fetching the current user.."); User currentUser = usrEventStatsList.get(i).user; System.out.println("current user name.." + currentUser.fullname); if (currentUserUpvoteCount > maxUpvotes) { maxUpvotes = currentUserUpvoteCount; mostUpvotedUser = currentUser; } } if (maxUpvotes > 0) output += "|" + " The most upvoted student for this event is " + mostUpvotedUser.fullname + " with " + maxUpvotes + " votes."; else output += "|" + " None of the students in this event were upvoted by his/her peers. "; } else { output = "This event is not completed. You can view the reports for this event once it is complete"; } return ok(output); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were summarizing the event")); } } public static Result instructorView() { try { // if(username == null || username.trim().equals("")) { // flash("error", "Please choose a valid username."); // return redirect(routes.Application.index()); // } User currUser = User.findByEmail(request().username()); // System.out.println("Request().username:"+ currUser.fullname); // System.out.println("User email id is " + currUser.email); return ok(instructorView.render(currUser)); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were retrieving the Instructor view")); } } public static Result instructorPastEventDiscussions() { try { List<Event> completedEvents = Event.findAllCompletedEvents(); User reportUser = User.findByEmail(request().username()); return ok(pastEventsForInstructors.render(reportUser, completedEvents)); }catch (Exception e) { e.printStackTrace(); return ok(exceptionLandingPage.render("Something went wrong while we were retrieving the past event discussions for the instructor")); } } public static class CreateEventForm { @Constraints.Required public String eventName; @Constraints.Required public String eventDescription; @Constraints.Required public String hashes; @Constraints.Required public String script1; @Constraints.Required public String script2; @Constraints.Required public String script3; @Constraints.Required public String script4; @Constraints.Required public String question; @Constraints.Required public String option1; @Constraints.Required public String option2; @Constraints.Required public String option3; @Constraints.Required public String option4; @Constraints.Required public String answer; @Constraints.Required public String fquestion; @Constraints.Required public String foption1; @Constraints.Required public String foption2; @Constraints.Required public String foption3; @Constraints.Required public String foption4; @Constraints.Required public String fanswer; @Constraints.Required public String date; //@Constraints.Required //public String endTime; @Constraints.Required public String phaseDuration; @Constraints.Required public String startTime; @Constraints.Required public List<String> participants; } public static class deleteEventForm{ @Constraints.Required public String eventNameToBeDeleted; } public static class reportForEvent { @Constraints.Required public String event; } }
dennyac/LearnLab
app/controllers/Dashboard.java
248,607
package view; import javax.swing.*; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuBar; import controller.BroadcastController; public class BarMenuView extends JMenuBar implements ActionListener { private static final long serialVersionUID = 1L; private JButton optionDisconnect; private JButton optionAccountParameters; private JButton optionOnlineUsers; private JButton optionConsultDiscussions; public BarMenuView() { int buttonLength = 70; int buttonHeight = 20; int fontSize = 12; //----------Mise en place de la barre d'options //Premier Menu : Utilisateur JMenu menuUtilisateur = new JMenu("Utilisateur"); optionDisconnect = new JButton("Se déconnecter"); optionDisconnect.setFont(new Font("Arial", Font.PLAIN, fontSize)); optionDisconnect.setSize(buttonLength,buttonHeight); optionDisconnect.addActionListener(this); menuUtilisateur.add(optionDisconnect); //--- optionAccountParameters = new JButton("Paramètres du compte"); optionAccountParameters.setFont(new Font("Arial", Font.PLAIN, fontSize)); optionAccountParameters.setSize(buttonLength,buttonHeight); optionAccountParameters.addActionListener(this); menuUtilisateur.add(optionAccountParameters); this.add(menuUtilisateur); //Second Menu : Clavardage JMenu menuPostes = new JMenu("Clavardage"); optionOnlineUsers = new JButton("Utilisateurs en ligne"); optionOnlineUsers.setFont(new Font("Arial", Font.PLAIN, fontSize)); optionOnlineUsers.setSize(buttonLength,buttonHeight); optionOnlineUsers.addActionListener(this); menuPostes.add(optionOnlineUsers); //-- optionConsultDiscussions = new JButton("Afficher clavardages en cours"); optionConsultDiscussions.setFont(new Font("Arial", Font.PLAIN, fontSize)); optionConsultDiscussions.setSize(buttonLength,buttonHeight); optionConsultDiscussions.addActionListener(this); menuPostes.add(optionConsultDiscussions); this.add(menuPostes); } public void actionPerformed(ActionEvent e) { if (e.getSource() == optionDisconnect) { /* Déconnexion de l'utilisateur */ System.out.println("Déconnexion"); model.Utilisateur.SetUtilisateurActuel(null); BroadcastController.GetInstance().Deconnexion(); MainView.AfficherAuthentification(); } else if (e.getSource() == optionAccountParameters) { /* Afficher les paramètres de compte de l'utilisateur */ MainView.AfficherParametresDuCompte(model.Utilisateur.GetUtilisateurActuel()); } else if (e.getSource() == optionOnlineUsers) { /* Afficher la liste des utilisateurs en ligne */ // MainView.ShowCreateDiscussion(); MainView.AfficherUtilisateursEnLigne(); } else if (e.getSource() == optionConsultDiscussions) { /* Affiche les discussions en cours */ // MainView.ShowSeeAllUsers(); MainView.AfficherClavardagesEnCours(); } } }
Pepotrouille/ChatSystem
src/main/java/view/BarMenuView.java
248,608
/* * Copyright of JyNI: * Copyright (c) 2013, 2014, 2015, 2016, 2017 Stefan Richthofer. * All rights reserved. * * * Copyright of Python and Jython: * Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, * 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 * Python Software Foundation. * All rights reserved. * * * This file is part of JyNI. * * JyNI is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * JyNI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with JyNI. If not, see <http://www.gnu.org/licenses/>. */ package JyNI; import java.util.AbstractList; import java.util.Collection; import org.python.core.PyObject; import JyNI.gc.*; import java.lang.ref.WeakReference; /** * JyList is an implementation of java.util.List, that * redirects all list-calls to a native backend, namely * a Python PyListObject as defined in listobject.h. * backendHandle must be a valid pointer to the backing * c-struct. The purpose of this implementation is to * allow perfect sync between a Jython org.python.core.PyList * object and a native PyListObject as defined in listobject.h. * Since the native object allows modification via macros, there * is no way to detect that modification and mirror it on java-side. * So the only way is, not to mirror anything, but to actually map * all list accesses to the original native data. * * If JyNI syncs a native PyListObject to a jython PyList, * there are two cases. If the original object is native, a * Jython PyList is created with a JyList as backend. * If the original object is a Jython PyList, we must replace * its backend with a JyList. First we setup an appropriate * native PyListObject. Then we convert all objects from * the non-native PyList to native PyObjects and insert them * into the native list object. Having that done, we setup * a JyList with our new native PyListObject as backend and * finally replace the original backend of the PyList with * our newly created JyList. However since PyList's backend * is stored in a private final field, replacing it is a rather * sneaky operation, which indeed might corrupt Extensions written * in Java, that also customize backends of PyLists. * Future JyNI versions will provide configuration-options * to tune this behavior - for instance to sync the original * backend as far as possible, maybe even by polling the native * list for changes. * * See http://docs.oracle.com/javase/specs/jls/se5.0/html/memory.html#17.5.3 * for information about subsequently modifying final fields. * See also these discussions about setting private final fields: * stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection * stackoverflow.com/questions/4516381/changing-private-final-fields-via-reflection * Note that PyList sets its backend in the constructor, so * replacing it should work like mentioned in the second discussion. * (By the way, I am not involved in any of them, I just found them * and thought it would be useful here.) */ public class JyList extends AbstractList<PyObject> implements TraversableGCHead, PyObjectGCHead { long backendHandle; Object headLinks; /* This is actually supposed to be a SoftReference, but we use a * WeakReference for easier debugging for now. */ WeakReference<PyObject> frontend; public JyList(long backendHandle) { super(); this.backendHandle = backendHandle; new JyWeakReferenceGC(this); } public JyList(Collection<PyObject> c, long backendHandle) { super(); this.backendHandle = backendHandle; addAll(0, c); new JyWeakReferenceGC(this); } public PyObject getPyObject() { return frontend != null ? frontend.get() : null; } public void setPyObject(PyObject object) { // System.out.println("JyList.setPyObject"); frontend = new WeakReference<>(object); } public void setLinks(Object links){ headLinks = links; // System.out.println("JyList setLinks "+this); // for (PyObjectGCHead op: ((java.util.List<PyObjectGCHead>) links)) { // System.out.println(" "+op+" - "+op.getPyObject()); // } } @Override public int setLink(int index, JyGCHead link) { // System.out.println(this.getClass()+".setLink ("+System.identityHashCode(this)+") "+index); int result = DefaultTraversableGCHead.setLink(headLinks, index, link); if (result == 1) { headLinks = link; return 0; } return result; } @Override public int insertLink(int index, JyGCHead link) { return DefaultTraversableGCHead.insertLink(headLinks, index, link); } @Override public int clearLink(int index) { return DefaultTraversableGCHead.clearLink(headLinks, index); } @Override public int clearLinksFromIndex(int startIndex) { return DefaultTraversableGCHead.clearLinksFromIndex(headLinks, startIndex); } @Override public int jyTraverse(JyVisitproc visit, Object arg) { return DefaultTraversableGCHead.jyTraverse(headLinks, visit, arg); } @Override public long[] toHandleArray() { return DefaultTraversableGCHead.toHandleArray(headLinks); } @Override public void ensureSize(int size) { headLinks = DefaultTraversableGCHead.ensureSize(headLinks, size); } @Override public void printLinks(java.io.PrintStream out) { DefaultTraversableGCHead.printLinksAsHashes(headLinks, out); } @Override public long getHandle() { return backendHandle; } /*public void installToPyList(PyList list) { try { Field backend = PyList.class.getDeclaredField("list"); backend.setAccessible(true); backend.set(list, this); } catch (Exception e) { System.err.println("Problem modifying PyList backend: "+e); } } public List<PyObject> installToPyListAndGetOldBackend(PyList list) { try { Field backend = list.getClass().getDeclaredField("list"); backend.setAccessible(true); List<PyObject> er = (List<PyObject>) backend.get(list); backend.set(list, this); return er; } catch (Exception e) { System.err.println("Problem in installToPyListAndGetOldBackend: "+e); return null; } }*/ public PyObject get(int index) { //System.out.println(backendHandle+" JyList-get "+index); return JyNI.JyList_get(backendHandle, index); } public int size() { //System.out.println(backendHandle+" JyList-size"); return JyNI.JyList_size(backendHandle); } public PyObject set(int index, PyObject o) { return JyNI.JyList_set(backendHandle, index, o, JyNI.lookupNativeHandle(o)); } public void add(int index, PyObject o) { JyNI.JyList_add(backendHandle, index, o, JyNI.lookupNativeHandle(o)); } public PyObject remove(int index) { return JyNI.JyList_remove(backendHandle, index); } }
Stewori/JyNI
JyNI-Java/src/JyNI/JyList.java
248,609
Coordination Mechanisms ____________________________________________________________________________ GitHub URL : https://github.com/techhue/FlipkartJEDI Questions : Discussions : https://tinyurl.com/ydylpn64 Must Share Your PRIMARY GMAIL ID Documents Will Be Shared ONLY ON your PRIMARY GMAIL ID Assignments ____________________________________________________________________________ DAY 1: Reading and Practice Linux Pocket Guide Till Page 63 DAY 2: Reading and Practice Linux Pocket Guide Till Page 131 DAY 3: Reading and Practice Git Commands Git Study Material Practical Assignments ____________________________________________________________________________ Simulate Branching WorkFlow As A Project Workflow Master, Dev and Testing Branch Simulate Branching Workflow As A Developer Dev Branch Is Developer Branch Implement Feature with Various Ideas and Approaches Use Branching To Maintain Your Ideas Implementation DAY 4: ASSIGNMENT 1 ____________________________________________ Write Sum Function In C Language // Which Will Return Valid SUM For ANY X, Y // Otherwise Print Can't Calculate SUM int sum(int x, int y) { } ASSIGNMENT 2 ____________________________________________ Write Sum Function In C Language // Which Will Return Valid SUM For ANY X, Y // Otherwise RETURN ERROR int sum(int x, int y) { } PROVE YOUR CODE IS RIGHT OR WRONG REASON WITH DEFINITION DATA TYPE ++++++++++++++++++++++++++++++++++++++++++++++++++++++ --> RAISE HAND IF DONE READING AND PRACTICE ASSIGNMENT ++++++++++++++++++++++++++++++++++++++++++++++++++++++ Hardware/Software Requirements ____________________________________________________________________________ Computer/Laptop with 8GB+ RAM and Minimum Core i5 Processor Operating System: Ubuntu 20.04, 64 Bit [ Desktop Edition ] SDK: Oracle Java Development Kit(JDK) 9+ Editors: Sublime Text, Visual Code Design For Programmers Light Weight Cross Platform [ Linux, MacOSX and Windows ] Install on Virtualisation Environment e.g. Oracle VirtualBox Setup Environment ____________________________________________________________________________ 1. Virtual Environment Easy Maintain. 2. Must Have Same Environment: Ubuntu 20.04, 64 Bit [ Desktop Edition ]. 3. Unix/Linux Part of Agenda 4. Design Perceptive Set of Nodes Childern of intelligene ____________________________________________________________________________ Applications Huawei.Router.Details.txt Public Calibre Library Library contact.txt CallDetails.txt Movies fibo.swift Desktop Music hello.swift Documents NITCAAEmailID.txt someData Downloads Pictures temp /Users/intelligene Parent of intelligene is Users Parents of Users / [ Root Directory ] In Case Windows What is The Root Directory? - C: Drive - e.g. In Mac World Achieve | C: Aspire | D: Inspire | E: MacOSX | H: Parent of These One Is Volumes Volumes has parent / Design Questions Should you start your filesystem design with DESIGN CHOICE: One Node or Multiple Node Which Design Choice Is Better? and Why? Training Pedagogy ____________________________________________________________________________ Design Oriented ANY QUESTION or DOUBT? ____________________________________________________________________________ Feel Free To Ask.... ____________________________________________________________________________ Unix OS Ken Thomson and Denish Ritchie Assembly Language Created C Language, Inspired From Language B ls : List Immediate Child Nodes ls command with Options/Switches ls -l : Detailed Listing ls -a : Shows all files Including Hidden Order Doesn't Matters ls -l -a ls -a -l ls -al ls -la Colored Output ls -lG pwd : Present Working Directory ____________________________________________________________________________ In Unix Everything Is File Files and File Type In Unix Experiment Commands ls -l drwx------@ 4 intelligene staff 170 Nov 27 15:36 Applications Directory File: Metadata About Other Files -rw-r--r-- 1 intelligene staff 244 Jul 9 2019 contact.txt Regular File First Character is d or - Experiment Commands cd /dev ls -l crw------- 1 intelligene staff 0, 0 Apr 28 08:54 console Character File: File Which is Read/Written Character By Character brw-r----- 1 root operator 1, 0 Apr 28 08:43 disk0 Block File: File Which is Read/Written Block By Block Block Size: 512 Bytes First Character is c or b File Size is 1024 Bytes -> 2 Block Sizes Block Size: 512 Bytes The file mode printed under the -l option consists of the entry type, owner permis- sions, and group permissions. The entry type character describes the type of file, as follows: b Block special file. c Character special file. d Directory. mkdir FileName - Regular file. touch FileName l Symbolic link. s Socket link. p FIFO. ____________________________________________________________________________ Discussion Questions What is A File? ____________________________________________________________________________ Path Concept ____________________________________________________________________________ Path: Branch In Tree Ending at Node Terminal Node: Documents Root Node: / (Root) Absolute Path: Path Starting From / Node /Users/intelligene/Documents cd /Users/intelligene/Documents Relative Path: Path Relative to Present Working Directory cd Documents Nodes Coming In Branch/Path / Users intelligene Documents Traversal: Bi Directional Child To Parent cd .. : Move to Immediate Parent Node cd . : Remain In Current Node(Directory) Parent To Child cd PATH cd ./Documents/Trainings/ Change To Home Directory cd ~ cd ____________________________________________________________________________ Creation of Nodes mkdir NODE mkdir -p PATH Creates BRNACH starting from FIRST NODE If It Doesn't Exists touch NODE cp NODE cp -r NODE mv SOURCE_PATH/NODE DEST_PATH/NODE Changes Parent Node SOURCE_PATH and DEST_PATH Are Same: Used For Renaming Deletion of Nodes Deletes Single Node ___________________ rm NODE rmdir NODE Removes Empty Directory Node Deletes Branch Provided Every Node is Empty rmdir -p PATH Removes Branch Starting From FIRST NODE OF PATH Deletes All Branches rm -R NODE Subtree including Parent NODE ____________________________________________________________________________ Log Files /var/log/syslog 10 Lines Of Files Starting/Ending head FILE tail FILE ____________________________________________________________________________ File Permission Model POSIX Permission Model - rw- r-- r-- 1 intelligene staff 244 Jul 9 2019 contact.txt Regular File Creator Friends Others _____________________________ Owner Group Others User RWX RWX RWX -rw-r--r-- 1 intelligene staff 0 Apr 28 12:34 AnushkaSharma intelligene staff others rw r r Paranoid Approach ____________________________________________________________________________ Owner Group Others RW R R RWX 000 0 001 1 EXECUTE 010 2 WRITE 011 3 100 4 READ 101 5 110 6 111 7 4 READ 2 WRITE 1 EXECUTE chmod u+x FILE Regular File : Default Permission umask Mac OSX Default Value for umask is 0022 666 - 0022 = 644 Ubuntu Default Value for umask is 0002 666 - 0002 = 664 Directory File : Default Permission rwx r-x r-x 777 - 0022 = 755 Link File : Default Permission 777 - 0022 = 755 ____________________________________________________________________________ System Design Thinking ____________________________________________________________________________ Privileage Design Never Ever Should Be Given By Name Scope Design Never Ever Should Be BROADEST Narrowest Scope First, Then Broader, Then Broader... Scope Design Examples Unix File Permission Design: Owner Level, Group Level, Others Level Bash Configrations Design: Session Level, User Level, System Level Git Configrations Design: Local Level, Global Level, System Level ____________________________________________________________________________ Email: Sunny Leone On Beach! SunnyLeone.jpg It's Virus Force To Download Scripts It's Not Virus SunnyLeone.jpg > SunnyLeone.exe Copy In Some Hidden Folder Hide Folder System Wide System Configuration ____________________________________________________________________________ Terminal Environment env export DING_DONG="Balleeee Balleeee" export PATH=$PATH:/Users/intelligene/Documents/FlipkartBatch/Heroines What is Terminal? Session To The OS What is Shell? Language Interpreter Configure System Session Level User Level: Applicable To All Sessions < ~/.bashrc System Level /etc/bashrc Scope Design Never Ever Should Be BROADEST Narrowest Scope First, Then Broader, Then Broader... Vim Editor : Mode Based Editor ____________________________________________________________________________ ~/.vimrc Command Mode -----> i ----> Insert Mode Command Mode <---- Esc----- Insert Mode Command Mode -----> Shift+V ----> Visual Line Mode Command Mode -----> Ctrl+V ----> Visual Block Mode Command Mode /SearchCriteria After Forwards Slash n Go To Next Search Item N Go To Previous Search Item Shift : :w Write To File :q Quit :q! Quit Without Saving :wq Write and Quit yy Current Line Yanking p Pasting Nyy N lines Yanked/Copied p N lines Pasted dd Current Line Deleted u Undo ctrl+r Redo Ndd N lines Deleted :set number To Show Line Numbers :set nonumber To Disable Line Numbers :%s/SOURCE_TEXT/SUSTITUTE_TEXT/gc g means globally whole file and c means confirmation Learning and Practicing Vim Basics ____________________________________________________________________________ vimtutor stdout and stdin Concepts ____________________________________________________________________________ printf Writes To A File: stdout By Default stdout file is pointing to terminal file cat AmirKhan write content to stdout file -> /dev/ttys0000 cat AmirKhan > DingDong write content to DingDong file scanf Reads From A File: stdin By Default stdout file is pointing to standard keyboard Soft and Hard Links ____________________________________________________________________________ ln -s Heroines/AshwaryaRai.doc ash IntelligeneMachine:FlipkartBatch intelligene$ ls -l lrwxr-xr-x 1 intelligene staff 24 Apr 29 09:54 ash -> Heroines/AshwaryaRai.doc Hard Link Creation ____________________________________________________________________________ IntelligeneMachine:Heroines intelligene$ ln AliaBhat Alia IntelligeneMachine:Heroines intelligene$ ls -l -rw-rw-r-- 2 intelligene staff 0 Apr 29 10:17 Alia -rw-rw-r-- 2 intelligene staff 0 Apr 29 10:17 AliaBhat IntelligeneMachine:Heroines intelligene$ ln -s AliaBhat BhatDaughter IntelligeneMachine:Heroines intelligene$ ls -l -rw-rw-r-- 2 intelligene staff 0 Apr 29 10:17 Alia -rw-rw-r-- 2 intelligene staff 0 Apr 29 10:17 AliaBhat lrwxr-xr-x 1 intelligene staff 8 Apr 29 10:48 BhatDaughter -> AliaBhat File Idea ____________________________________________________________________________ What is The File? Few More Commands ____________________________________________________________________________ du du -ah file stat chmod chown chgrp find locate grep egrep zip tar diff -u Hello.c HelloMore.c diff -ur DIR1 DIR2 mount Make a disk partition accessible umount Unmount a disk partition (make it inaccessible) df mkdir /mnt/mydir mount /dev/hda1 /mnt/mydir mydir Mount Point df /mnt/mydir Device Files Existing In Directory: /dev/ Linux/Ubuntu Naming Conventions hda0 hda1 // IDE Hard Disk sda0 // SCSI Architecture sda1 sda2 MacOSX Naming Conventions disk0 disk0s1 disk0s2 disk1 Mount Command Syntax df /mnt/mydir mkdir /mnt/mydir Create Mount Point: mydir mount DEVICE_FILE MOUNT_POINT mount /dev/hda1 /mnt/mydir unmount DEVICE_FILE rmdir MOUNT_POINT unmount -a Groups In Unix groups : Print the group membership of a user groupadd : Create a new group groupdel : Delete a group groupmod : Modify a group Change User Password ____________________________________________________________________________ passwd GIT Distributed Version Control System ____________________________________________________________________________ Installation And Configuration 1. Install GIT MacOSX brew install git Ubuntu sudo apt install git snap install git 2. Create GitHub Account Getting Started with Git and GitHub ____________________________________________________________________________ 1. Create Git Repository at GitHub 2. mkdir LearnGIT in FlipkartBatch 3. cd LearnGit 4. git clone of ThinkFlipkart Creating Git Repository Locally ____________________________________________________________________________ 1. Create Git Repository From Already Existing Project LOCALLY git init Initialized empty Git repository git add FILES git commit Cloning Remote Repository ____________________________________________________________________________ git clone REMOTE_GIT_REPOSITORY_URL Git Commands ____________________________________________________________________________ git log : Log Of All Commits Done Git Configuration ____________________________________________________________________________ Configuration Levels ____________________________________________________________________________ Local : Applicable To One Git Repository Global : Applicable To All Git Repositories For A User System : Applicable To All Git Repositories For All Users Configuration SCOPE DESIGN ____________________________________________________________________________ Local < Global < System Git Configuration Options ____________________________________________________________________________ --local LOCAL_GIT_REPOSITORY/.git/config --global ~/.gitconfig --system IN UBUNTU: /etc/gitconfig IN MACOSX: /usr/local/etc/gitconfig IN WINDOWXP : C:\Documents and Settings\All Users\Application Data\Git\config IN WINDOWSVISTA : C:\ProgramData\Git\config Configuration Application Order ____________________________________________________________________________ System Configuration Then Global Configuration Then Local Configuration To Achieve: Narrowest Scope Takes Precedences git config --list Actual Configrations Which Are Got Applied Finally! git config --global user.name "Amarjit Singh" git config --global user.email "[email protected]" git config --global core.editor "vim" git config --system user.name "Ding Dong" git config --local user.email "[email protected]" git config --system -e git config --global -e git config --local -e git status git log git log -p -p means Patch Mode i.e. Diff Mode git log -p 2 git log --pretty=online git diff git diff --cached git add FILE1 FILE2 FILE3 git restore --cached FILE git commit git rm FILE git mv SOURCE_FILE DESTINATION_FILE git push origin master Push Local Repository ChangeSets To Remote Repository git pull Pull Remotes Repository ChangeSets To Local Repository git remote git branch git remote show origin
 ____________________________________________________________________________ Pulling Changes : Happening In Remote Repository ____________________________________________________________________________ Changes Are Pushed By Other Users of Repository Pushed To Remote Repository 1. Create Commit Directly in Remote Repository 2. git pull To Sync Local Repository with Remote Repository ++++++++++++++++++++++++++++++++++++++++++++ --> RAISE HAND IF ABOVE EXPERIMENTS ARE OVER ++++++++++++++++++++++++++++++++++++++++++++ ____________________________________________________________________________ ALWAYS DO FOLLOWING ____________________________________________________________________________ git pull BEFORE DOING git push git pull Consists of Following Two Step Processes git fetch git merge Tagging Commit In Branch ____________________________________________________________________________ git tag -a v0.1 -m "Version 0.1" git tag git show v0.1 git tag -a v0.05 6f2448d9c1de git tag -d v0.05 git log cat .git/HEAD cat .git/refs/heads/master git log git push origin v0.1 git push origin --tags Git Branching ____________________________________________________________________________ git branch Show Branches Available git branch testing Creates New Branch git branch git checkout testing Switches To testing Branch git branch Branching Experiment ____________________________________________________________________________ Create Testing Branch Make Testing Branch Current Commit 1 ChangeSet to Testing Branch Make Master Branch Current Commit 1 ChangeSet to Master Branch Check Values of Following Files and REASON IT cat .git/refs/heads/master cat .git/refs/heads/testing Branch Merging git checkout TARGET_BRANCH git merge BRANCH_NAME Merge Conflict Simualte Merge Conflict Scenario Resolve Merge Conflict While Merging Merge Code 3-Way Merge Tools Distributed Version Control System Sequence Of Commands To Achieve Above Idea ____________________________________________________________________________ git branch testing git branch git checkout testing git branch git branch cd SourceCode/ cd Maths/ vim Numbers.c git diff git add Numbers.c git status git diff --cached git commit git log cd ../.. cat .git/refs/heads/master git branch git log git branch git log git checkout master git branch git log git branch cd SourceCode/ cd String/ vim String.cpp git diff git add String.cpp git diff --cached git commit git log cd .. cd .. cat .git/refs/heads/master cat .git/refs/heads/testing JAVA PROGRAMMING LANGUAGE ____________________________________________________________________________ Java Softwares Installation ____________________________________________________________________________ Java JDK 9+ TEST YOUR ENVIRONMENT : COMMANDS TO COMPILE AND RUN JAVA CODE ______________________________________________________________________________ Create Following Things Hello.java mkdir ClassFiles javac Hello.java -d ClassFiles // Compilation By Invoking Java Compiler // Result Will Hello.class File // -d Destination of .class Files java -cp ClassFiles/ learnJava.Hello // Invoking JVM // Please Load learnJava.Hello // Search main Function // Start Execution From main Function . ├── ClassFiles │   └── learnJava │   └── Hello.class └── Hello.java java Hello.java ++++++++++++++++++++++++++++++++++++++++ RAISE HAND WHEN FOLLOWING ARE DONE ++++++++++++++++++++++++++++++++++++++++ ____________________________________________________________________________ ASSIGNMENT 1 ____________________________________________ Write Sum Function In C Language // Which Will Return Valid SUM For ANY X, Y // Otherwise Print Can't Calculate SUM int sum(int x, int y) { } ASSIGNMENT 2 ____________________________________________ Write Sum Function In C Language // Which Will Return Valid SUM For ANY X, Y // Otherwise RETURN ERROR int sum(int x, int y) { } PROVE YOUR CODE IS RIGHT OR WRONG REASON WITH DEFINITION DATA TYPE ++++++++++++++++++++++++++++++++++++++++ RAISE HAND WHEN ABOVE ARE DONE ++++++++++++++++++++++++++++++++++++++++ ____________________________________________________________________________ DESIGN 1 : BAD CODE int sum(int x, int y) { return x + y; } ____________________________________________________________________________ DESIGN 2 : BAD CODE int sum(int a,int b) { long int res = a + b; // res contains already overlowed result // INT_MIN <= res INT_MAX // Violates Closure Property/Law // Following CONDITION is ALWAYS FALSE if(res > INT_MAX || res < INT_MIN){ printf(""Cant print sum""); return -1; } else return (int)res; } ____________________________________________________________________________ DESIGN 3: BAD CODE // API Design Wrong MEss long long sum(long long int a,long long int b){ // NOT Portable Code // Asssuming Hardware Architecture if(a>0 && b>0 && a+b<0 ) { printf(""Can't calculate sum""); } else if(a<0 && b<0 && a+b>0){ printf(""Can't calculate sum""); } else printf(""%lld"", a+b); } ____________________________________________________________________________ DESIGN 4: BAD CODE int sum(int x, int y) { long nx=x,ny=y; nx+=ny; if(nx>INT_MAX || nx<INT_MIN) { printf(""can't print valid sum""); exit(1); } return (int)(nx); } ____________________________________________________________________________ DESIGN 5: RIGHT Directional int sum(int x,int y) { int res = (x+y); if(res-y == x and res-x == y) return res; printf(""Error : Can't calculate valid sum.\n""); print(""Returning the first 32 bits of computed sum.\n"") exit(1); } ____________________________________________________________________________ DESIGN 6: BAD CODE int sum(int a, int b){ long result = (long)a + (long)b; if(result>INT_MAX||result<INT_MIN){ printf(""Can't calculate valid sum\n""); return 0; } else // Overflow/Underflow return (int)result; } ____________________________________________________________________________ DESIGN 8: RIGHT Directional int sum(int a,int b){ int x = a+b; if(a>0 && b>0){ if(x>a) return x; else printf(""Invalid""); } else if(a<0 && b<0){ if(x<a) return x; else printf(""Invalid""); } return x; } ____________________________________________________________________________ // NOT RESPETING TYPE DEFINITION // int sum (int a, int b) { long int sum = (long int)a + (long int)b; if (sum > (long int)INT_MAX || sum < (long int)INT_MIN) {printf(""Sum exceeds int range\n"");exit(1);} else return a + b; } ____________________________________________________________________________ int sum(int x,int y){ int upper_bound=INT_MAX; int lower_bound=INT_MIN; if(y>=0){ /// if( x>=0 && upper_bound-x< y){ printf(""error\n""); exit(0); } } else{ if(x<=0 && lower_bound-x>y){ printf(""error\n""); exit(0); } } return x+y; } ____________________________________________________________________________ Another Approach int sum(int x, int y) { int result = (x+y); if(x>0 && y>0 && (result)<0) { printf(""Can't Calculate Sum""); return -1; } else if(x<0 && y<0 && (result)>0) { printf(""Can't Calculate Sum""); return -1; } else return result; } ____________________________________________________________________________ int sum(int a, int b){ // Good Check if((a >= 0 && b > INT_MAX-a) || (a <=0 && b < INT_MIN-a)){ printf(""Can't Calculate the Sum""); // POSSIBLE SUM return -1; } return (a+b); } _____________________________ CLIENT CODE int result = sum(a, b); ____________________________________________________________________________ DESIGN : GOOD CODE DESIGN THINKING: THINKING in ONLY ONE LAYER - LANGUAGE LAYER #include <limits.h> // DEFAULT int is Signed int sum(signed int si_a, signed int si_b) { signed int sum = 0; // Type Safe Code // Following Two Lines // Are Repecting Data Type Definition: // int Data Type if (((si_b > 0) && (si_a > (INT_MAX - si_b))) || ((si_b < 0) && (si_a < (INT_MIN - si_b)))) { /* Handle error */ printf("Can't Calculate SUM") } else { sum = si_a + si_b; } return sum; } ____________________________________________________________________________ Prove Int In C = Int In Java? Prove Int In Java = Int In C++? Prove Int In C = Int In C++? Fundamental Thinking ____________________________________________________________________________ OverFlow And Underflow Fundamental Part of System [Finite] What is Far More Fundamental Value or Type Variable Language Designer Thinking ____________________________________________________________________________ Language Design Ballee Balleee Language Data Type int In Balleee Ballee Which Design You Will Prefer and Why? Object Oriented Design ______________________________________________________________________________ Behaviour Deriven Design Behaviour | Messages | Operations Objects Talks With Each Others Using Message Passging Object Oriented Design Concepts : Revisit ______________________________________________________________________________ 1. Encapsulation 2. Inheritance 3. Polymorphism 4. Abstraction 5. Composite System Design Principles ______________________________________________________________________________ Fundamental Principles Scope Design Principles Because Localisation Happens In System Design Towards Abstrat Type Rather Than Concerete Type Design Towards Interfaces Rather Than Concerete Classes Interfaces Brings Contract In System Design By Conventions When Everyone Respect Conventions It Brings Trust In System System Based Trust Works Better Design By Configuration(Rules) Rules Are Fixed System Evolution Stops Design Towards Immutability Rather Than Mutability Classes Not Meant To Subclassed Must Be Final Member Functions Not Meant To Be Overridden Must Be Final Member Varibles Not Meant To Be Changing Must Be Final SOLID Principles ______________________________________________________________________________ 1. Single Repsonility Design Principle 2. Open Close Principle Classes/Types Are Open Extension But Close Modification Learning Principles ______________________________________________________________________________ Chaos is a Ladder :P
 First Choas Than Order! Toughest Things In This World is Unlearning! System Design Thining ____________________________________________________________________________ Where To Start? ____________________________________________________________ Should You Design System Based On Configuration(Rules)? Mind Focused Towards States and Rules Rules Meant To Be Broken! Should You Design System Based On Conventions? Mind Focused Towards Contracts/Trust e.g. Design Towards Interfaces Rather Than Concerete Classes Design By Conventions VS Design By Configurations ____________________________________________________________ Design By Conventions is Better Con Function As An Idea ______________________________________________________________________________ Function As Procedure | Task | Routine | Method ______________________________________________________________________________ Definition: Sequence of Instuctions Function Type ______________________________________________________________________________ Definition: Function is Type Function Type = { Operations, Range } Function is Lambda ______________________________________________________________________________ Special Case of Lambda Lambda ______________________________________________________________________________ It is a Context Which Captures Immediate Context Around It Override equal Method : Best Practices ______________________________________________________________________ - There are a number of routine steps that you need to go through in an equals method: - Whenever you override the equals method, you must provide a compatible hashCode method as well - It is common for equal objects to be identical, and that test is very inexpensive. - Every equals method is required to return false when comparing against null. - Since the equals method overrides Object.equals, its parameter is of type Object, and you need to cast it to the actual type so you can look at its instance variables. Before doing that, make a type check, either with the getClass method or with the instanceof operator. - Finally, compare the instance variables. Use == for primitive types. How- ever, for double values, if you are concerned about ±∞ or NaN, use Double.equals. For objects, use Objects.equals, a null-safe version of the equals method. The call Objects.equals(x, y) returns false if x is null, whereas x.equals(y) would throw an exception. - The hashCode and equals methods must be compatible: If x.equals(y), then it must be the case that x.hashCode() == y.hashCode() - A hash code is an integer that is derived from an object. - Hash codes should be scrambled—if x and y are two unequal objects, there should be a high probability that x.hashCode() and y.hashCode() are different. equals Contract In Java Specification _____________________________________________________________________ public boolean equals(Object obj) Indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. //____________________________________________________________ For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. _____________________________________________________________________ class Money { int amount; String currencyCode; } Money income = new Money(55, "USD"); Money expenses = new Money(55, "USD"); boolean balanced = income.equals(expenses) class Money { int amount; String currencyCode; @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Money)) return false; Money other = (Money)o; boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); return this.amount == other.amount && currencyCodeEquals; } } class WrongVoucher extends Money { private String store; @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof WrongVoucher)) return false; WrongVoucher other = (WrongVoucher)o; boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null) || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode)); boolean storeEquals = (this.store == null && other.store == null) || (this.store != null && this.store.equals(other.store)); return this.amount == other.amount && currencyCodeEquals && storeEquals; } // other methods } At first glance, the Voucher class and its override for equals() seem to be correct. And both equals() methods behave correctly as long as we compare Money to Money or Voucher to Voucher. But what happens, if we compare these two objects? Money cash = new Money(42, "USD"); WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon"); voucher.equals(cash) => false // As expected. cash.equals(voucher) => true // That's wrong. That violates the symmetry criteria of the equals() contract ____________________________________________________________________________ From saurav anand to Everyone: (02:22 PM) 
sir rw-rwxrwx
is not making the file run
 From Anil Bansal to Everyone: (02:22 PM) 
if the execute permission is given to others then will the owner be able to execute it?
 From saurav anand to Everyone: (02:22 PM) 
bur x permission is with grp ____________________________________________________________________________ // Sahaj int a[2][2];
 printf("%p\n%p\n",a,*a);
subhash-arabhi/engineering_work
flipkart/LearnGit/Discussions.java
248,610
/* * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package java.time; import static java.time.LocalTime.MICROS_PER_SECOND; import static java.time.LocalTime.MILLIS_PER_SECOND; import static java.time.LocalTime.NANOS_PER_SECOND; import static java.time.LocalTime.SECONDS_PER_DAY; import static java.time.LocalTime.SECONDS_PER_HOUR; import static java.time.LocalTime.SECONDS_PER_MINUTE; import static java.time.temporal.ChronoField.INSTANT_SECONDS; import static java.time.temporal.ChronoField.MICRO_OF_SECOND; import static java.time.temporal.ChronoField.MILLI_OF_SECOND; import static java.time.temporal.ChronoField.NANO_OF_SECOND; import static java.time.temporal.ChronoUnit.DAYS; import static java.time.temporal.ChronoUnit.NANOS; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalQuery; import java.time.temporal.TemporalUnit; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; import java.util.Objects; /** * An instantaneous point on the time-line. * <p> * This class models a single instantaneous point on the time-line. * This might be used to record event time-stamps in the application. * <p> * The range of an instant requires the storage of a number larger than a {@code long}. * To achieve this, the class stores a {@code long} representing epoch-seconds and an * {@code int} representing nanosecond-of-second, which will always be between 0 and 999,999,999. * The epoch-seconds are measured from the standard Java epoch of {@code 1970-01-01T00:00:00Z} * where instants after the epoch have positive values, and earlier instants have negative values. * For both the epoch-second and nanosecond parts, a larger value is always later on the time-line * than a smaller value. * * <h2>Time-scale</h2> * <p> * The length of the solar day is the standard way that humans measure time. * This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds, * forming a 86400 second day. * <p> * Modern timekeeping is based on atomic clocks which precisely define an SI second * relative to the transitions of a Caesium atom. The length of an SI second was defined * to be very close to the 86400th fraction of a day. * <p> * Unfortunately, as the Earth rotates the length of the day varies. * In addition, over time the average length of the day is getting longer as the Earth slows. * As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds. * The actual length of any given day and the amount by which the Earth is slowing * are not predictable and can only be determined by measurement. * The UT1 time-scale captures the accurate length of day, but is only available some * time after the day has completed. * <p> * The UTC time-scale is a standard approach to bundle up all the additional fractions * of a second from UT1 into whole seconds, known as <i>leap-seconds</i>. * A leap-second may be added or removed depending on the Earth's rotational changes. * As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where * necessary in order to keep the day aligned with the Sun. * <p> * The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds. * Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and * alterations to the length of the notional second. As of 2012, discussions are underway * to change the definition of UTC again, with the potential to remove leap seconds or * introduce other changes. * <p> * Given the complexity of accurate timekeeping described above, this Java API defines * its own time-scale, the <i>Java Time-Scale</i>. * <p> * The Java Time-Scale divides each calendar day into exactly 86400 * subdivisions, known as seconds. These seconds may differ from the * SI second. It closely matches the de facto international civil time * scale, the definition of which changes from time to time. * <p> * The Java Time-Scale has slightly different definitions for different * segments of the time-line, each based on the consensus international * time scale that is used as the basis for civil time. Whenever the * internationally-agreed time scale is modified or replaced, a new * segment of the Java Time-Scale must be defined for it. Each segment * must meet these requirements: * <ul> * <li>the Java Time-Scale shall closely match the underlying international * civil time scale;</li> * <li>the Java Time-Scale shall exactly match the international civil * time scale at noon each day;</li> * <li>the Java Time-Scale shall have a precisely-defined relationship to * the international civil time scale.</li> * </ul> * There are currently, as of 2013, two segments in the Java time-scale. * <p> * For the segment from 1972-11-03 (exact boundary discussed below) until * further notice, the consensus international time scale is UTC (with * leap seconds). In this segment, the Java Time-Scale is identical to * <a href="http://www.cl.cam.ac.uk/~mgk25/time/utc-sls/">UTC-SLS</a>. * This is identical to UTC on days that do not have a leap second. * On days that do have a leap second, the leap second is spread equally * over the last 1000 seconds of the day, maintaining the appearance of * exactly 86400 seconds per day. * <p> * For the segment prior to 1972-11-03, extending back arbitrarily far, * the consensus international time scale is defined to be UT1, applied * proleptically, which is equivalent to the (mean) solar time on the * prime meridian (Greenwich). In this segment, the Java Time-Scale is * identical to the consensus international time scale. The exact * boundary between the two segments is the instant where UT1 = UTC * between 1972-11-03T00:00 and 1972-11-04T12:00. * <p> * Implementations of the Java time-scale using the JSR-310 API are not * required to provide any clock that is sub-second accurate, or that * progresses monotonically or smoothly. Implementations are therefore * not required to actually perform the UTC-SLS slew or to otherwise be * aware of leap seconds. JSR-310 does, however, require that * implementations must document the approach they use when defining a * clock representing the current instant. * See {@link Clock} for details on the available clocks. * <p> * The Java time-scale is used for all date-time classes. * This includes {@code Instant}, {@code LocalDate}, {@code LocalTime}, {@code OffsetDateTime}, * {@code ZonedDateTime} and {@code Duration}. * <p> * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a> * class; programmers should treat instances that are * {@linkplain #equals(Object) equal} as interchangeable and should not * use instances for synchronization, or unpredictable behavior may * occur. For example, in a future release, synchronization may fail. * The {@code equals} method should be used for comparisons. * * @implSpec * This class is immutable and thread-safe. * * @since 1.8 */ @jdk.internal.ValueBased public final class Instant implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable { /** * Constant for the 1970-01-01T00:00:00Z epoch instant. */ public static final Instant EPOCH = new Instant(0, 0); /** * The minimum supported epoch second. */ private static final long MIN_SECOND = -31557014167219200L; /** * The maximum supported epoch second. */ private static final long MAX_SECOND = 31556889864403199L; /** * The minimum supported {@code Instant}, '-1000000000-01-01T00:00Z'. * This could be used by an application as a "far past" instant. * <p> * This is one year earlier than the minimum {@code LocalDateTime}. * This provides sufficient values to handle the range of {@code ZoneOffset} * which affect the instant in addition to the local date-time. * The value is also chosen such that the value of the year fits in * an {@code int}. */ public static final Instant MIN = Instant.ofEpochSecond(MIN_SECOND, 0); /** * The maximum supported {@code Instant}, '1000000000-12-31T23:59:59.999999999Z'. * This could be used by an application as a "far future" instant. * <p> * This is one year later than the maximum {@code LocalDateTime}. * This provides sufficient values to handle the range of {@code ZoneOffset} * which affect the instant in addition to the local date-time. * The value is also chosen such that the value of the year fits in * an {@code int}. */ public static final Instant MAX = Instant.ofEpochSecond(MAX_SECOND, 999_999_999); /** * Serialization version. */ @java.io.Serial private static final long serialVersionUID = -665713676816604388L; /** * The number of seconds from the epoch of 1970-01-01T00:00:00Z. */ private final long seconds; /** * The number of nanoseconds, later along the time-line, from the seconds field. * This is always positive, and never exceeds 999,999,999. */ private final int nanos; //----------------------------------------------------------------------- /** * Obtains the current instant from the system clock. * <p> * This will query the {@link Clock#systemUTC() system UTC clock} to * obtain the current instant. * <p> * Using this method will prevent the ability to use an alternate time-source for * testing because the clock is effectively hard-coded. * * @return the current instant using the system clock, not null */ public static Instant now() { return Clock.currentInstant(); } /** * Obtains the current instant from the specified clock. * <p> * This will query the specified clock to obtain the current time. * <p> * Using this method allows the use of an alternate clock for testing. * The alternate clock may be introduced using {@link Clock dependency injection}. * * @param clock the clock to use, not null * @return the current instant, not null */ public static Instant now(Clock clock) { Objects.requireNonNull(clock, "clock"); return clock.instant(); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Instant} using seconds from the * epoch of 1970-01-01T00:00:00Z. * <p> * The nanosecond field is set to zero. * * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z * @return an instant, not null * @throws DateTimeException if the instant exceeds the maximum or minimum instant */ public static Instant ofEpochSecond(long epochSecond) { return create(epochSecond, 0); } /** * Obtains an instance of {@code Instant} using seconds from the * epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second. * <p> * This method allows an arbitrary number of nanoseconds to be passed in. * The factory will alter the values of the second and nanosecond in order * to ensure that the stored nanosecond is in the range 0 to 999,999,999. * For example, the following will result in exactly the same instant: * <pre> * Instant.ofEpochSecond(3, 1); * Instant.ofEpochSecond(4, -999_999_999); * Instant.ofEpochSecond(2, 1000_000_001); * </pre> * * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z * @param nanoAdjustment the nanosecond adjustment to the number of seconds, positive or negative * @return an instant, not null * @throws DateTimeException if the instant exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) { long secs = Math.addExact(epochSecond, Math.floorDiv(nanoAdjustment, NANOS_PER_SECOND)); int nos = (int)Math.floorMod(nanoAdjustment, NANOS_PER_SECOND); return create(secs, nos); } /** * Obtains an instance of {@code Instant} using milliseconds from the * epoch of 1970-01-01T00:00:00Z. * <p> * The seconds and nanoseconds are extracted from the specified milliseconds. * * @param epochMilli the number of milliseconds from 1970-01-01T00:00:00Z * @return an instant, not null * @throws DateTimeException if the instant exceeds the maximum or minimum instant */ public static Instant ofEpochMilli(long epochMilli) { long secs = Math.floorDiv(epochMilli, 1000); int mos = Math.floorMod(epochMilli, 1000); return create(secs, mos * 1000_000); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Instant} from a temporal object. * <p> * This obtains an instant based on the specified temporal. * A {@code TemporalAccessor} represents an arbitrary set of date and time information, * which this factory converts to an instance of {@code Instant}. * <p> * The conversion extracts the {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS} * and {@link ChronoField#NANO_OF_SECOND NANO_OF_SECOND} fields. * <p> * This method matches the signature of the functional interface {@link TemporalQuery} * allowing it to be used as a query via method reference, {@code Instant::from}. * * @param temporal the temporal object to convert, not null * @return the instant, not null * @throws DateTimeException if unable to convert to an {@code Instant} */ public static Instant from(TemporalAccessor temporal) { if (temporal instanceof Instant) { return (Instant) temporal; } Objects.requireNonNull(temporal, "temporal"); try { long instantSecs = temporal.getLong(INSTANT_SECONDS); int nanoOfSecond = temporal.get(NANO_OF_SECOND); return Instant.ofEpochSecond(instantSecs, nanoOfSecond); } catch (DateTimeException ex) { throw new DateTimeException("Unable to obtain Instant from TemporalAccessor: " + temporal + " of type " + temporal.getClass().getName(), ex); } } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Instant} from a text string such as * {@code 2007-12-03T10:15:30.00Z}. * <p> * The string must represent a valid instant in UTC and is parsed using * {@link DateTimeFormatter#ISO_INSTANT}. * * @param text the text to parse, not null * @return the parsed instant, not null * @throws DateTimeParseException if the text cannot be parsed */ public static Instant parse(final CharSequence text) { return DateTimeFormatter.ISO_INSTANT.parse(text, Instant::from); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code Instant} using seconds and nanoseconds. * * @param seconds the length of the duration in seconds * @param nanoOfSecond the nano-of-second, from 0 to 999,999,999 * @throws DateTimeException if the instant exceeds the maximum or minimum instant */ private static Instant create(long seconds, int nanoOfSecond) { if ((seconds | nanoOfSecond) == 0) { return EPOCH; } if (seconds < MIN_SECOND || seconds > MAX_SECOND) { throw new DateTimeException("Instant exceeds minimum or maximum instant"); } return new Instant(seconds, nanoOfSecond); } /** * Constructs an instance of {@code Instant} using seconds from the epoch of * 1970-01-01T00:00:00Z and nanosecond fraction of second. * * @param epochSecond the number of seconds from 1970-01-01T00:00:00Z * @param nanos the nanoseconds within the second, must be positive */ private Instant(long epochSecond, int nanos) { super(); this.seconds = epochSecond; this.nanos = nanos; } //----------------------------------------------------------------------- /** * Checks if the specified field is supported. * <p> * This checks if this instant can be queried for the specified field. * If false, then calling the {@link #range(TemporalField) range}, * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} * methods will throw an exception. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The supported fields are: * <ul> * <li>{@code NANO_OF_SECOND} * <li>{@code MICRO_OF_SECOND} * <li>{@code MILLI_OF_SECOND} * <li>{@code INSTANT_SECONDS} * </ul> * All other {@code ChronoField} instances will return false. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the field is supported is determined by the field. * * @param field the field to check, null returns false * @return true if the field is supported on this instant, false if not */ @Override public boolean isSupported(TemporalField field) { if (field instanceof ChronoField) { return field == INSTANT_SECONDS || field == NANO_OF_SECOND || field == MICRO_OF_SECOND || field == MILLI_OF_SECOND; } return field != null && field.isSupportedBy(this); } /** * Checks if the specified unit is supported. * <p> * This checks if the specified unit can be added to, or subtracted from, this date-time. * If false, then calling the {@link #plus(long, TemporalUnit)} and * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. * <p> * If the unit is a {@link ChronoUnit} then the query is implemented here. * The supported units are: * <ul> * <li>{@code NANOS} * <li>{@code MICROS} * <li>{@code MILLIS} * <li>{@code SECONDS} * <li>{@code MINUTES} * <li>{@code HOURS} * <li>{@code HALF_DAYS} * <li>{@code DAYS} * </ul> * All other {@code ChronoUnit} instances will return false. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} * passing {@code this} as the argument. * Whether the unit is supported is determined by the unit. * * @param unit the unit to check, null returns false * @return true if the unit can be added/subtracted, false if not */ @Override public boolean isSupported(TemporalUnit unit) { if (unit instanceof ChronoUnit) { return unit.isTimeBased() || unit == DAYS; } return unit != null && unit.isSupportedBy(this); } //----------------------------------------------------------------------- /** * Gets the range of valid values for the specified field. * <p> * The range object expresses the minimum and maximum valid values for a field. * This instant is used to enhance the accuracy of the returned range. * If it is not possible to return the range, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return * appropriate range instances. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the range can be obtained is determined by the field. * * @param field the field to query the range for, not null * @return the range of valid values for the field, not null * @throws DateTimeException if the range for the field cannot be obtained * @throws UnsupportedTemporalTypeException if the field is not supported */ @Override // override for Javadoc public ValueRange range(TemporalField field) { return Temporal.super.range(field); } /** * Gets the value of the specified field from this instant as an {@code int}. * <p> * This queries this instant for the value of the specified field. * The returned value will always be within the valid range of values for the field. * If it is not possible to return the value, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return valid * values based on this date-time, except {@code INSTANT_SECONDS} which is too * large to fit in an {@code int} and throws a {@code DateTimeException}. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} * passing {@code this} as the argument. Whether the value can be obtained, * and what the value represents, is determined by the field. * * @param field the field to get, not null * @return the value for the field * @throws DateTimeException if a value for the field cannot be obtained or * the value is outside the range of valid values for the field * @throws UnsupportedTemporalTypeException if the field is not supported or * the range of values exceeds an {@code int} * @throws ArithmeticException if numeric overflow occurs */ @Override // override for Javadoc and performance public int get(TemporalField field) { if (field instanceof ChronoField chronoField) { return switch (chronoField) { case NANO_OF_SECOND -> nanos; case MICRO_OF_SECOND -> nanos / 1000; case MILLI_OF_SECOND -> nanos / 1000_000; default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field); }; } return range(field).checkValidIntValue(field.getFrom(this), field); } /** * Gets the value of the specified field from this instant as a {@code long}. * <p> * This queries this instant for the value of the specified field. * If it is not possible to return the value, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return valid * values based on this date-time. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} * passing {@code this} as the argument. Whether the value can be obtained, * and what the value represents, is determined by the field. * * @param field the field to get, not null * @return the value for the field * @throws DateTimeException if a value for the field cannot be obtained * @throws UnsupportedTemporalTypeException if the field is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public long getLong(TemporalField field) { if (field instanceof ChronoField chronoField) { return switch (chronoField) { case NANO_OF_SECOND -> nanos; case MICRO_OF_SECOND -> nanos / 1000; case MILLI_OF_SECOND -> nanos / 1000_000; case INSTANT_SECONDS -> seconds; default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field); }; } return field.getFrom(this); } //----------------------------------------------------------------------- /** * Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z. * <p> * The epoch second count is a simple incrementing count of seconds where * second 0 is 1970-01-01T00:00:00Z. * The nanosecond part is returned by {@link #getNano}. * * @return the seconds from the epoch of 1970-01-01T00:00:00Z */ public long getEpochSecond() { return seconds; } /** * Gets the number of nanoseconds, later along the time-line, from the start * of the second. * <p> * The nanosecond-of-second value measures the total number of nanoseconds from * the second returned by {@link #getEpochSecond}. * * @return the nanoseconds within the second, always positive, never exceeds 999,999,999 */ public int getNano() { return nanos; } //------------------------------------------------------------------------- /** * Returns an adjusted copy of this instant. * <p> * This returns an {@code Instant}, based on this one, with the instant adjusted. * The adjustment takes place using the specified adjuster strategy object. * Read the documentation of the adjuster to understand what adjustment will be made. * <p> * The result of this method is obtained by invoking the * {@link TemporalAdjuster#adjustInto(Temporal)} method on the * specified adjuster passing {@code this} as the argument. * <p> * This instance is immutable and unaffected by this method call. * * @param adjuster the adjuster to use, not null * @return an {@code Instant} based on {@code this} with the adjustment made, not null * @throws DateTimeException if the adjustment cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public Instant with(TemporalAdjuster adjuster) { return (Instant) adjuster.adjustInto(this); } /** * Returns a copy of this instant with the specified field set to a new value. * <p> * This returns an {@code Instant}, based on this one, with the value * for the specified field changed. * If it is not possible to set the value, because the field is not supported or for * some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the adjustment is implemented here. * The supported fields behave as follows: * <ul> * <li>{@code NANO_OF_SECOND} - * Returns an {@code Instant} with the specified nano-of-second. * The epoch-second will be unchanged. * <li>{@code MICRO_OF_SECOND} - * Returns an {@code Instant} with the nano-of-second replaced by the specified * micro-of-second multiplied by 1,000. The epoch-second will be unchanged. * <li>{@code MILLI_OF_SECOND} - * Returns an {@code Instant} with the nano-of-second replaced by the specified * milli-of-second multiplied by 1,000,000. The epoch-second will be unchanged. * <li>{@code INSTANT_SECONDS} - * Returns an {@code Instant} with the specified epoch-second. * The nano-of-second will be unchanged. * </ul> * <p> * In all cases, if the new value is outside the valid range of values for the field * then a {@code DateTimeException} will be thrown. * <p> * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} * passing {@code this} as the argument. In this case, the field determines * whether and how to adjust the instant. * <p> * This instance is immutable and unaffected by this method call. * * @param field the field to set in the result, not null * @param newValue the new value of the field in the result * @return an {@code Instant} based on {@code this} with the specified field set, not null * @throws DateTimeException if the field cannot be set * @throws UnsupportedTemporalTypeException if the field is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public Instant with(TemporalField field, long newValue) { if (field instanceof ChronoField chronoField) { chronoField.checkValidValue(newValue); return switch (chronoField) { case MILLI_OF_SECOND -> { int nval = (int) newValue * 1000_000; yield nval != nanos ? create(seconds, nval) : this; } case MICRO_OF_SECOND -> { int nval = (int) newValue * 1000; yield nval != nanos ? create(seconds, nval) : this; } case NANO_OF_SECOND -> newValue != nanos ? create(seconds, (int) newValue) : this; case INSTANT_SECONDS -> newValue != seconds ? create(newValue, nanos) : this; default -> throw new UnsupportedTemporalTypeException("Unsupported field: " + field); }; } return field.adjustInto(this, newValue); } //----------------------------------------------------------------------- /** * Returns a copy of this {@code Instant} truncated to the specified unit. * <p> * Truncating the instant returns a copy of the original with fields * smaller than the specified unit set to zero. * The fields are calculated on the basis of using a UTC offset as seen * in {@code toString}. * For example, truncating with the {@link ChronoUnit#MINUTES MINUTES} unit will * round down to the nearest minute, setting the seconds and nanoseconds to zero. * <p> * The unit must have a {@linkplain TemporalUnit#getDuration() duration} * that divides into the length of a standard day without remainder. * This includes all supplied time units on {@link ChronoUnit} and * {@link ChronoUnit#DAYS DAYS}. Other units throw an exception. * <p> * This instance is immutable and unaffected by this method call. * * @param unit the unit to truncate to, not null * @return an {@code Instant} based on this instant with the time truncated, not null * @throws DateTimeException if the unit is invalid for truncation * @throws UnsupportedTemporalTypeException if the unit is not supported */ public Instant truncatedTo(TemporalUnit unit) { if (unit == ChronoUnit.NANOS) { return this; } Duration unitDur = unit.getDuration(); if (unitDur.getSeconds() > LocalTime.SECONDS_PER_DAY) { throw new UnsupportedTemporalTypeException("Unit is too large to be used for truncation"); } long dur = unitDur.toNanos(); if ((LocalTime.NANOS_PER_DAY % dur) != 0) { throw new UnsupportedTemporalTypeException("Unit must divide into a standard day without remainder"); } long nod = (seconds % LocalTime.SECONDS_PER_DAY) * LocalTime.NANOS_PER_SECOND + nanos; long result = Math.floorDiv(nod, dur) * dur; return plusNanos(result - nod); } //----------------------------------------------------------------------- /** * Returns a copy of this instant with the specified amount added. * <p> * This returns an {@code Instant}, based on this one, with the specified amount added. * The amount is typically {@link Duration} but may be any other type implementing * the {@link TemporalAmount} interface. * <p> * The calculation is delegated to the amount object by calling * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free * to implement the addition in any way it wishes, however it typically * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation * of the amount implementation to determine if it can be successfully added. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToAdd the amount to add, not null * @return an {@code Instant} based on this instant with the addition made, not null * @throws DateTimeException if the addition cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public Instant plus(TemporalAmount amountToAdd) { return (Instant) amountToAdd.addTo(this); } /** * Returns a copy of this instant with the specified amount added. * <p> * This returns an {@code Instant}, based on this one, with the amount * in terms of the unit added. If it is not possible to add the amount, because the * unit is not supported or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoUnit} then the addition is implemented here. * The supported fields behave as follows: * <ul> * <li>{@code NANOS} - * Returns an {@code Instant} with the specified number of nanoseconds added. * This is equivalent to {@link #plusNanos(long)}. * <li>{@code MICROS} - * Returns an {@code Instant} with the specified number of microseconds added. * This is equivalent to {@link #plusNanos(long)} with the amount * multiplied by 1,000. * <li>{@code MILLIS} - * Returns an {@code Instant} with the specified number of milliseconds added. * This is equivalent to {@link #plusNanos(long)} with the amount * multiplied by 1,000,000. * <li>{@code SECONDS} - * Returns an {@code Instant} with the specified number of seconds added. * This is equivalent to {@link #plusSeconds(long)}. * <li>{@code MINUTES} - * Returns an {@code Instant} with the specified number of minutes added. * This is equivalent to {@link #plusSeconds(long)} with the amount * multiplied by 60. * <li>{@code HOURS} - * Returns an {@code Instant} with the specified number of hours added. * This is equivalent to {@link #plusSeconds(long)} with the amount * multiplied by 3,600. * <li>{@code HALF_DAYS} - * Returns an {@code Instant} with the specified number of half-days added. * This is equivalent to {@link #plusSeconds(long)} with the amount * multiplied by 43,200 (12 hours). * <li>{@code DAYS} - * Returns an {@code Instant} with the specified number of days added. * This is equivalent to {@link #plusSeconds(long)} with the amount * multiplied by 86,400 (24 hours). * </ul> * <p> * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} * passing {@code this} as the argument. In this case, the unit determines * whether and how to perform the addition. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToAdd the amount of the unit to add to the result, may be negative * @param unit the unit of the amount to add, not null * @return an {@code Instant} based on this instant with the specified amount added, not null * @throws DateTimeException if the addition cannot be made * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public Instant plus(long amountToAdd, TemporalUnit unit) { if (unit instanceof ChronoUnit chronoUnit) { return switch (chronoUnit) { case NANOS -> plusNanos(amountToAdd); case MICROS -> plus(amountToAdd / 1000_000, (amountToAdd % 1000_000) * 1000); case MILLIS -> plusMillis(amountToAdd); case SECONDS -> plusSeconds(amountToAdd); case MINUTES -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_MINUTE)); case HOURS -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_HOUR)); case HALF_DAYS -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY / 2)); case DAYS -> plusSeconds(Math.multiplyExact(amountToAdd, SECONDS_PER_DAY)); default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); }; } return unit.addTo(this, amountToAdd); } //----------------------------------------------------------------------- /** * Returns a copy of this instant with the specified duration in seconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param secondsToAdd the seconds to add, positive or negative * @return an {@code Instant} based on this instant with the specified seconds added, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public Instant plusSeconds(long secondsToAdd) { return plus(secondsToAdd, 0); } /** * Returns a copy of this instant with the specified duration in milliseconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param millisToAdd the milliseconds to add, positive or negative * @return an {@code Instant} based on this instant with the specified milliseconds added, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public Instant plusMillis(long millisToAdd) { return plus(millisToAdd / 1000, (millisToAdd % 1000) * 1000_000); } /** * Returns a copy of this instant with the specified duration in nanoseconds added. * <p> * This instance is immutable and unaffected by this method call. * * @param nanosToAdd the nanoseconds to add, positive or negative * @return an {@code Instant} based on this instant with the specified nanoseconds added, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public Instant plusNanos(long nanosToAdd) { return plus(0, nanosToAdd); } /** * Returns a copy of this instant with the specified duration added. * <p> * This instance is immutable and unaffected by this method call. * * @param secondsToAdd the seconds to add, positive or negative * @param nanosToAdd the nanos to add, positive or negative * @return an {@code Instant} based on this instant with the specified seconds added, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ private Instant plus(long secondsToAdd, long nanosToAdd) { if ((secondsToAdd | nanosToAdd) == 0) { return this; } long epochSec = Math.addExact(seconds, secondsToAdd); epochSec = Math.addExact(epochSec, nanosToAdd / NANOS_PER_SECOND); nanosToAdd = nanosToAdd % NANOS_PER_SECOND; long nanoAdjustment = nanos + nanosToAdd; // safe int+NANOS_PER_SECOND return ofEpochSecond(epochSec, nanoAdjustment); } //----------------------------------------------------------------------- /** * Returns a copy of this instant with the specified amount subtracted. * <p> * This returns an {@code Instant}, based on this one, with the specified amount subtracted. * The amount is typically {@link Duration} but may be any other type implementing * the {@link TemporalAmount} interface. * <p> * The calculation is delegated to the amount object by calling * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free * to implement the subtraction in any way it wishes, however it typically * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation * of the amount implementation to determine if it can be successfully subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToSubtract the amount to subtract, not null * @return an {@code Instant} based on this instant with the subtraction made, not null * @throws DateTimeException if the subtraction cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public Instant minus(TemporalAmount amountToSubtract) { return (Instant) amountToSubtract.subtractFrom(this); } /** * Returns a copy of this instant with the specified amount subtracted. * <p> * This returns an {@code Instant}, based on this one, with the amount * in terms of the unit subtracted. If it is not possible to subtract the amount, * because the unit is not supported or for some other reason, an exception is thrown. * <p> * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. * See that method for a full description of how addition, and thus subtraction, works. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToSubtract the amount of the unit to subtract from the result, may be negative * @param unit the unit of the amount to subtract, not null * @return an {@code Instant} based on this instant with the specified amount subtracted, not null * @throws DateTimeException if the subtraction cannot be made * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public Instant minus(long amountToSubtract, TemporalUnit unit) { return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); } //----------------------------------------------------------------------- /** * Returns a copy of this instant with the specified duration in seconds subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param secondsToSubtract the seconds to subtract, positive or negative * @return an {@code Instant} based on this instant with the specified seconds subtracted, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public Instant minusSeconds(long secondsToSubtract) { if (secondsToSubtract == Long.MIN_VALUE) { return plusSeconds(Long.MAX_VALUE).plusSeconds(1); } return plusSeconds(-secondsToSubtract); } /** * Returns a copy of this instant with the specified duration in milliseconds subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param millisToSubtract the milliseconds to subtract, positive or negative * @return an {@code Instant} based on this instant with the specified milliseconds subtracted, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public Instant minusMillis(long millisToSubtract) { if (millisToSubtract == Long.MIN_VALUE) { return plusMillis(Long.MAX_VALUE).plusMillis(1); } return plusMillis(-millisToSubtract); } /** * Returns a copy of this instant with the specified duration in nanoseconds subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param nanosToSubtract the nanoseconds to subtract, positive or negative * @return an {@code Instant} based on this instant with the specified nanoseconds subtracted, not null * @throws DateTimeException if the result exceeds the maximum or minimum instant * @throws ArithmeticException if numeric overflow occurs */ public Instant minusNanos(long nanosToSubtract) { if (nanosToSubtract == Long.MIN_VALUE) { return plusNanos(Long.MAX_VALUE).plusNanos(1); } return plusNanos(-nanosToSubtract); } //------------------------------------------------------------------------- /** * Queries this instant using the specified query. * <p> * This queries this instant using the specified query strategy object. * The {@code TemporalQuery} object defines the logic to be used to * obtain the result. Read the documentation of the query to understand * what the result of this method will be. * <p> * The result of this method is obtained by invoking the * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the * specified query passing {@code this} as the argument. * * @param <R> the type of the result * @param query the query to invoke, not null * @return the query result, null may be returned (defined by the query) * @throws DateTimeException if unable to query (defined by the query) * @throws ArithmeticException if numeric overflow occurs (defined by the query) */ @SuppressWarnings("unchecked") @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.precision()) { return (R) NANOS; } // inline TemporalAccessor.super.query(query) as an optimization if (query == TemporalQueries.chronology() || query == TemporalQueries.zoneId() || query == TemporalQueries.zone() || query == TemporalQueries.offset() || query == TemporalQueries.localDate() || query == TemporalQueries.localTime()) { return null; } return query.queryFrom(this); } /** * Adjusts the specified temporal object to have this instant. * <p> * This returns a temporal object of the same observable type as the input * with the instant changed to be the same as this. * <p> * The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)} * twice, passing {@link ChronoField#INSTANT_SECONDS} and * {@link ChronoField#NANO_OF_SECOND} as the fields. * <p> * In most cases, it is clearer to reverse the calling pattern by using * {@link Temporal#with(TemporalAdjuster)}: * <pre> * // these two lines are equivalent, but the second approach is recommended * temporal = thisInstant.adjustInto(temporal); * temporal = temporal.with(thisInstant); * </pre> * <p> * This instance is immutable and unaffected by this method call. * * @param temporal the target object to be adjusted, not null * @return the adjusted object, not null * @throws DateTimeException if unable to make the adjustment * @throws ArithmeticException if numeric overflow occurs */ @Override public Temporal adjustInto(Temporal temporal) { return temporal.with(INSTANT_SECONDS, seconds).with(NANO_OF_SECOND, nanos); } /** * Calculates the amount of time until another instant in terms of the specified unit. * <p> * This calculates the amount of time between two {@code Instant} * objects in terms of a single {@code TemporalUnit}. * The start and end points are {@code this} and the specified instant. * The result will be negative if the end is before the start. * The calculation returns a whole number, representing the number of * complete units between the two instants. * The {@code Temporal} passed to this method is converted to a * {@code Instant} using {@link #from(TemporalAccessor)}. * For example, the amount in seconds between two dates can be calculated * using {@code startInstant.until(endInstant, SECONDS)}. * <p> * There are two equivalent ways of using this method. * The first is to invoke this method. * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: * <pre> * // these two lines are equivalent * amount = start.until(end, SECONDS); * amount = SECONDS.between(start, end); * </pre> * The choice should be made based on which makes the code more readable. * <p> * The calculation is implemented in this method for {@link ChronoUnit}. * The units {@code NANOS}, {@code MICROS}, {@code MILLIS}, {@code SECONDS}, * {@code MINUTES}, {@code HOURS}, {@code HALF_DAYS} and {@code DAYS} * are supported. Other {@code ChronoUnit} values will throw an exception. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} * passing {@code this} as the first argument and the converted input temporal * as the second argument. * <p> * This instance is immutable and unaffected by this method call. * * @param endExclusive the end date, exclusive, which is converted to an {@code Instant}, not null * @param unit the unit to measure the amount in, not null * @return the amount of time between this instant and the end instant * @throws DateTimeException if the amount cannot be calculated, or the end * temporal cannot be converted to an {@code Instant} * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public long until(Temporal endExclusive, TemporalUnit unit) { Instant end = Instant.from(endExclusive); if (unit instanceof ChronoUnit chronoUnit) { return switch (chronoUnit) { case NANOS -> nanosUntil(end); case MICROS -> microsUntil(end); case MILLIS -> millisUntil(end); case SECONDS -> secondsUntil(end); case MINUTES -> secondsUntil(end) / SECONDS_PER_MINUTE; case HOURS -> secondsUntil(end) / SECONDS_PER_HOUR; case HALF_DAYS -> secondsUntil(end) / (12 * SECONDS_PER_HOUR); case DAYS -> secondsUntil(end) / (SECONDS_PER_DAY); default -> throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); }; } return unit.between(this, end); } private long nanosUntil(Instant end) { long secsDiff = Math.subtractExact(end.seconds, seconds); long totalNanos = Math.multiplyExact(secsDiff, NANOS_PER_SECOND); return Math.addExact(totalNanos, end.nanos - nanos); } private long microsUntil(Instant end) { long secsDiff = Math.subtractExact(end.seconds, seconds); long totalMicros = Math.multiplyExact(secsDiff, MICROS_PER_SECOND); return Math.addExact(totalMicros, (end.nanos - nanos) / 1000); } private long millisUntil(Instant end) { long secsDiff = Math.subtractExact(end.seconds, seconds); long totalMillis = Math.multiplyExact(secsDiff, MILLIS_PER_SECOND); return Math.addExact(totalMillis, (end.nanos - nanos) / 1000_000); } private long secondsUntil(Instant end) { long secsDiff = Math.subtractExact(end.seconds, seconds); long nanosDiff = end.nanos - nanos; if (secsDiff > 0 && nanosDiff < 0) { secsDiff--; } else if (secsDiff < 0 && nanosDiff > 0) { secsDiff++; } return secsDiff; } //----------------------------------------------------------------------- /** * Combines this instant with an offset to create an {@code OffsetDateTime}. * <p> * This returns an {@code OffsetDateTime} formed from this instant at the * specified offset from UTC/Greenwich. An exception will be thrown if the * instant is too large to fit into an offset date-time. * <p> * This method is equivalent to * {@link OffsetDateTime#ofInstant(Instant, ZoneId) OffsetDateTime.ofInstant(this, offset)}. * * @param offset the offset to combine with, not null * @return the offset date-time formed from this instant and the specified offset, not null * @throws DateTimeException if the result exceeds the supported range */ public OffsetDateTime atOffset(ZoneOffset offset) { return OffsetDateTime.ofInstant(this, offset); } /** * Combines this instant with a time-zone to create a {@code ZonedDateTime}. * <p> * This returns an {@code ZonedDateTime} formed from this instant at the * specified time-zone. An exception will be thrown if the instant is too * large to fit into a zoned date-time. * <p> * This method is equivalent to * {@link ZonedDateTime#ofInstant(Instant, ZoneId) ZonedDateTime.ofInstant(this, zone)}. * * @param zone the zone to combine with, not null * @return the zoned date-time formed from this instant and the specified zone, not null * @throws DateTimeException if the result exceeds the supported range */ public ZonedDateTime atZone(ZoneId zone) { return ZonedDateTime.ofInstant(this, zone); } //----------------------------------------------------------------------- /** * Converts this instant to the number of milliseconds from the epoch * of 1970-01-01T00:00:00Z. * <p> * If this instant represents a point on the time-line too far in the future * or past to fit in a {@code long} milliseconds, then an exception is thrown. * <p> * If this instant has greater than millisecond precision, then the conversion * will drop any excess precision information as though the amount in nanoseconds * was subject to integer division by one million. * * @return the number of milliseconds since the epoch of 1970-01-01T00:00:00Z * @throws ArithmeticException if numeric overflow occurs */ public long toEpochMilli() { if (seconds < 0 && nanos > 0) { long millis = Math.multiplyExact(seconds+1, 1000); long adjustment = nanos / 1000_000 - 1000; return Math.addExact(millis, adjustment); } else { long millis = Math.multiplyExact(seconds, 1000); return Math.addExact(millis, nanos / 1000_000); } } //----------------------------------------------------------------------- /** * Compares this instant to the specified instant. * <p> * The comparison is based on the time-line position of the instants. * It is "consistent with equals", as defined by {@link Comparable}. * * @param otherInstant the other instant to compare to, not null * @return the comparator value, negative if less, positive if greater * @throws NullPointerException if otherInstant is null */ @Override public int compareTo(Instant otherInstant) { int cmp = Long.compare(seconds, otherInstant.seconds); if (cmp != 0) { return cmp; } return nanos - otherInstant.nanos; } /** * Checks if this instant is after the specified instant. * <p> * The comparison is based on the time-line position of the instants. * * @param otherInstant the other instant to compare to, not null * @return true if this instant is after the specified instant * @throws NullPointerException if otherInstant is null */ public boolean isAfter(Instant otherInstant) { return compareTo(otherInstant) > 0; } /** * Checks if this instant is before the specified instant. * <p> * The comparison is based on the time-line position of the instants. * * @param otherInstant the other instant to compare to, not null * @return true if this instant is before the specified instant * @throws NullPointerException if otherInstant is null */ public boolean isBefore(Instant otherInstant) { return compareTo(otherInstant) < 0; } //----------------------------------------------------------------------- /** * Checks if this instant is equal to the specified instant. * <p> * The comparison is based on the time-line position of the instants. * * @param other the other instant, null returns false * @return true if the other instant is equal to this one */ @Override public boolean equals(Object other) { if (this == other) { return true; } return (other instanceof Instant otherInstant) && this.seconds == otherInstant.seconds && this.nanos == otherInstant.nanos; } /** * Returns a hash code for this instant. * * @return a suitable hash code */ @Override public int hashCode() { return ((int) (seconds ^ (seconds >>> 32))) + 51 * nanos; } //----------------------------------------------------------------------- /** * A string representation of this instant using ISO-8601 representation. * <p> * The format used is the same as {@link DateTimeFormatter#ISO_INSTANT}. * * @return an ISO-8601 representation of this instant, not null */ @Override public String toString() { return DateTimeFormatter.ISO_INSTANT.format(this); } // ----------------------------------------------------------------------- /** * Writes the object using a * <a href="{@docRoot}/serialized-form.html#java.time.Ser">dedicated serialized form</a>. * @serialData * <pre> * out.writeByte(2); // identifies an Instant * out.writeLong(seconds); * out.writeInt(nanos); * </pre> * * @return the instance of {@code Ser}, not null */ @java.io.Serial private Object writeReplace() { return new Ser(Ser.INSTANT_TYPE, this); } /** * Defend against malicious streams. * * @param s the stream to read * @throws InvalidObjectException always */ @java.io.Serial private void readObject(ObjectInputStream s) throws InvalidObjectException { throw new InvalidObjectException("Deserialization via serialization delegate"); } void writeExternal(DataOutput out) throws IOException { out.writeLong(seconds); out.writeInt(nanos); } static Instant readExternal(DataInput in) throws IOException { long seconds = in.readLong(); int nanos = in.readInt(); return Instant.ofEpochSecond(seconds, nanos); } }
zxiaofan/JDK
JDK-18-ea31/src/java.base/java/time/Instant.java
248,611
package a03; import java.io.File; import java.io.FileNotFoundException; import java.text.DecimalFormat; import java.util.*; /** * Program will count the words and occurrences of words in the complete Lord of the Rings Trilogy by J.R.R Tolkien, * calculate how many words are not found in the provided dictionary, * and calculate the most closely associated with the Ring using proximity searching. * This is the class header. * * @date Feb 20, 2022 * @author DUC LONG NGUYEN (Paul) * * DISCUSSIONS: * 1. The percentage of total empty buckets ~ 2% * 2. The best performance -> Use the a03.SimpleHashSet dictionary and the contains method provided (~5ms) * Use the binarySearch method of the Collections class (Collections.binarySearch) (~20ms) * The lowest performance-> Use the contains method of ArrayList to find matches (~2000ms) * * The calculation of the perfomances are based on the time required to figure out the number of * misspelled words in the file. Therefore, before calculate the number of misspelled word, * we need to call System.nanoTime() and call this method after calculate. * From that, we will have the performance of each method measured in milisecond. * The best performance (Use the a03.SimpleHashSet dictionary and the contains method provided) is * the method with the completely time is smallest */ public class Assignment3_Start { private static final int MOST_FREQUENT_WORDS = 10; // The list of the 10 most frequent words and counts private static final int OCCUR_EXACTLY = 64; // The list of words that occur exactly 64 times in the file. private static final String WORD_TO_CALC_PRO_DISTANCE = "ring"; // Measure the proximity distance of a character to the word “ring” private static final int PRO_DISTANCE_CUT_OFF =42; // a proximity distance cut-off private static final String[] ACTORS = new String[] // Evaluate the character list to find The Lord of the "Ring" {"frodo", "sam", "bilbo", "gandalf", "boromir", "aragorn", "legolas", "gollum","pippin", "merry", "gimli", "sauron", "saruman", "faramir", "denethor", "treebeard", "elrond", "galadriel"}; private static String DISCUSSIONS = ""; /** PART A * The method to read and store all unique words into an ArrayList from a US.txt file. * @param fileDic The name of file * @return an ArrayList stored all the unique words from UX.txt file */ private static ArrayList<BookWord> arrDic(String fileDic){ ArrayList<BookWord> dic = new ArrayList<>(); try { Scanner finDic = new Scanner(new File(fileDic)); while (finDic.hasNext()) dic.add(new BookWord(finDic.next())); finDic.close(); } catch (FileNotFoundException ex) { System.out.println("Exception opening file : " + ex.getMessage()); } Collections.sort(dic, (w1, w2) -> w1.getText().compareToIgnoreCase(w2.getText())); return dic; } /** PART A * The method to read and store all unique words into an a03.SimpleHashSet from a US.txt file. * @param fileDic The name of file * @return an a03.SimpleHashSet stored all the unique words from UX.txt file */ private static SimpleHashSet<BookWord> simpleHashSetDic(String fileDic){ SimpleHashSet<BookWord> dic = new SimpleHashSet<>(); try { Scanner finDic = new Scanner(new File(fileDic)); while (finDic.hasNext()) dic.insert(new BookWord(finDic.next())); finDic.close(); } catch (FileNotFoundException ex) { System.out.println("Exception opening file : " + ex.getMessage()); } DISCUSSIONS+="\t1. The percentage of total empty buckets: "+ (new DecimalFormat("#.##") .format((double) dic.getNumberofEmptyBuckets()*100/dic.size()))+"%\n"; return dic; } /** PART A * The method to read and store all unique words into an ArrayList from a TheLordOfTheRIngs.txt file. * @param fileName The name of file * @return a sorted ArrayList stored all the unique words from TheLordOfTheRIngs.txt file */ private static ArrayList<BookWord> words(String fileName){ SimpleHashSet<BookWord> words =new SimpleHashSet<>(); try { Scanner fin = new Scanner(new File(fileName)); fin.useDelimiter("\\s|\"|\\(|\\)|\\.|\\,|\\?|\\!|\\_|\\-|\\:|\\;|\\n"); // Filter - DO NOT CHANGE while (fin.hasNext()) { String fileWord = fin.next().toLowerCase(); if (fileWord.length() > 0) { BookWord word = new BookWord(fileWord); words.insert(word); if (words.contains(word)) { ArrayList<BookWord> _words = words.buckets[words.getHash(word, words.getNumberofBuckets())]; _words.get(_words.indexOf(word)).incrementCount(); //count the total of this word in the file } } } fin.close(); }catch (Exception e){ System.out.println("Exception caught: " + e.getMessage()); } ArrayList<BookWord> arrayListWords = new ArrayList<>(); for (ArrayList<BookWord> _words : words.buckets) arrayListWords.addAll(_words); Collections.sort(arrayListWords, (w1, w2) -> (w2.getCount() - w1.getCount())!=0 ? (w2.getCount() - w1.getCount()) : w1.getText().compareToIgnoreCase(w2.getText())); return arrayListWords; } /** PART A * The method to calculate the most frequent words, and stores they into an array from an ArrayList of words. * @param words an ArrayList of words (from TheLordOfTheRIngs.txt file) * @return a sorted array stores the most frequent words */ private static BookWord[] mostFrequentWords(ArrayList<BookWord> words){ BookWord[] frequentWords = new BookWord[MOST_FREQUENT_WORDS]; for (int i=0; i<MOST_FREQUENT_WORDS; i++) frequentWords[i]=words.get(i); return frequentWords; } /** PART A * The method to calculate and list the words that occur exactly [OCCUR_EXACTLY] times in the file, and store they into an ArrayList * @param words an ArrayList of words (from TheLordOfTheRIngs.txt file) * @return a sorted ArrayList stores the words that occur exactly [OCCUR_EXACTLY] times in the file (TheLordOfTheRIngs.txt file) */ private static ArrayList<BookWord> occurExactly(ArrayList<BookWord> words){ ArrayList<BookWord> occurExactly = new ArrayList<>(); for (BookWord word : words) if(word.getCount()==OCCUR_EXACTLY) occurExactly.add(word); return occurExactly; } /** PART A * The method to calculate the number of misspelled words in the file (the words that are not contained in the dictionary) * through the METHOD 01: Use the contains method of ArrayList to find matches. * @param words an ArrayList of words (from TheLordOfTheRIngs.txt file) * @param dic an ArrayList of words in dictionary (from UX.txt file) * @return an integer number that is the number of misspelled words in the file */ private static int checkMisspelledM1(ArrayList<BookWord> words, ArrayList<BookWord> dic){ int count = 0; for (BookWord _word : words) { boolean isContain = false; if (dic.contains(_word)) isContain=true; count = isContain ? count : count+1; } return count; } /** PART A * The method to calculate the number of misspelled words in the file (the words that are not contained in the dictionary) * through the METHOD 02: Use the binarySearch method of the Collections class (Collections.binarySearch) * to search the ArrayList dictionary. Supply a Lambda expression for the binary search of the Dictionary. * @param words an ArrayList of words (from TheLordOfTheRIngs.txt file) * @param dic an ArrayList of words in dictionary (from UX.txt file) * @return an integer number that is the number of misspelled words in the file */ private static int checkMisspelledM2(ArrayList<BookWord> words, ArrayList<BookWord> dic){ int count = 0; for (BookWord word : words) if(Collections.binarySearch(dic, word, (o1, o2) -> o1.getText().compareToIgnoreCase(o2.getText()))<0) count++; return count; } /** PART A * The method to calculate the number of misspelled words in the file (the words that are not contained in the dictionary) * through the METHOD 03: Use the a03.SimpleHashSet dictionary and the contains method provided * @param words an ArrayList of words (from TheLordOfTheRIngs.txt file) * @param dic a a03.SimpleHashSet of words in dictionary (from UX.txt file) * @return an integer number that is the number of misspelled words in the file */ private static int checkMisspelledM3(ArrayList<BookWord> words, SimpleHashSet<BookWord> dic){ int count = 0; for (BookWord word : words) if(dic.contains(word)) count++; return words.size() - count; } /** PART A * The method to print the information of 3 methods above when calculation the number of misspelled words in the file * including the name of methods, the number of misspelled words and the performance for each method. * @param words an ArrayList of words (from TheLordOfTheRIngs.txt file) * @param dic an ArrayList of words in dictionary (from UX.txt file) * @param simpleHashSetDic a a03.SimpleHashSet of words in dictionary (from UX.txt file) * @return a string that includes all the information of 3 methods (including the number of misspelled word and the performance) */ private static String checkMisspelled3M(ArrayList<BookWord> words, ArrayList<BookWord> dic, SimpleHashSet<BookWord> simpleHashSetDic){ ArrayList<String[]> performances = new ArrayList<>(); String checkMisspelled = "5. Check misspelled words:\n\t____________Method________________Misspelled Words___Performance\n\t"; String performanceM1 = "Contains method of ArrayList"; long startTimeEfficiency = System.nanoTime(); //calculate timing checkMisspelled += performanceM1+"\t\t" +checkMisspelledM1(words,dic)+"\t\t\t "; int endTimeEfficiency = Math.abs((int)(System.nanoTime() - startTimeEfficiency)/1000000); performances.add(new String[]{performanceM1,endTimeEfficiency+""}); checkMisspelled+=performances.get(0)[1]+"ms\n\t"; String performanceM2 = "BinarySearch method"; startTimeEfficiency = System.nanoTime(); checkMisspelled += "\t"+performanceM2+"\t\t\t\t" +checkMisspelledM2(words,dic)+"\t\t\t "; endTimeEfficiency = Math.abs((int)(System.nanoTime() - startTimeEfficiency)/1000000); performances.add(new String[]{performanceM2, endTimeEfficiency+""}); checkMisspelled+=performances.get(1)[1]+"ms\n\t"; String performanceM3 = "Contains method and a03.SimpleHashSet"; startTimeEfficiency = System.nanoTime(); checkMisspelled += performanceM3+"\t" +checkMisspelledM3(words,simpleHashSetDic)+"\t\t\t "; endTimeEfficiency = Math.abs((int)(System.nanoTime() - startTimeEfficiency)/1000000); performances.add(new String[]{performanceM3,endTimeEfficiency+""}); checkMisspelled+=performances.get(2)[1]+"ms\n\t"; Collections.sort(performances, (p1,p2) -> Integer.parseInt(p1[1]) - Integer.parseInt(p2[1])); DISCUSSIONS+="\t2. The best performance -> "; for (String[] per : performances) DISCUSSIONS+=per[0]+"("+per[1]+"ms) -> "; DISCUSSIONS+=" The lowest performance.\n"; return checkMisspelled; } /** PART B * The method to read and store all words into an array from a TheLordOfTheRIngs.txt file. * @param filename The name of file * @param length the length of this array * @return an array stored all the word from TheLordOfTheRIngs.txt file */ private static String[] arrWords(String filename, int length){ String[] _arrWords = new String[length]; int count = 0; try { Scanner fin = new Scanner(new File(filename)); fin.useDelimiter("\\s|\"|\\(|\\)|\\.|\\,|\\?|\\!|\\_|\\-|\\:|\\;|\\n"); // Filter - DO NOT CHANGE while (fin.hasNext()) { String fileWord = fin.next().toLowerCase(); if (fileWord.length() > 0){ _arrWords[count] = fileWord; count++; } } fin.close(); } catch (FileNotFoundException e) { System.out.println("Exception caught: " + e.getMessage()); } return _arrWords; } /** PART B * The method to store a word and its indexes into a two-dimensional array ([word][index]) from an array of words * @param arrWords a string array stored all the word from TheLordOfTheRIngs.txt file * @param closenessString the word to store into this two-dimensional array * @return an array that stores this word and its indexes into a two-dimensional array ([word][index]) from an array of words */ private static String[][] arrWordAndIndex(String[] arrWords, String closenessString){ int count=0; for (String word : arrWords) if (word.equalsIgnoreCase(closenessString)) count++; String[][] _closeness = new String[count][2]; count=0; for (int i=0; i<arrWords.length; i++) if (arrWords[i].equalsIgnoreCase(closenessString)){ _closeness[count][0] = arrWords[i]; _closeness[count][1] = i+""; count++; } return _closeness; } /** PART B * The method to store words of [ACTORS] array and their indexes * into a three-dimensional array ([index of ACTORS array][word][index]) from an array of words * @param arrWords a string array stored all the word from TheLordOfTheRIngs.txt file * @return an array that stores these words and their indexes * into a three-dimensional array ([index of ACTORS array][word][index]) from an array of words */ private static String[][][] actors(String[] arrWords){ String[][][] actors = new String[ACTORS.length][][]; int count=0; for (String actor : ACTORS){ actors[count] = arrWordAndIndex(arrWords, actor); count++; } return actors; } /** PART B * This method will calculate and store the proximity distances of characters to the word [WORD_TO_CALC_PRO_DISTANCE] * within the text and count up the times it is within a proximity cut-off distance * @param rings an array of the word [WORD_TO_CALC_PRO_DISTANCE] including their positions * @param actors an array of characters to calculate the proximity distances including their positions * @return an array that stores proximity distances of characters to the word [WORD_TO_CALC_PRO_DISTANCE] * into a two-dimensional array ([index of ACTORS array][the info of the proximity distances for this ACTOR]) */ private static String[][] proximityDistances(String[][] rings, String[][][] actors){ int[] closeness = new int[actors.length]; int count=0; for (String[][] actor : actors){ if (actor.length>0) { int countProDistance = 0; for (String[] _actor : actor) for (String[] ring : rings) if (Math.abs(Integer.parseInt(_actor[1]) - Integer.parseInt(ring[1])) <= PRO_DISTANCE_CUT_OFF) countProDistance++; closeness[count] = countProDistance; } else closeness[count] = 0; count++; } String[][] proximityDistances = new String[ACTORS.length][4]; for (int i=0; i< ACTORS.length; i++) proximityDistances[i] = new String[]{ACTORS[i], actors[i].length+"", closeness[i]+"", (actors[i].length == 0 ? 0 : (double)closeness[i]/actors[i].length)+""}; Arrays.sort(proximityDistances, (pd1, pd2) -> (int) (Double.parseDouble(pd2[3])*10000 - Double.parseDouble(pd1[3])*10000)); return proximityDistances; } /** * The starting point of the application */ public static void main(String[] args) { // File is stored in a resources folder in the project final String filename = "src/a03/TheLOrdOfTheRings.txt"; int count = 0; try { Scanner fin = new Scanner(new File(filename)); fin.useDelimiter("\\s|\"|\\(|\\)|\\.|\\,|\\?|\\!|\\_|\\-|\\:|\\;|\\n"); // Filter - DO NOT CHANGE while (fin.hasNext()) { String fileWord = fin.next().toLowerCase(); if (fileWord.length() > 0) { // Just print to the screen for now - REMOVE once you have completed code // System.out.printf("%s\n", fileWord); count++; } } fin.close(); } catch (FileNotFoundException e) { System.out.println("Exception caught: " + e.getMessage()); } System.out.println("I/ PART A ____________\n1. There are a total of " + count + " words in the file "); // ADD other code after here ArrayList<BookWord> dic = arrDic("src/a03/US.txt"); // read us.txt SimpleHashSet<BookWord> simpleHashSetDic = simpleHashSetDic("src/US.txt"); // read us.txt ArrayList<BookWord> words = words(filename); // read TheLordOfTheRIngs.txt /** PART A*/ System.out.print("2. There are a total of "+words.size()+" different words in the file\n"); // The list of the most frequent words and counts String mostFrequentWords = "3. The list of the "+MOST_FREQUENT_WORDS+" most frequent words and counts : "; for (int i=0; i< mostFrequentWords(words).length; i++) mostFrequentWords += "\n\t 3."+(i+1)+": ["+mostFrequentWords(words)[i]+"]"; System.out.println(mostFrequentWords); // The list of words below each occur 64 times String occurList = "4. The words below each occur "+OCCUR_EXACTLY+" times in the file: "; for (int i=0; i< occurExactly(words).size(); i++) occurList += "\n\t 4."+(i+1)+": ["+occurExactly(words).get(i)+"]"; System.out.println(occurList); // Calculate the total of misspelled words and performance. System.out.println(checkMisspelled3M(words,dic, simpleHashSetDic) +"\nII/ PART B ____________\n\t____ORDER of WHO REALLY WANTS the RING_______________"); /** PART B*/ String[] arrWords = arrWords(filename,count); String[][] proximityDistances = proximityDistances(arrWordAndIndex(arrWords, WORD_TO_CALC_PRO_DISTANCE), actors(arrWords)); for (String[] pd : proximityDistances) System.out.println("\t["+pd[0]+","+pd[1]+"]\t"+(pd[0].length()<6 && Integer.parseInt(pd[1])<1500 ? "\t" :"") +"Close to "+WORD_TO_CALC_PRO_DISTANCE.toUpperCase()+" "+pd[2]+(Integer.parseInt(pd[2])<10 ?"\t":"") +"\tCloseness Factor "+(new DecimalFormat("#.####").format(Double.parseDouble(pd[3])))); /** DISCUSSIONS*/ System.out.println("\nIII/ DISCUSSION: ____________\n"+DISCUSSIONS); } }
educlong/Java-Core_Data-Structures_Algorithms
src/a03/Assignment3_Start.java
248,612
package ejb_exam.dto; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import ejb_exam.dto.request.RoleRequest; import ejb_exam.dto.response.DiscussionListResponse; import ejb_exam.dto.response.RoleResponse; import ejb_exam.dto.response.UserResponse; import ejb_exam.entities.Discussion; import ejb_exam.entities.Message; import ejb_exam.entities.Role; import ejb_exam.entities.User; public abstract class Mapper { public static RoleResponse roleToResponse(Role role) { RoleResponse roleResponse = new RoleResponse(); roleResponse.setId(role.getId()); roleResponse.setNom(role.getNom()); return roleResponse; } public static Role roleRequestToRole(RoleRequest roleRequest) { Role role = new Role(); role.setNom(roleRequest.getNom()); return role; } public static List<RoleResponse> rolesToRolesResponses(List<Role> roles){ List<RoleResponse> roleResponses = new ArrayList<>(); roles.forEach(role->roleResponses.add(roleToResponse(role))); return roleResponses; } public static DiscussionListResponse discussionTDiscussionListResponse(Discussion discussion) { DiscussionListResponse discli = new DiscussionListResponse(); User createur =discussion.getCreateur(); discli.setCreateur(createur.getPrenom() + " " + createur.getNom()); OffsetDateTime dateMessage = discussion.getDateMessage(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy", Locale.FRENCH); String formattedDate = formatter.format(dateMessage); discli.setDateMessage(formattedDate); List<Message> messages = discussion.getMessages(); Message message = null; if(!messages.isEmpty()) { message = messages.get(0); for (Message sms : messages) { if(sms.getDateMessage().compareTo(message.getDateMessage())>0) { message = sms; } } } if(message == null) { discli.setDernierMessageDate(""); discli.setDernierMessageUser("pas encore de message"); }else { discli.setDernierMessageDate(formatter.format(message.getDateMessage())); User du = message.getEnvoyeur(); discli.setDernierMessageUser(du.getPrenom()+" "+du.getNom()); } discli.setId(discussion.getId()); discli.setNombreMessages(message != null ? messages.size() : 0); discli.setSujet(discussion.getSujet()); discli.setVue(discussion.getVue()); return discli; } public static List<DiscussionListResponse> discussionsToDiscussionListResponses(List<Discussion> discussions){ List<DiscussionListResponse> discussionListResponses = new ArrayList<>(); for (Discussion discussion : discussions) { discussionListResponses.add(discussionTDiscussionListResponse(discussion)); } return discussionListResponses; } }
fayeyoussou/ejb_exam
ejbModule/ejb_exam/dto/Mapper.java
248,613
package pages; import dev.failsafe.internal.util.Assert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.EnumMap; import java.util.Map; public class BrowsePage { WebDriver driver; WebDriverWait wait; private final By threadNamePath = By.cssSelector("[class='topic-title-link '][data-analytics-index='0']"); private final By filteredByTextPath = By.cssSelector("[class='filtered-by-text']"); private final By discussionsBtnPath = By.cssSelector("a[data-filter-id='filterDiscussions']"); private final By userTipsBtnPath = By.cssSelector("a[data-filter-id='filterUserTips']"); private final By solvedQuestionsBtnPath = By.cssSelector(".filter-link[href='?type=filterAnswered']"); private final By unsolvedQuestionsBtnPath = By.cssSelector("a[data-filter-id='filterOpen']"); private final By communityBtnPath = By.cssSelector("[data-filter-group-id='community']"); private final By iPhoneBtnPath = By.cssSelector("a[data-filter-id='2043020']"); private final By iPadBtnPath = By.cssSelector("a[data-filter-id='2039020']"); private final By appleWatchBtnPath = By.cssSelector("a[data-filter-id='3061020']"); private final By topicHeadingPath = By.cssSelector("[class='topics-heading']"); private final By authorNameBtn1Path = By.cssSelector("tr:nth-child(2) > th > article > div.topic-meta > [data-action='topic-author']"); private final By popupUserNamePath = By.id("user-profile-popup-title"); private final By popupClosePath = By.cssSelector("[class='modal-close-button']"); private final By authorNameBtn2Path = By.cssSelector("tr:nth-child(2) > td.topics-table-row-latest-activity > div > a.author"); private final By subCommunityBtnPath = By.cssSelector("tr:nth-child(2) > th > article > div.topic-meta > a.community-link"); private final By filterBtnPath = By.cssSelector("[class='open-filters-button']"); public enum Button { SubCommunityButton, AuthorNameButton2, AuthorNameButton1, PopupUserName, FilteredByText, UserTipsButton, DiscussionsButton, IPhoneButton, IPadButton, CommunityButton, PopupClose, SolvedQuestionsButton, UnsolvedQuestionsButton, ThreadName, FilterButton } private final Map<BrowsePage.Button, By> paths = new EnumMap<>(BrowsePage.Button.class); { paths.put(Button.SubCommunityButton, subCommunityBtnPath); paths.put(Button.AuthorNameButton2, authorNameBtn2Path); paths.put(Button.AuthorNameButton1, authorNameBtn1Path); paths.put(Button.PopupUserName, popupUserNamePath); paths.put(Button.FilteredByText, filteredByTextPath); paths.put(Button.UserTipsButton, userTipsBtnPath); paths.put(Button.DiscussionsButton, discussionsBtnPath); paths.put(Button.IPhoneButton, iPhoneBtnPath); paths.put(Button.IPadButton, iPadBtnPath); paths.put(Button.CommunityButton, communityBtnPath); paths.put(Button.PopupClose, popupClosePath); paths.put(Button.SolvedQuestionsButton, solvedQuestionsBtnPath); paths.put(Button.UnsolvedQuestionsButton, unsolvedQuestionsBtnPath); paths.put(Button.ThreadName, threadNamePath); paths.put(Button.FilterButton, filterBtnPath); } public BrowsePage(WebDriver driver) { this.driver = driver; wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } public void clickButton(Button button) { wait.until(ExpectedConditions.elementToBeClickable(paths.get(button))).click(); } public String getButtonText(Button button) { return wait.until(ExpectedConditions.elementToBeClickable(paths.get(button))).getText(); } public void waitButtonVisibility() { wait.until(ExpectedConditions.visibilityOfElementLocated(topicHeadingPath)); } private By pagePerBtnPath(String pageCount) { return By.cssSelector("[aria-label='" + pageCount + " per page']"); } public void checkPerPageButton(String count) { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); wait.until(ExpectedConditions.visibilityOfElementLocated(pagePerBtnPath(count))).click(); driver.navigate().to("https://discussions.apple.com/browse/?page=1&perPage=" + count); String getAttributeName = wait.until(ExpectedConditions.visibilityOfElementLocated(pagePerBtnPath(count))).getAttribute("class"); String activeCountPerPagePath = "per-page-count active-per-page"; Assert.isTrue(getAttributeName.equals(activeCountPerPagePath), "per page button no active"); } public void clickAppleWatchBtn() throws InterruptedException { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollTo(0, document.body.scrollHeight/8)"); Thread.sleep(4000); wait.until(ExpectedConditions.elementToBeClickable(appleWatchBtnPath)).click(); wait.until(ExpectedConditions.elementToBeClickable(topicHeadingPath)); Thread.sleep(4000); } }
santriarustamyan/AppleWebApp
src/main/java/pages/BrowsePage.java
248,614
/* * Copyright (C) 2005 Leos Literak * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package cz.abclinuxu.data; import cz.abclinuxu.persistence.SQLTool; import cz.abclinuxu.security.Roles; import cz.abclinuxu.servlets.Constants; import cz.abclinuxu.servlets.html.edit.EditGroup; import cz.abclinuxu.utils.LRUMap; import cz.abclinuxu.utils.Misc; import cz.abclinuxu.utils.config.impl.AbcConfig; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Class containing basic user data */ public class User extends CommonObject implements ImageAssignable<User.UserImage> { /** * All available images for user * @author kapy * */ public enum UserImage implements ImageAssignable.AssignedImage { PHOTO, AVATAR } /** * login name of the user */ private String login; /** openid login */ private String openId; /** real name of the user */ private String name; /** nickname of the user */ private String nick; /** email of the user */ private String email; /** (noncrypted) password, not persisted */ private String password; /** time of last synchronization with LDAP (optional) */ private Date lastSynced; /** cache of granted user roles */ private Map roles; /** map where key is discussion id and value is id of last seen comment */ private Map<Integer, Integer> lastSeenDiscussions; public User() { super(); } public User(int id) { super(id); } /** * @return login name of the user */ public String getLogin() { return login; } /** * sets login name of the user */ public void setLogin(String login) { this.login = login; } /** * @return real name of the user */ public String getName() { return name; } /** * @return openid */ public String getOpenId() { return openId; } /** * Sets openid * @param openId valid openid url */ public void setOpenId(String openId) { this.openId = openId; } /** * sets real name of the user */ public void setName(String name) { this.name = name; } /** * @return nickname of the user */ public String getNick() { return nick; } /** * Set nickname of the user */ public void setNick(String nick) { this.nick = nick; } /** * @return email of the user */ public String getEmail() { return email; } /** * sets email of the user */ public void setEmail(String email) { this.email = email; } /** * User password. It is not persisted in database since migration to LDAP. * @return (noncrypted) password */ public String getPassword() { return password; } /** * (noncrypted) password */ public void setPassword(String password) { this.password = password; } /** * Get time of last synchronization with LDAP * * @return last synchronization time or null */ public Date getLastSynced() { return lastSynced; } /** * Sets time of last synchronization with LDAP * @param lastSynced time */ public void setLastSynced(Date lastSynced) { this.lastSynced = lastSynced; } /** * Finds out, whether user is in given role. * @param role name of role. * @return true, if user is in give role. * @see cz.abclinuxu.security.Roles */ public boolean hasRole(String role) { if (role == null || role.length() == 0) return false; if (roles == null) { Document data = getData(); if (data == null) { roles = Collections.EMPTY_MAP; return false; } List nodes = data.selectNodes("/data/roles/role"); if (nodes == null || nodes.size() == 0) { roles = Collections.EMPTY_MAP; return false; } roles = new HashMap(nodes.size(), 1.0f); for (Iterator iter = nodes.iterator(); iter.hasNext();) { String value = ((Node) iter.next()).getText(); roles.put(value, value); } } if (roles.containsKey(Roles.ROOT)) return true; if (roles.containsKey(role)) return true; return false; } /** * @return true, if user is member of specified group. */ public boolean isMemberOf(int group) { return getData().selectSingleNode("/data/system/group[text()='" + group + "']") != null; } /** * @return true, if user is member of specified group. */ public boolean isMemberOf(String groupName) { List<Item> items = SQLTool.getInstance().findItemsWithType(Item.GROUP, 0, EditGroup.DEFAULT_MAX_NUMBER_OF_GROUPS); for (Item item : items) { if (item.getTitle().equals(groupName)) return true; } return false; } public boolean isRoot() { return isMemberOf(Constants.GROUP_ADMINI); } /** * Fills last seen comments for this user. This is cache to be filled from * persistent storage, changes are not propagated to persistence. * * @param map map to be copied, key is discussion id (integer), value is * last seen comment id (integer). */ public void fillLastSeenComments(Map<Integer, Integer> map) { createLastSeenCommentsMap(); lastSeenDiscussions.putAll(map); } /** * Creates map where cache of last seen comments will be stored. */ private void createLastSeenCommentsMap() { lastSeenDiscussions = new LRUMap(AbcConfig.getMaxWatchedDiscussionLimit()); } /** * Stores id of last seen comment for given discussion (not persistent). * * @param discussion * @param lastComment */ public void storeLastSeenComment(int discussion, int lastComment) { if (lastSeenDiscussions == null) createLastSeenCommentsMap(); lastSeenDiscussions.put(discussion, lastComment); } /** * Finds id of comment that this user has seen as last. * * @param discussion id of discussion * @return id of last seen comment or null, if he has not opened that * dicussion yet */ public Integer getLastSeenComment(int discussion) { if (lastSeenDiscussions == null) return null; return lastSeenDiscussions.get(discussion); } /** * sets XML data of this object */ public void setData(Document data) { super.setData(data); roles = null; } /** * sets XML data of this object in String format */ public void setData(String data) { super.setData(data); roles = null; } public void assignImage(UserImage imageId, String imageUrl) { Element image; switch (imageId) { case AVATAR: image = DocumentHelper.makeElement(getData(), "/data/profile/avatar"); break; case PHOTO: image = DocumentHelper.makeElement(getData(), "/data/profile/photo"); break; default: return; } if (image != null) image.setText(imageUrl); } public String detractImage(UserImage imageId) { Node node; switch (imageId) { case AVATAR: node = getData().selectSingleNode("/data/profile/avatar"); break; case PHOTO: node = getData().selectSingleNode("/data/profile/photo"); break; default: return null; } String url = null; if (node != null) { url = node.getText(); node.detach(); } return url; } public String proposeImageUrl(UserImage imageId, String suffix) { StringBuilder sb = new StringBuilder(); switch (imageId) { case AVATAR: return sb.append("images/avatars/").append(id).append('.').append(suffix).toString(); case PHOTO: return sb.append("images/faces/").append(id).append('.').append(suffix).toString(); default: return null; } } /** * Initialize this object with values from <code>obj</code>, if * this.getClass.equals(obj.getClass()). */ public void synchronizeWith(GenericObject obj) { if (!(obj instanceof User)) return; if (obj == this) return; super.synchronizeWith(obj); User b = (User) obj; name = b.getName(); nick = b.getNick(); login = b.getLogin(); email = b.getEmail(); password = b.getPassword(); } public String toString() { StringBuffer sb = new StringBuffer("User: id="); sb.append(id); if (name != null) sb.append(",name=").append(name); return sb.toString(); } public boolean preciseEquals(Object o) { if (!(o instanceof User)) return false; User p = (User) o; if (id != p.id) return false; if (!Misc.same(login, p.login)) return false; if (!Misc.same(name, p.name)) return false; if (!Misc.same(nick, p.nick)) return false; if (!Misc.same(email, p.email)) return false; if (!Misc.same(password, p.password)) return false; if (!Misc.sameXml(getDataAsString(), p.getDataAsString())) return false; return true; } public int hashCode() { String tmp = "User" + id; return tmp.hashCode(); } /** * Compares content fields of this and that GenericObject. The argument must * be instance of same class and have same content properties. * * @param obj compared class * @return true if both instances have same content */ public boolean contentEquals(GenericObject obj) { if (obj == this) return true; if (!super.contentEquals(obj)) return false; User p = (User) obj; if (!Misc.same(login, p.login)) return false; if (!Misc.same(name, p.name)) return false; if (!Misc.same(nick, p.nick)) return false; return Misc.same(email, p.email); } }
abclinuxu/abclinuxu
src/cz/abclinuxu/data/User.java
248,615
package com.exzalt.mdroid; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; public class Forums extends BaseActivity { String courseName = ""; String courseID = ""; String forumID = ""; String forumName = ""; String discussionCount = "0"; ArrayList<String> DiscussionIDs = new ArrayList<String>(); ArrayList<String> DiscussionSubject = new ArrayList<String>(); ArrayList<String> DiscussionAuthor = new ArrayList<String>(); ArrayList<String> DiscussionRepliesCount = new ArrayList<String>(); ArrayList<String> DiscussionLastPostTime = new ArrayList<String>(); @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.forums); // For getting Preferences appPrefs = new AppPreferences(getApplicationContext()); Bundle extras = getIntent().getExtras(); if (extras == null) { return; } courseID = extras.getString("courseID"); courseName = extras.getString("courseName"); forumID = extras.getString("forumID"); forumName = extras.getString("forumName"); // Setting title of FileListing activity.. setTitle(forumName + " (" + discussionCount + "): " + courseName); new getForumsPageContent().execute(forumID); } /* AsycTask Thread */ private class getForumsPageContent extends AsyncTask<String, Integer, Long> { protected Long doInBackground(String... forumID) { try { getPageContentForumsTwo(forumID[0]); } catch (ClientProtocolException e) { } catch (IOException e) { } return null; } protected void onProgressUpdate(Integer... progress) { } protected void onPostExecute(Long result) { // Changing title of FileListing activity.. setTitle(forumName + " (" + discussionCount + "): " + courseName); listFilesInListView(DiscussionIDs, DiscussionSubject, DiscussionAuthor, DiscussionRepliesCount, DiscussionLastPostTime); } } public void getPageContentForumsTwo(String forumViewID) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = MainActivity.httpclient; HttpGet httpgetCourse = new HttpGet(serverAddress + "/mod/forum/view.php?f=" + forumViewID); HttpResponse responseCourse = httpclient.execute(httpgetCourse); HttpEntity entityCourse = responseCourse.getEntity(); try { inputStreamToStringForumsTwo(responseCourse.getEntity() .getContent()); } catch (IOException e) { } if (entityCourse != null) { entityCourse.consumeContent(); } } private void inputStreamToStringForumsTwo(InputStream is) throws IOException { String line = ""; StringBuilder total = new StringBuilder(); // Wrap a BufferedReader around the InputStream BufferedReader rd = new BufferedReader(new InputStreamReader(is)); // Read response until the end while ((line = rd.readLine()) != null) { total.append(line); } extractFileDetailsForForumsTwo(total.toString()); } // Call to ListFilesInListView for Forum files made here.. public void extractFileDetailsForForumsTwo(String htmlDataString) { int prevIndex = 0; int endIndex = 0; while (true) { prevIndex = htmlDataString.indexOf( "class=\"topic starter\"><a href=\"", prevIndex); if (prevIndex == -1) break; // for Post ID prevIndex += 31; endIndex = htmlDataString.indexOf("\"", prevIndex); DiscussionIDs.add(htmlDataString.substring(prevIndex, endIndex)); // for post subject prevIndex = endIndex + 2; endIndex = htmlDataString.indexOf("</a>", prevIndex); String textConvertedhtmlDataString = htmlDataString.substring( prevIndex, endIndex); textConvertedhtmlDataString = android.text.Html.fromHtml( textConvertedhtmlDataString).toString(); DiscussionSubject.add(textConvertedhtmlDataString); // for post Author prevIndex = endIndex; prevIndex = htmlDataString.indexOf( "<td class=\"author\"><a href=\"", prevIndex) + 28; prevIndex = htmlDataString.indexOf("\">", prevIndex) + 2; endIndex = htmlDataString.indexOf("</a>", prevIndex); DiscussionAuthor.add(htmlDataString.substring(prevIndex, endIndex)); // for post replies count prevIndex = endIndex; prevIndex = htmlDataString.indexOf( "<td class=\"replies\"><a href=\"", prevIndex) + 29; prevIndex = htmlDataString.indexOf("\">", prevIndex) + 2; endIndex = htmlDataString.indexOf("</a>", prevIndex); DiscussionRepliesCount.add(htmlDataString.substring(prevIndex, endIndex)); // for post last reply time prevIndex = endIndex; prevIndex = htmlDataString.indexOf( "<td class=\"lastpost\"><a href=\"", prevIndex) + 30; prevIndex = htmlDataString.indexOf("\">", prevIndex) + 2; prevIndex = htmlDataString.indexOf("\">", prevIndex) + 2; prevIndex = htmlDataString.indexOf(",", prevIndex) + 2; endIndex = htmlDataString.indexOf("</a>", prevIndex); DiscussionLastPostTime.add(htmlDataString.substring(prevIndex, endIndex)); } discussionCount = DiscussionIDs.size() + ""; } public void listFilesInListView(ArrayList<String> DiscussionIDs, ArrayList<String> DiscussionSubject, ArrayList<String> DiscussionAuthor, ArrayList<String> DiscussionRepliesCount, ArrayList<String> DiscussionLastPostTime) { if(DiscussionSubject.size() == 0){ ((TextView)this.findViewById(R.id.forumTitle)).setText("Forum Empty"); ((ProgressBar)this.findViewById(R.id.progressBarForum)).setVisibility(View.GONE); return; } this.findViewById(R.id.forum_loading_card).setVisibility(View.GONE); ListView forumsList = (ListView) findViewById(R.id.forumListView); ForumCardAdapter cardAdapter = new ForumCardAdapter(this); for(int i=0; i<DiscussionSubject.size(); i++){ cardAdapter.add(new ForumCard(DiscussionIDs.get(i), DiscussionSubject.get(i), DiscussionAuthor.get(i), DiscussionRepliesCount.get(i), DiscussionLastPostTime.get(i))); } forumsList.setAdapter(cardAdapter); ListHelper.getListViewSize(forumsList); } public class ForumCardAdapter extends BaseAdapter { private Context context; private ArrayList<ForumCard> items; private boolean isChanged = false; private int mScrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE; private int mAccentColor; private int mPopupMenu = -1; private boolean mCardsClickable = true; private int mLayout = R.layout.forumslistviewlayout; public ForumCardAdapter(Context context) { this.context = context; this.items = new ArrayList<ForumCard>(); mAccentColor = context.getResources().getColor(android.R.color.black); } @Override public boolean isEnabled(int position) { ForumCard item = getItem(position); if (!mCardsClickable) return false; else return true; } public final ForumCardAdapter setAccentColor(int color) { mAccentColor = color; return this; } public final ForumCardAdapter setAccentColorRes(int colorRes) { setAccentColor(getContext().getResources().getColor(colorRes)); return this; } public final ForumCardAdapter setCardLayout(int layoutRes) { mLayout = layoutRes; return this; } public int getLayout(int index, int type) { return getItem(index).getLayout(); } private void invalidatePadding(int index, View view) { int top = index == 0 ? R.dimen.card_outer_padding_firstlast : R.dimen.card_outer_padding_top; int bottom = index == (getCount() - 1) ? R.dimen.card_outer_padding_firstlast : R.dimen.card_outer_padding_top; view.setPadding(view.getPaddingLeft(), getContext().getResources().getDimensionPixelSize(top), view.getPaddingRight(), getContext().getResources().getDimensionPixelSize(bottom)); } @Override public int getCount() { // TODO Auto-generated method stub return items.size(); } @Override public ForumCard getItem(int i) { return items.get(i); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.forumslistviewlayout, null); } invalidatePadding(position, convertView); ForumCard item = new ForumCard(getItem(position)); final TextView subjectTextView = (TextView) convertView .findViewById(R.id.forumThreadSubject); subjectTextView.setText(item.getSubject()); subjectTextView.setHint(item.getId()); final TextView repliesCountTextView = (TextView) convertView .findViewById(R.id.forumThreadRepliesCount); repliesCountTextView.setText("(" + item.getRepliesCount() + ")"); final TextView authorTextView = (TextView) convertView .findViewById(R.id.forumThreadAuthor); authorTextView.setText(item.getAuthor()); final TextView timeTextView = (TextView) convertView .findViewById(R.id.forumThreadStartTime); timeTextView.setText(item.getLastPostTime()); convertView.setOnClickListener(new OnClickListener() { public void onClick(View v) { final int REQUEST_CODE = 16; Intent i = new Intent(context, ForumDiscussThread.class); i.putExtra("discussID", subjectTextView.getHint() + "&mode=1"); i.putExtra("discussSubject", subjectTextView.getText()); i.putExtra("courseName", courseName); startActivityForResult(i, REQUEST_CODE); } }); return convertView; } public final Context getContext() { return context; } //functions below from Silk Adapter public void add(int index, ForumCard toAdd) { isChanged = true; this.items.add(index, toAdd); notifyDataSetChanged(); } /** * Adds a single item to the adapter and notifies the attached ListView. */ public void add(ForumCard toAdd) { isChanged = true; this.items.add(toAdd); //notifyDataSetChanged(); } /** * Updates a single item in the adapter using isSame() from SilkComparable. Once the filter finds the item, the loop is broken * so you cannot update multiple items with a single call. * <p/> * If the item is not found, it will be added to the adapter. * * @return True if the item was updated. */ public boolean update(ForumCard toUpdate) { return update(toUpdate, true); } /** * Updates a single item in the adapter using isSame() from SilkComparable. Once the filter finds the item, the loop is broken * so you cannot update multiple items with a single call. * * @param addIfNotFound Whether or not the item will be added if it's not found. * @return True if the item was updated or added. */ public boolean update(ForumCard toUpdate, boolean addIfNotFound) { boolean found = false; for (int i = 0; i < items.size(); i++) { if (toUpdate.isSameAs(items.get(i))) { items.set(i, toUpdate); found = true; break; } } if (found) return true; else if (addIfNotFound && !found) { add(toUpdate); return true; } return false; } } }
anilshanbhag/MDroid
src/com/exzalt/mdroid/Forums.java
248,616
// // $Id$ package client.groups; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.threerings.orth.data.MediaDescSize; import com.threerings.gwt.ui.EnterClickAdapter; import com.threerings.gwt.ui.FloatPanel; import com.threerings.gwt.ui.InlinePanel; import com.threerings.gwt.ui.SmartTable; import com.threerings.msoy.group.gwt.GalaxyData; import com.threerings.msoy.group.gwt.GroupCard; import com.threerings.msoy.group.gwt.GroupService; import com.threerings.msoy.group.gwt.GroupServiceAsync; import com.threerings.msoy.web.gwt.Pages; import client.shell.CShell; import client.ui.MsoyUI; import client.ui.ThumbBox; import client.util.InfoCallback; import client.util.Link; /** * Display the public groups in a sensical manner, including a sorted list of characters that * start the groups, allowing people to select a subset of the public groups to view. */ public class GalaxyPanel extends FlowPanel { public GalaxyPanel () { setStyleName("galaxyPanel"); add(MsoyUI.createNowLoading()); _groupsvc.getGalaxyData(new InfoCallback<GalaxyData>() { public void onSuccess (GalaxyData galaxy) { init(galaxy); } }); } /** * Called when my groups & tags data is retrieved after this panel is created; populate the * page with data. */ protected void init (final GalaxyData data) { clear(); // search box floats on far right FloatPanel search = new FloatPanel("Search"); search.add(MsoyUI.createLabel(_msgs.galaxySearchTitle(), "SearchTitle")); final TextBox searchInput = MsoyUI.createTextBox("", 255, 15); search.add(searchInput); ClickHandler doSearch = new ClickHandler() { public void onClick (ClickEvent event) { Link.go(Pages.GROUPS, ACTION_SEARCH, 0, searchInput.getText().trim()); } }; EnterClickAdapter.bind(searchInput, doSearch); search.add(MsoyUI.createImageButton("GoButton", doSearch)); add(search); // blurb about groups on the left InlinePanel introBlurb = new InlinePanel("IntroBlurb"); add(introBlurb); introBlurb.add(MsoyUI.createHTML(_msgs.galaxyIntroBlurb(), null)); if (!CShell.isGuest()) { introBlurb.add(MsoyUI.createHTML(_msgs.galaxyIntroCreate(), null)); } // category tag links add(new CategoryLinks()); FloatPanel content = new FloatPanel("Content"); add(content); FlowPanel leftColumn = MsoyUI.createFlowPanel("LeftColumn"); content.add(leftColumn); // add the My Groups display leftColumn.add(MsoyUI.createLabel(_msgs.galaxyMyGroupsTitle(), "MyGroupsHeader")); FlowPanel myGroups = MsoyUI.createFlowPanel("QuickGroups"); myGroups.addStyleName("MyGroups"); leftColumn.add(myGroups); if (data.myGroups.size() == 0) { myGroups.add(MsoyUI.createLabel(_msgs.galaxyMyGroupsNone(), "NoGroups")); } else { for (GroupCard group : data.myGroups) { myGroups.add(createQuickGroupWidget(group)); } myGroups.add(Link.create(_msgs.galaxySeeAll(), "SeeAll", Pages.GROUPS, "mygroups")); } // add the official groups display FlowPanel officialGroups = MsoyUI.createFlowPanel("QuickGroups"); leftColumn.add(MsoyUI.createLabel(_msgs.galaxyOfficialGroupsTitle(), "OfficialGroupsHeader")); officialGroups.addStyleName("OfficialGroups"); for (GroupCard group : data.officialGroups) { officialGroups.add(createQuickGroupWidget(group)); } leftColumn.add(officialGroups); content.add(MsoyUI.createLabel(_msgs.galaxyFeaturedTitle(), "FeaturedHeader")); SmartTable grid = new SmartTable("GroupsList", 0, 10); int row = 0, col = 0; for (GroupCard card : data.featuredGroups) { grid.setWidget(row, col, createGroupWidget(card)); if (++col == GRID_COLUMNS) { row++; col = 0; } } grid.addWidget(Link.create(_msgs.galaxySeeAll(), Pages.GROUPS, "list"), GRID_COLUMNS, "SeeAll"); content.add(grid); } /** * A single one of "my" groups on the left column. */ protected Widget createQuickGroupWidget (GroupCard group) { FloatPanel widget = new FloatPanel("Group"); widget.add(new ThumbBox(group.getLogo(), MediaDescSize.QUARTER_THUMBNAIL_SIZE, Pages.GROUPS, "d", group.name.getGroupId())); widget.add(Link.create(group.name.toString(), "Name", Pages.GROUPS, "d", group.name.getGroupId())); widget.add(Link.create(_msgs.galaxyMyGroupsDiscussions(), "Discussions", Pages.GROUPS, "f", group.name.getGroupId())); return widget; } /** * A single group in the right column grid */ protected Widget createGroupWidget (GroupCard group) { FlowPanel widget = MsoyUI.createFlowPanel("Group"); FloatPanel logoAndName = new FloatPanel("LogoAndName"); logoAndName.add(new ThumbBox(group.getLogo(), MediaDescSize.HALF_THUMBNAIL_SIZE, Pages.GROUPS, "d", group.name.getGroupId())); logoAndName.add(Link.create(group.name.toString(), "GroupName", Pages.GROUPS, "d", group.name.getGroupId())); widget.add(logoAndName); widget.add(MsoyUI.createLabel(_msgs.galaxyMemberCount(group.memberCount + " "), "MemberCount")); widget.add(Link.create(_msgs.galaxyPeopleInRooms(group.population + ""), "InRooms", Pages.WORLD, "s" + group.homeSceneId)); widget.add(Link.create(_msgs.galaxyDiscussions(), "ThreadCount", Pages.GROUPS, "f", group.name.getGroupId())); return widget; } /* dynamic widgets */ protected CategoryLinks _categoryLinks; protected static final GroupsMessages _msgs = GWT.create(GroupsMessages.class); protected static final GroupServiceAsync _groupsvc = GWT.create(GroupService.class); protected static final String ACTION_SEARCH = "search"; protected static final int GRID_COLUMNS = 4; }
greyhavens/msoy
src/gwt/client/groups/GalaxyPanel.java
248,617
/* * emxDiscussionBase.java * * Copyright (c) 1992-2016 Dassault Systemes. * * All Rights Reserved. * This program contains proprietary and trade secret information of * MatrixOne, Inc. Copyright notice is precautionary only and does * not evidence any actual or intended publication of such program. * */ import java.io.BufferedReader; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import matrix.db.Access; import matrix.db.AccessItr; import matrix.db.AccessList; import matrix.db.BusinessObject; import matrix.db.BusinessObjectList; import matrix.db.BusinessObjectWithSelect; import matrix.db.BusinessObjectWithSelectList; import matrix.db.Context; import matrix.db.JPO; import matrix.util.SelectList; import matrix.util.StringList; import matrix.util.Pattern; import com.matrixone.apps.common.CommonDocument; import com.matrixone.apps.common.Company; import com.matrixone.apps.common.Message; import com.matrixone.apps.common.Person; import com.matrixone.apps.common.Route; import com.matrixone.apps.common.util.ComponentsUtil; import com.matrixone.apps.domain.DomainConstants; import com.matrixone.apps.domain.DomainObject; import com.matrixone.apps.domain.util.AccessUtil; import com.matrixone.apps.domain.util.EnoviaResourceBundle; import com.matrixone.apps.domain.util.FrameworkException; import com.matrixone.apps.domain.util.FrameworkProperties; import com.matrixone.apps.domain.util.FrameworkUtil; import com.matrixone.apps.domain.util.MapList; import com.matrixone.apps.domain.util.MqlUtil; import com.matrixone.apps.domain.util.PersonUtil; import com.matrixone.apps.domain.util.PropertyUtil; import com.matrixone.apps.domain.util.XSSUtil; import com.matrixone.apps.domain.util.ContextUtil; import com.matrixone.apps.domain.util.eMatrixDateFormat; import com.matrixone.apps.domain.util.i18nNow; import com.matrixone.apps.framework.ui.UIUtil; /** * @version AEF Rossini - Copyright (c) 2002, MatrixOne, Inc. */ public class emxDiscussionBase_mxJPO extends emxDomainObject_mxJPO { /** * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments * @throws Exception if the operation fails * @since AEF Rossini * @grade 0 */ public emxDiscussionBase_mxJPO (Context context, String[] args) throws Exception { super(context, args); } /** * This method is executed if a specific method is not specified. * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments * @return nothing * @throws Exception if the operation fails * @since AEF Rossini * @grade 0 */ public int mxMain(Context context, String[] args) throws Exception { if (!context.isConnected()) throw new Exception(ComponentsUtil.i18nStringNow("emxComponents.Generic.NotSupportedOnDesktopClient", context.getLocale().getLanguage())); return 0; } /***** * Constants for grantor User Name * ******/ /** Workspace Access User name. */ static final String AEF_WORKSPACE_ACCESS_GRANTOR_USERNAME = "Workspace Access Grantor"; /** Workspace Access User name. */ static final String AEF_WORKSPACE_LEAD_GRANTOR_USERNAME = "Workspace Lead Grantor"; /** Workspace Access User name. */ static final String AEF_WORKSPACE_MEMBER_GRANTOR_USERNAME = "Workspace Member Grantor"; /** Workspace Access User name. */ static final String AEF_ROUTE_DELEGATION_GRANTOR_USERNAME = "Route Delegation Grantor"; static final String ROLE_EMPLOYEE = PropertyUtil.getSchemaProperty ("role_Employee"); /** * getDiscussionMembersList - gets the list of Members the user has access to the Discussion. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @return Object * @throws Exception if the operation fails * @since AEF Rossini * @grade 0 */ @com.matrixone.apps.framework.ui.ProgramCallable public Object getDiscussionMembersList(Context context, String[] args) throws Exception { try { pushContextAccessGrantor(context); HashMap programMap = (HashMap) JPO.unpackArgs(args); MapList discussionMembers = new MapList(); String objectId = (String) programMap.get("objectId"); String SELECT_ROUTE_ID = "to["+RELATIONSHIP_MESSAGE+"].from.to["+RELATIONSHIP_THREAD+"].from.id"; String SELECT_ACCESS_TYPE = "to["+RELATIONSHIP_MESSAGE+"].attribute["+ATTRIBUTE_ACCESS_TYPE+"].value"; DomainObject message = newInstance(context); message.setId(objectId); StringList objSelects = new StringList(); objSelects.add(SELECT_ROUTE_ID); objSelects.add(SELECT_ACCESS_TYPE); Map resultMap = message.getInfo(context,objSelects); String accessType = (String)resultMap.get(SELECT_ACCESS_TYPE); String routeId = (String)resultMap.get(SELECT_ROUTE_ID); String SELECT_ROUTE_MEMBER_ID = "from["+DomainObject.RELATIONSHIP_ROUTE_NODE+"].to.id"; DomainObject route = newInstance(context); route.setId(routeId); StringList routeMembers = route.getInfoList(context,SELECT_ROUTE_MEMBER_ID); HashMap member = null; DomainObject person = newInstance(context); if(accessType.equals("Inherited")) { for(int i=0;i<routeMembers.size();i++) { member = new HashMap(); member.put(SELECT_ID,(String)routeMembers.get(i)); member.put(KEY_LEVEL,"1"); discussionMembers.add(member); } } else { StringList grantees = message.getGrantees(context); for(int i=0;i<routeMembers.size();i++) { member = new HashMap(); person.setId((String)routeMembers.get(i)); if(grantees != null) { if(grantees.indexOf((String)person.getName(context)) != -1) { member.put(SELECT_ID,(String)person.getId()); member.put(KEY_LEVEL,"1"); discussionMembers.add(member); } } } } return discussionMembers; } catch (Exception ex) { throw ex; } finally { ContextUtil.popContext(context); } } /** * Grants Access to Project Member for the workspace and its data structure. * * @param context the eMatrix Context object * @param Access List of Access objects holds the access rights, grantee and grantor. * @throws Exception if the operation fails * @since TC V3 * @grade 0 */ public void grantAccess(matrix.db.Context context, String[] args) throws Exception { boolean hasAccess = false; try { // check if the logged in user has access to edit the access for the object hasAccess = AccessUtil.isOwnerWorkspaceLead(context, this.getId()); } catch(Exception fex) { throw(fex); } if(!hasAccess) { return; } // Access Iterator of the Access list passed. AccessItr accessItr = new AccessItr((AccessList)JPO.unpackArgs(args)); Access access = null; // BO list of the current object BusinessObjectList objList = new BusinessObjectList(); objList.addElement(this); while (accessItr.next()) { access = (Access)accessItr.obj(); // push the context for grantor. pushContextForGrantor(context, access.getGrantor()); try { grantAccessRights(context, objList, access); } catch(Exception exp) { if(access.getGrantor().equals(AEF_WORKSPACE_MEMBER_GRANTOR_USERNAME)) { ContextUtil.popContext(context); MqlUtil.mqlCommand(context, "trigger $1", true, "on"); } ContextUtil.popContext(context); throw exp; } // if Access granted is empty then Revoke the access from grantee for business Object List if(access.getGrantor().equals(AEF_WORKSPACE_MEMBER_GRANTOR_USERNAME)) { if (access.hasNoAccess()) { revokeAccessGrantorGrantee(context, access.getGrantor(), access.getUser()); } ContextUtil.popContext(context); MqlUtil.mqlCommand(context, "trigger $1", true, "on"); } ContextUtil.popContext(context); } } /** * getDiscussionList - gets the list of Discussions attached to the object. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF Rossini * @grade 0 */ @com.matrixone.apps.framework.ui.ProgramCallable public Object getDiscussionList(Context context, String[] args) throws Exception { MapList list = new MapList(); if (args.length == 0 ) { throw new IllegalArgumentException(); } HashMap paramMap = (HashMap)JPO.unpackArgs(args); String objectId = (String)paramMap.get("objectId"); // added for the Bug 339013 String strPolicy = PropertyUtil.getSchemaProperty(context,"policy_PrivateMessage"); String strOwner = context.getUser(); String roleEmployee = PropertyUtil.getSchemaProperty ( context, "role_Employee" ); boolean hasEmpRole =false; Vector assignments = new Vector(); assignments = PersonUtil.getAssignments(context); if(assignments.contains(roleEmployee)) { hasEmpRole= true; } // Till Here if(objectId.indexOf("~") != -1) { objectId = objectId.substring(0,objectId.indexOf("~")); } if(FrameworkUtil.isObjectId(context,objectId)) { DomainObject messageHolder = DomainObject.newInstance(context,objectId); StringList objectSelects = new StringList(); objectSelects.add(SELECT_ID); objectSelects.add(SELECT_OWNER); objectSelects.add(SELECT_POLICY); // added for the Bug 339013 String objectWhere = "((policy =="+"\""+DomainConstants.POLICY_MESSAGE+"\")||((policy =="+"\""+strPolicy+"\") && ("+ Boolean.valueOf(hasEmpRole) +" || (owner =="+"\""+strOwner+"\"))))"; list = Message.getMessages(context, messageHolder, objectSelects,objectWhere, 1); } return list; } /** * showCommand - Returns true of the context person is the owner of message object. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns boolean * @throws Exception if the operation fails * @since AEF Rossini * @grade 0 */ public boolean showCommand(Context context, String[] args) throws Exception { if (args.length == 0 ) throw new IllegalArgumentException(); HashMap paramMap = (HashMap)JPO.unpackArgs(args); boolean showCommand = false; String objectId = (String)paramMap.get("objectId"); DomainObject obj = newInstance(context); obj.setId(objectId); com.matrixone.apps.common.Person contextPerson = com.matrixone.apps.common.Person.getPerson(context); String owner = obj.getInfo(context,SELECT_OWNER); if(owner.equals(contextPerson.getName())) { showCommand = true; } return showCommand; } /** * Revoke access on Object b/w particular Grantor and Grantee * * @param context the eMatrix Context object * @param grantor name to push context to. * @return void * @throws Exception if the operation fails * @since TC V3 * @grade 0 */ protected void revokeAccessGrantorGrantee(matrix.db.Context context, String sGrantor, String sGrantee) throws Exception { MqlUtil.mqlCommand(context,"modify bus $1 revoke grantor $2 grantee $3", getId(context), sGrantor, sGrantee); } /** * Change context to Workspace Access Grantor * * @param context the eMatrix Context object * @return void * @throws Exception if the operation fails * @since TC V3 * @grade 0 */ protected void pushContextAccessGrantor(Context context) throws Exception { ContextUtil.pushContext(context, AEF_WORKSPACE_ACCESS_GRANTOR_USERNAME, null, null); } /** * Push the context for the respective grantor. * * @param context the eMatrix Context object * @param grantor name to push context to. * @return void * @throws Exception if the operation fails * @since TC V3 * @grade 0 */ protected void pushContextForGrantor(matrix.db.Context context, String sGrantor) throws Exception { // Check for grantor. if(sGrantor.equals(AEF_WORKSPACE_ACCESS_GRANTOR_USERNAME)) { pushContextAccessGrantor(context); } else if (sGrantor.equals(AEF_WORKSPACE_MEMBER_GRANTOR_USERNAME)) { pushContextMemberGrantor(context); } else if (sGrantor.equals(AEF_WORKSPACE_LEAD_GRANTOR_USERNAME)) { pushContextLeadGrantor(context); } } /** * Change context to Workspace Member Grantor * * @param context the eMatrix Context object * @return void * @throws Exception if the operation fails * @since TC V3 * @grade 0 */ protected void pushContextMemberGrantor(Context context) throws Exception { // Puch context to super user to turn off triggers ContextUtil.pushContext(context, null, null, null); try { // Turn off all triggers MqlUtil.mqlCommand(context, "trigger $1", true, "off"); } catch (Exception exp) { ContextUtil.popContext(context); throw exp; } ContextUtil.pushContext(context, AEF_WORKSPACE_MEMBER_GRANTOR_USERNAME, null, null); } /** * Change context to Workspace Lead Grantor * * @param context the eMatrix Context object * @return void * @throws Exception if the operation fails * @since TC V3 * @grade 0 */ protected void pushContextLeadGrantor(Context context) throws Exception { ContextUtil.pushContext(context, AEF_WORKSPACE_LEAD_GRANTOR_USERNAME, null, null); } /** * showCheckbox - determines if the checkbox needs to be enabled in the column of the Discussion Summary table * * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object of type Vector * @throws Exception if the operation fails * @since Common 10-0-0-0 * @grade 0 */ public Vector showCheckbox(Context context, String[] args) throws Exception { try { HashMap programMap = (HashMap) JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Vector enableCheckbox = new Vector(); String user = context.getUser(); Iterator objectListItr = objectList.iterator(); while(objectListItr.hasNext()) { Map objectMap = (Map) objectListItr.next(); String owner = (String)objectMap.get(SELECT_OWNER); if(user.equals(owner)) { enableCheckbox.add("true"); } else { enableCheckbox.add("false"); } } return enableCheckbox; } catch (Exception ex) { throw ex; } } /** * getDiscussionAttachmentsList - gets the list of Attachments for the * Discussion. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns MapList * @throws Exception if the operation fails * @since APP 10-5 */ @com.matrixone.apps.framework.ui.ProgramCallable public MapList getDiscussionAttachmentsList(Context context, String[] args) throws Exception { MapList attachmentList = new MapList(); try { HashMap programMap = (HashMap) JPO.unpackArgs(args); String objectId = (String) programMap.get("objectId"); Pattern relPattern = new Pattern(DomainObject.RELATIONSHIP_MESSAGE_ATTACHMENTS); relPattern.addPattern(DomainObject.RELATIONSHIP_REPLY); Pattern includeRelPattern = new Pattern(DomainObject.RELATIONSHIP_MESSAGE_ATTACHMENTS); StringList typeSelects = new StringList(10); typeSelects.add(CommonDocument.SELECT_ID); typeSelects.add(CommonDocument.SELECT_TYPE); typeSelects.add(CommonDocument.SELECT_FILE_NAME); typeSelects.add(CommonDocument.SELECT_ACTIVE_FILE_LOCKED); typeSelects.add(CommonDocument.SELECT_TITLE); typeSelects.add(CommonDocument.SELECT_REVISION); typeSelects.add(CommonDocument.SELECT_NAME); typeSelects.add(CommonDocument.SELECT_ACTIVE_FILE_VERSION); typeSelects.add(CommonDocument.SELECT_HAS_ROUTE); typeSelects.add(CommonDocument.SELECT_FILE_NAMES_OF_ACTIVE_VERSION); typeSelects.add(CommonDocument.SELECT_SUSPEND_VERSIONING); typeSelects.add(CommonDocument.SELECT_HAS_CHECKOUT_ACCESS); typeSelects.add(CommonDocument.SELECT_HAS_CHECKIN_ACCESS); StringList relSelects = new StringList(1); relSelects.add(DomainConstants.SELECT_RELATIONSHIP_ID); DomainObject discussionObj = DomainObject.newInstance(context); discussionObj.setId(objectId); attachmentList = discussionObj.getRelatedObjects(context, relPattern.getPattern(), "*", typeSelects, relSelects, false, true, (short)2, null, null, null, includeRelPattern, null); } catch (Exception ex) { throw ex; } finally { return attachmentList; } } /////////////////// My Discussions ///////////////////////////////////////////////////////////////// /** * getFilteredDiscussionList - filters the list of Discussions present in the system based on the where expression * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF Rossini * @grade 0 */ protected Object getFilteredDiscussionList(Context context,String whereExpression) throws Exception { MapList finalMapList = new MapList(); try { com.matrixone.apps.common.Person person = com.matrixone.apps.common.Person.getPerson(context); Company company = person.getCompany(context); BufferedReader in = new BufferedReader(new StringReader(MqlUtil.mqlCommand(context,"temp query bus $1 $2 $3 vault $4 where $5 select $6 $7 dump $8",TYPE_MESSAGE, "*", "*", company.getAllVaults(context,true), whereExpression, "id", "policy", "|" ))); String line; while ((line = in.readLine()) != null) { int lastIdxOfSeperator = line.lastIndexOf("|"); String policy = line.substring(lastIdxOfSeperator + 1); String id = line.substring(line.lastIndexOf("|", lastIdxOfSeperator - 1)+1, lastIdxOfSeperator); Map objMap = new HashMap(); objMap.put(SELECT_ID, id); objMap.put(SELECT_POLICY, policy); finalMapList.add(objMap); } } catch(Exception ex) { throw ex; } return finalMapList; } /** * showSubscriptionStatus - shows a visual cue if the discussion is subscribed or not * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @return Vector * @throws Exception if the operation fails * @since AEF V11 * @grade 0 */ public Vector getSubscriptionIcon(Context context, String[] args) throws Exception { if (args.length == 0 ) { throw new IllegalArgumentException(); } Vector vSubscribed = new Vector(); String contextUser = context.getUser(); String relPublishSubscribe = PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_PublishSubscribe); String relPublish = PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_Publish); String relSubscribedPerson = PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_SubscribedPerson); String selSubPersonName = new StringBuffer().append("from[").append(relPublishSubscribe).append("].to.from[").append(relPublish). append("].to.from[").append(relSubscribedPerson).append("].to.name").toString(); String selRootObjId = new StringBuffer().append("to[").append(PropertyUtil.getSchemaProperty(context,"relationship_Message")). append("].from.to[").append(PropertyUtil.getSchemaProperty(context,"relationship_Thread")).append("].from.id").toString(); String selEventIdFromRootObj = new StringBuffer("from[").append(relPublishSubscribe).append("].to.from["). append(relPublish).append("].to.id").toString(); String selEventTypeFromEvent = new StringBuffer("attribute[").append(PropertyUtil.getSchemaProperty(context,"attribute_EventType")).append("]").toString(); String selEventSubscirbedPersonFromEvent = new StringBuffer("from[").append(relSubscribedPerson).append("].to.name").toString(); DomainObject.MULTI_VALUE_LIST.add(selSubPersonName); StringList selectList = new StringList(); selectList.addElement(selSubPersonName); selectList.addElement(selRootObjId); StringList eventSelList = new StringList(); eventSelList.add(selEventTypeFromEvent); eventSelList.add(selEventSubscirbedPersonFromEvent); try { HashMap programMap = (HashMap) JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Iterator objItr = objectList.iterator(); String strSubscribed = EnoviaResourceBundle.getProperty(context,"emxComponentsStringResource",new Locale(context.getSession().getLanguage()),"emxComponents.Common.Subscribed"); strSubscribed = FrameworkUtil.findAndReplace(strSubscribed, "\'", "&#39;"); strSubscribed = FrameworkUtil.findAndReplace(strSubscribed, "\"", "&quot;"); //XSSOK String imgSrc ="<img src='images/iconSmallSubscription.gif' title=\'"+strSubscribed+"\' ></img>"; String objIds[] = new String[objectList.size()]; int i=0; while(objItr.hasNext()) { Map messageObj = (Map) objItr.next(); objIds[i] = (String)messageObj.get(SELECT_ID); i++; } BusinessObjectWithSelectList bosWithSelect = BusinessObject.getSelectBusinessObjectData(context,objIds,selectList); for(int j=0;j<bosWithSelect.size();j++) { BusinessObjectWithSelect bows = bosWithSelect.getElement(j); StringList subscriptionStatus = bows.getSelectDataList(selSubPersonName); //Default show blank, if the context user is subscribed then show imange. String subscriptionICON = "&#160;"; if(subscriptionStatus!=null && subscriptionStatus.contains(contextUser)) { subscriptionICON = imgSrc; } else { String rootId = bows.getSelectData(selRootObjId); DomainObject rootObj = new DomainObject(rootId); StringList eventIds = rootObj.getInfoList(context, selEventIdFromRootObj); BusinessObjectWithSelectList eventInfo = BusinessObject.getSelectBusinessObjectData(context, (String[])eventIds.toArray(new String []{}), eventSelList); for (Iterator iter = eventInfo.iterator(); iter.hasNext();) { BusinessObjectWithSelect event = (BusinessObjectWithSelect) iter.next(); String eventType = event.getSelectData(selEventTypeFromEvent); if(eventType.equals("New Reply") || eventType.equals("New Discussion")) { StringList subscriberList = event.getSelectDataList(selEventSubscirbedPersonFromEvent); if(subscriberList != null && subscriberList.contains(contextUser)) { subscriptionICON = imgSrc; break; } } } } vSubscribed.addElement(subscriptionICON); } } catch(Exception ex) { throw ex; } return vSubscribed; } /** * getSubscribedDiscussionList - gets the list of subscribed discussion objects * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @return Object * @throws Exception if the operation fails * @since AEF V11 * @grade 0 */ @com.matrixone.apps.framework.ui.ProgramCallable public Object getSubscribedDiscussionList(Context context, String[] args) throws Exception { MapList subscribedMsgList = new MapList(); StringBuffer whereCond = new StringBuffer(); whereCond.append("attribute["); whereCond.append(ATTRIBUTE_EVENT_TYPE); whereCond.append("] == 'New Reply' || attribute["); whereCond.append(ATTRIBUTE_EVENT_TYPE); whereCond.append("] == 'New Discussion'"); String strOutput = MqlUtil.mqlCommand(context,"expand bus $1 $2 $3 to relationship $4 type $5 select bus $6 where $7 dump $8", "Person", context.getUser(), "-", RELATIONSHIP_SUBSCRIBED_PERSON, TYPE_EVENT, "id", whereCond.toString(), "|"); StringTokenizer strLineToken = new StringTokenizer(strOutput,"\n"); String strRecToken =""; String objIds[] = new String[strLineToken.countTokens()]; ArrayList objList = new ArrayList(); int i=0; while(strLineToken.hasMoreTokens()) { strRecToken = strLineToken.nextToken(); strRecToken = strRecToken.substring(strRecToken.lastIndexOf("|")+1,strRecToken.length()); objIds[i] = strRecToken; objList.add(strRecToken); i++; } StringBuffer selectBuf = new StringBuffer(); selectBuf.append("to[").append(RELATIONSHIP_PUBLISH).append("].from.to[").append(RELATIONSHIP_PUBLISH_SUBSCRIBE).append("].businessobject."); StringList selectList = new StringList(); selectList.add(selectBuf.toString() + "id"); selectList.add(selectBuf.toString() + "type"); selectList.add(selectBuf.toString() + "policy"); BusinessObjectWithSelectList bosWithSelect = BusinessObject.getSelectBusinessObjectData(context, objIds, selectList); for(int j=0;j<bosWithSelect.size();j++) { BusinessObjectWithSelect bows = bosWithSelect.getElement(j); String id = bows.getSelectData((String)selectList.elementAt(0)); String type = bows.getSelectData((String)selectList.elementAt(1)); String policy = bows.getSelectData((String)selectList.elementAt(2)); if (type == null || id == null || policy == null || "".equals(type) || "".equals(id) || "".equals(policy)) { continue; } if(TYPE_MESSAGE.equals(type)) { HashMap messageMap = new HashMap(); messageMap.put(SELECT_ID, id); messageMap.put(SELECT_POLICY, policy); subscribedMsgList.add(messageMap); } else { DomainObject bs = new DomainObject(id); SelectList selects = new SelectList(); selects.addId(); selects.addPolicy(); MapList discussions = bs.getRelatedObjects(context, RELATIONSHIP_THREAD + "," + RELATIONSHIP_MESSAGE, TYPE_MESSAGE, selects, null, false, true, (short)-1, null, null, 0, null, null, null); for(int k=0; k<discussions.size(); k++) { Map objInfo = (Map)discussions.get(k); String objId = (String)objInfo.get(SELECT_ID); if (objId != null && !objList.contains(objId)) { HashMap messageMap = new HashMap(); messageMap.put(SELECT_ID, objId); messageMap.put(SELECT_POLICY, objInfo.get(SELECT_POLICY)); subscribedMsgList.add(messageMap); } } } } return subscribedMsgList; } /** * getLast30DaysDiscussions - gets the list of subscribed discussion objects * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF V11 * @grade 0 */ @com.matrixone.apps.framework.ui.ProgramCallable public Object getLast30DaysDiscussions(Context context,String[] args) throws Exception { MapList objectList= new MapList(); try { StringBuffer whereExp = new StringBuffer(); java.text.SimpleDateFormat mxDateFrmt = new java.text.SimpleDateFormat (eMatrixDateFormat.getEMatrixDateFormat()); java.util.GregorianCalendar gc = new java.util.GregorianCalendar(); String currDate = mxDateFrmt.format(gc.getTime()); String toDate=""; gc.add(java.util.GregorianCalendar.DAY_OF_YEAR,-30); toDate = mxDateFrmt.format(gc.getTime()); String selRootObjId = new StringBuffer().append("to[").append(PropertyUtil.getSchemaProperty(context,"relationship_Message")). append("].from.to[").append(PropertyUtil.getSchemaProperty(context,"relationship_Thread")).append("]").toString(); whereExp.append("modified >='"); whereExp.append(toDate); // whereExp.append("' and modified <='"); // whereExp.append(currDate); whereExp.append("' and to["); whereExp.append(PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_Message)); whereExp.append("]=='True'"); whereExp.append("and "+selRootObjId+"=='True'"); objectList = (MapList)getFilteredDiscussionList(context,whereExp.toString()); } catch(Exception ex) { throw ex; } return objectList; } /** * getLast90DaysDiscussions - gets the list of subscribed discussion objects * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @return Object * @throws Exception if the operation fails * @since AEF V11 * @grade 0 */ @com.matrixone.apps.framework.ui.ProgramCallable public Object getLast90DaysDiscussions(Context context,String[] args) throws Exception { MapList objectList = new MapList(); try { StringBuffer whereExp = new StringBuffer(); java.text.SimpleDateFormat mxDateFrmt = new java.text.SimpleDateFormat (eMatrixDateFormat.getEMatrixDateFormat()); java.util.GregorianCalendar gc = new java.util.GregorianCalendar(); String currDate = mxDateFrmt.format(gc.getTime()); String toDate=""; gc.add(java.util.GregorianCalendar.DAY_OF_YEAR,-90); toDate = mxDateFrmt.format(gc.getTime()); String selRootObjId = new StringBuffer().append("to[").append(PropertyUtil.getSchemaProperty(context,"relationship_Message")). append("].from.to[").append(PropertyUtil.getSchemaProperty(context,"relationship_Thread")).append("]").toString(); whereExp.append("modified >='"); whereExp.append(toDate); // whereExp.append("' and modified <='"); // whereExp.append(currDate); whereExp.append("' and to["); whereExp.append(PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_Message)); whereExp.append("]=='True'"); whereExp.append("and "+selRootObjId+"=='True'"); objectList = (MapList)getFilteredDiscussionList(context,whereExp.toString()); } catch(Exception ex) { throw ex; } return objectList; } /** * getMessageType - gets policy of the message and decides whether the message is public or private * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public static Vector getMessageType(Context context,String [] args) throws Exception { Vector vMessageTypeVec = new Vector(); try { HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); String lang = context.getSession().getLanguage(); for (Iterator iter = objectList.iterator(); iter.hasNext();) { Map discusion = (Map) iter.next(); String policy = (String) discusion.get(SELECT_POLICY); policy = policy == null ? MqlUtil.mqlCommand(context, "print bus $1 select $2 dump", (String)discusion.get(SELECT_ID), policy) : policy; vMessageTypeVec.addElement( EnoviaResourceBundle.getProperty(context,"emxComponentsStringResource",new Locale(lang),POLICY_MESSAGE.equals(policy) ? "emxComponents.Discussion.Public" : "emxComponents.Discussion.Private" )); } } catch(Exception ex) { throw ex; } return vMessageTypeVec; } /** * getLatestMessageOriginatedDate - gets the l * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public static Vector getLatestMessageOriginatedDate(Context context, String[] args) throws Exception { Vector vModifiedDateVec = new Vector(); try { Map objMap = null; String lastModifiedDate=""; String objId = ""; StringBuffer mqlString=null; StringList objectSelects = new StringList(); objectSelects.addElement(SELECT_ORIGINATED); HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Iterator objItr = objectList.iterator(); MapList leafNodeList = new MapList(); while(objItr.hasNext()) { objMap = (Map)objItr.next(); objId = (String)objMap.get(SELECT_ID); DomainObject messageObject = new DomainObject(objId); leafNodeList = messageObject.getRelatedObjects(context, DomainConstants.RELATIONSHIP_REPLY , DomainConstants.TYPE_MESSAGE, objectSelects, null, false, true, (short)0 , null, null, (short)0); leafNodeList.addSortKey(SELECT_ORIGINATED,"descending","date"); leafNodeList.sort(); if(leafNodeList.size()>0) { lastModifiedDate = (String)(((Map)leafNodeList.get(0)).get(SELECT_ORIGINATED)); vModifiedDateVec.addElement(lastModifiedDate); } else { lastModifiedDate = (String)messageObject.getInfo(context,SELECT_ORIGINATED); vModifiedDateVec.addElement(lastModifiedDate); } } } catch(Exception ex) { throw ex; } return vModifiedDateVec; } /** * getReplyCountForDiscussion - gets the No.of replies given for each discussion * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public Vector getReplyCountForDiscussion(Context context,String args[]) throws Exception { Map objMap = null; String objId=""; String count = ""; Vector vReplyVec = new Vector(); try { HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Iterator objItr = objectList.iterator(); while(objItr.hasNext()) { objMap = (Map) objItr.next(); objId = (String) objMap.get(SELECT_ID); count = MqlUtil.mqlCommand(context, "eval expr $1 on expand bus $2 from rel $3 recurse to all", "count TRUE", objId, PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_Reply)); vReplyVec.addElement(count); } } catch(Exception ex) { throw ex; } return vReplyVec; } /** * showSubscribeCommand - Returns true if the selected filter is other than Subscribed. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @return boolean * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public boolean showSubscribeCommand(Context context,String[] args) throws Exception { HashMap programMap = (HashMap)JPO.unpackArgs(args); boolean showCommand = true; try { String selectedFilter = (String)programMap.get("selectedFilter"); if(selectedFilter!=null && !"null".equals(selectedFilter) && !"".equals(selectedFilter) && "emxDiscussion:getSubscribedDiscussionList".equals(selectedFilter)) { showCommand = false; } } catch(Exception ex) { throw ex; } return showCommand; } /** * showVisibilityColumn - Returns true if the user is a part of Private Discussion association. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList * @returns Object * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public boolean showVisibilityColumn(Context context, String[] args) throws Exception { return hasAccessToPrivateDiscussion(context, null); } /////////////////// My Discussions ///////////////////////////////////////////////////////////////// /** * isPrivateUser - returns true if user has the Autherity to * access Private Message else false. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - objectList MapList/ Object Id of parent * @returns boolean value * @throws Exception if the operation fails * @since AEF V11 * @grade 0 */ public boolean isPrivateUser(Context context,String args[]) throws Exception { String objectId = null; if(args.length > 1){ HashMap programMap = (HashMap) JPO.unpackArgs(args); objectId = (String) programMap.get("objectId"); } else{ objectId = args [0]; } return hasAccessToPrivateDiscussion(context, objectId); } private boolean hasAccessToPrivateDiscussion(Context context, String objectId) throws Exception, FrameworkException { com.matrixone.apps.common.Person person = (com.matrixone.apps.common.Person) DomainObject.newInstance(context, DomainConstants.TYPE_PERSON); person = (Person)newInstance(context, person.getPerson(context).getId(context)); String orgId = person.getInfo(context, "relationship["+RELATIONSHIP_EMPLOYEE+"].from.id"); String strHostCompanyId= Company.getHostCompany(context); Boolean hasAccessFlag = false; if(PersonUtil.getAssignments(context).contains(ROLE_EMPLOYEE)|| orgId.equals(strHostCompanyId)) { hasAccessFlag = true; } return hasAccessFlag; } /** * updateRootMessageObject - Updates the Root Messag Object Count attribute with the no.of child messages. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - ObjectId of the Created Reply * @return int * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public static int updateRootMessageObject (Context context, String args[])throws Exception { int updated=0; try { String objectId = args[0]; String parentObjId = args[1]; String rootMessageObjectId = emxMessageUtil_mxJPO.getRootMessageId(context,objectId); String strCount = MqlUtil.mqlCommand(context, "eval expr $1 on expand bus $2 from rel $3 recurse to all", "count TRUE", rootMessageObjectId, PropertyUtil.getSchemaProperty(context,SYMBOLIC_relationship_Reply)); DomainObject rootMsgobj = new DomainObject(rootMessageObjectId); rootMsgobj.setAttributeValue(context,ATTRIBUTE_COUNT,strCount); if(!rootMessageObjectId.equals(parentObjId)) { //set the value to immediate parent rootMsgobj.setId(parentObjId); int count; try { count = Integer.parseInt(rootMsgobj.getAttributeValue(context, ATTRIBUTE_COUNT)); } catch (NumberFormatException ex) { count = 0; } count++; rootMsgobj.setAttributeValue(context,ATTRIBUTE_COUNT,Integer.toString(count)); } } catch(Exception e) { updated=1; } return updated; } //2011x Team Wellness Plan feature /** * updateRootMessageObject - Updates the Root Messag Object Count attribute with the no.of child messages. * @param context the eMatrix <code>Context</code> object * @param args holds the following input arguments: * 0 - ObjectId of the Created Reply * @return int * @throws Exception if the operation fails * @since AEF 11-0 * @grade 0 */ public String getOwnedFilesRadiobuttons(Context context, String[] args) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<input type=\"radio\" name=\"ownedFiles\" id=\"ownedFiles\" value=\"true\" checked>&nbsp;&nbsp;"); sb.append(EnoviaResourceBundle.getProperty(context,"emxTeamCentralStringResource",new Locale(context.getSession().getLanguage()),"emxTeamCentral.FindFiles.FileIOwn")); sb.append("<br>"); sb.append("<input type=\"radio\" name=\"ownedFiles\" id=\"ownedFiles\" value=\"false\">&nbsp;&nbsp;"); sb.append(EnoviaResourceBundle.getProperty(context,"emxTeamCentralStringResource",new Locale(context.getSession().getLanguage()),"emxTeamCentral.FindFiles.AllFiles")); return sb.toString(); } /** * getWorkspaceSubfoldersCheckbox - Displays the workspace subfolders checkbox for find files search * @param context the eMatrix <code>Context</code> object * @return String * @throws Exception if the operation fails * @since R210 * @grade 0 */ public String getWorkspaceSubfoldersCheckbox(Context context, String[] args) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<input type=\"checkbox\" name=\"workspacesubfolders\" id=\"workspacesubfolders\" value=\"True\">&nbsp;&nbsp;"); sb.append(EnoviaResourceBundle.getProperty(context,"emxTeamCentralStringResource",new Locale(context.getSession().getLanguage()),"emxTeamCentral.FindFiles.IncludeSubFolders")); return sb.toString(); } /** * getDiscussionMatchcase - Displays the checkbox for Match case * @param context the eMatrix <code>Context</code> object * @return String * @throws Exception if the operation fails * @since R210 * @grade 0 */ public String getDiscussionMatchcase(Context context, String[] args) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<input type=\"text\" name=\"matchCase\" id=\"matchCase\" value=\"*\">&nbsp;&nbsp;"); sb.append("<input type=\"checkbox\" name=\"matchCase\" value=\"True\" id=\"matchCase\" checked>&nbsp;"); sb.append(EnoviaResourceBundle.getProperty(context,"emxTeamCentralStringResource",new Locale(context.getSession().getLanguage()),"emxTeamCentral.FindFiles.MatchCase")); return sb.toString(); } /** * showFilesWorkspaceName - Displays the workspace name to search files under * @param context the eMatrix <code>Context</code> object * @return Vector * @throws Exception if the operation fails * @since R210 * @grade 0 */ public Vector showFilesWorkspaceName(Context context, String[] args) throws Exception { Vector workspacenames = new Vector(); HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Iterator wrkspaceItr = objectList.iterator(); while(wrkspaceItr.hasNext()) { Map map = (Map)wrkspaceItr.next(); String strWorkspaceName = (String)map.get("workspaceNames"); workspacenames.add(XSSUtil.encodeForHTML(context, strWorkspaceName)); } return workspacenames; } /** * showFilesFolderName - Displays the folder under which the files are present * @param context the eMatrix <code>Context</code> object * @return Vector * @throws Exception if the operation fails * @since R210 * @grade 0 */ public Vector showFilesFolderName(Context context, String[] args) throws Exception { Vector foldernames = new Vector(); HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Iterator folderItr = objectList.iterator(); while(folderItr.hasNext()) { Map map = (Map)folderItr.next(); String strFolderName = (String)map.get("folder"); foldernames.add(XSSUtil.encodeForHTML(context, strFolderName)); } return foldernames; } /** * showFilesVersion - Displays the version of the files in search results * @param context the eMatrix <code>Context</code> object * @return Vector * @throws Exception if the operation fails * @since R210 * @grade 0 */ public Vector showFilesVersion(Context context, String[] args) throws Exception { Vector fileVersions = new Vector(); HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); Iterator versionItr = objectList.iterator(); while(versionItr.hasNext()) { Map map = (Map)versionItr.next(); String strFileVersion = (String)map.get("version"); fileVersions.add(XSSUtil.encodeForHTML(context, strFileVersion)); } return fileVersions; } /** * showDocFilesCheckbox - Displays the document files checkbox * @param context the eMatrix <code>Context</code> object * @return Vector * @throws Exception if the operation fails * @since R210 * @grade 0 */ public Vector showDocFilesCheckbox(Context context, String[] args) throws Exception { Vector docCheckboxes = new Vector(); HashMap programMap = (HashMap)JPO.unpackArgs(args); MapList objectList = (MapList)programMap.get("objectList"); HashMap requestMap = (HashMap)programMap.get("paramList"); String sSelectedObjId = (String)requestMap.get("objectId"); String sWorkspaceFolder = (String)requestMap.get("WorkspaceFolderDisplay"); String sWorkspaceFolderId = (String)requestMap.get("WorkspaceFolder"); String sTypeProjectVault = PropertyUtil.getSchemaProperty(context,"type_ProjectVault"); String sRelVaultedDocuments = PropertyUtil.getSchemaProperty(context,"relationship_VaultedDocuments"); String sTypeProject = PropertyUtil.getSchemaProperty(context,"type_Project"); String sRelProjectVaults = PropertyUtil.getSchemaProperty(context,"relationship_ProjectVaults"); String strRouteType = PropertyUtil.getSchemaProperty(context, "type_Route"); String sRelObjRou = PropertyUtil.getSchemaProperty(context, "relationship_ObjectRoute"); String sRelRouteScope = PropertyUtil.getSchemaProperty(context,"relationship_RouteScope"); String DocumentsinMultipleRoutes = EnoviaResourceBundle.getProperty(context,"emxTeamCentral.DocumentsinMultipleRoutes"); String canRouteCheckoutDocuments = EnoviaResourceBundle.getProperty(context,"emxTeamCentral.CanRouteCheckoutDocuments"); DomainObject fromObject = DomainObject.newInstance(context); StringList connectedFileList = new StringList(); if(sWorkspaceFolder == null ){ sWorkspaceFolder = ""; } if( sSelectedObjId != null && (!sSelectedObjId.equals(""))){ fromObject.setId(sSelectedObjId); } if(sWorkspaceFolderId==null || sWorkspaceFolderId.equals("*")){ sWorkspaceFolderId=""; } String contentFromType = fromObject.getInfo(context, fromObject.SELECT_TYPE); String routeScopeId = ""; boolean bfromMeetorDis = false; DomainObject scopeObject = DomainObject.newInstance(context); if(strRouteType.equals(contentFromType)) { sWorkspaceFolder = ""; //sWorkspaceFolderId = ""; routeScopeId = fromObject.getInfo(context, "to["+sRelRouteScope+"].from.id"); scopeObject.setId(routeScopeId); if(sTypeProject.equals((scopeObject.getInfo(context, fromObject.SELECT_TYPE)))) { // build the list of folders if(sWorkspaceFolderId.equals("")){ StringList folderList = scopeObject.getInfoList(context, "from["+sRelProjectVaults+"].to.id"); Iterator folderItr = folderList.iterator(); while(folderItr.hasNext()) { sWorkspaceFolderId = sWorkspaceFolderId + folderItr.next() + ","; } } } else { sWorkspaceFolderId = routeScopeId + ","; } connectedFileList = fromObject.getInfoList(context, "to["+sRelObjRou+"].from.attribute["+DomainObject.ATTRIBUTE_TITLE+"]"); } else if((sTypeProject.equals(contentFromType) || sTypeProjectVault.equals(contentFromType))) { sWorkspaceFolder = ""; sWorkspaceFolderId = ""; if(sTypeProject.equals(contentFromType)) { scopeObject.setId(sSelectedObjId); StringList folderList = scopeObject.getInfoList(context, "from["+sRelProjectVaults+"].to.id"); Iterator folderItr = folderList.iterator(); while(folderItr.hasNext()) { sWorkspaceFolderId = sWorkspaceFolderId + folderItr.next() + ","; } } else { sWorkspaceFolderId = sSelectedObjId + ","; } } else if(sTypeProjectVault.equals(contentFromType)) { connectedFileList = fromObject.getInfoList(context, "from["+sRelVaultedDocuments+"].to.attribute["+DomainObject.ATTRIBUTE_TITLE+"]"); } else if((fromObject.TYPE_MEETING).equals(contentFromType)) { bfromMeetorDis = true; connectedFileList = fromObject.getInfoList(context, "from["+fromObject.RELATIONSHIP_MEETING_ATTACHMENTS+"].to.attribute["+DomainObject.ATTRIBUTE_TITLE+"]"); } else if((fromObject.TYPE_MESSAGE).equals(contentFromType)) { bfromMeetorDis = true; connectedFileList = fromObject.getInfoList(context, "from["+fromObject.RELATIONSHIP_MESSAGE_ATTACHMENTS+"].to.attribute["+DomainObject.ATTRIBUTE_TITLE+"]"); } Iterator itr = objectList.iterator(); while(itr.hasNext()) { Map map = (Map)itr.next(); String sObjName = (String)map.get("name"); String toConnAccess = (String)map.get("toConnectAccess"); String inRoute = (String)map.get("inRoute"); String sConnected = ""; if(connectedFileList != null && connectedFileList.contains(sObjName)){ sConnected = "true"; } String sLocked = (String)map.get("lock"); if(contentFromType.equals(sTypeProjectVault)){ if ((sLocked.equals("true")) || "true".equals(sConnected)) { docCheckboxes.add("false"); } else { docCheckboxes.add("true"); } }else if(contentFromType.equals(DomainObject.TYPE_MESSAGE)){ if("FALSE".equals(toConnAccess) || "true".equals(sConnected)){ docCheckboxes.add("false"); }else{ docCheckboxes.add("true"); } }else{ if (DocumentsinMultipleRoutes.equals("false") && canRouteCheckoutDocuments.equals("false") ) { if(inRoute.equals("true") || sLocked.equals("true") || "true".equals(sConnected) ){ docCheckboxes.add("false"); }else{ docCheckboxes.add("true"); } } else if(DocumentsinMultipleRoutes.equals("false") && canRouteCheckoutDocuments.equals("true")) { if(inRoute.equals("true") || "true".equals(sConnected)){ docCheckboxes.add("false"); }else{ docCheckboxes.add("true"); } }else if(DocumentsinMultipleRoutes.equals("true") && canRouteCheckoutDocuments.equals("false")) { if( (sLocked.equals("false") && "false".equals(sConnected))){ docCheckboxes.add("false"); }else{ docCheckboxes.add("true"); } }else{ if (("true".equals(sConnected))) { docCheckboxes.add("false"); } else { docCheckboxes.add("true"); } } } if (inRoute.equals("true")) { if(sLocked.equals("true")) { docCheckboxes.add("false"); } else { docCheckboxes.add("true"); } } } return docCheckboxes; } /** * getFileType - Displays the file type and icon for discussion find files search form * @param context the eMatrix <code>Context</code> object * @return String * @throws Exception if the operation fails * @since R210 * @grade 0 */ public String getFileType(Context context, String[] args) throws Exception { StringBuffer sb = new StringBuffer(); sb.append("<img border=0 src=../teamcentral/images/iconFile.gif></img>&nbsp;"); sb.append(EnoviaResourceBundle.getProperty(context,"emxTeamCentralStringResource",new Locale(context.getSession().getLanguage()),"emxTeamCentral.FindFiles.File")); return sb.toString(); } /** * getDiscussionVisibility - Displays the visibility for discussion object either Public or Private * @param context the eMatrix <code>Context</code> object * @return String[] args containing parammap and requestmap * @throws Exception if the operation fails * @since R212 */ public String getDiscussionVisibility(Context context, String[] args) throws Exception { HashMap programMap = (HashMap)JPO.unpackArgs(args); HashMap paramMap = (HashMap)programMap.get("paramMap"); String languageStr = (String) paramMap.get("languageStr"); Map requestMap = (Map)programMap.get("requestMap"); String discType = (String)requestMap.get("DiscType"); discType = "Public".equals(discType) ? EnoviaResourceBundle.getProperty(context,"emxComponentsStringResource",new Locale(languageStr),"emxComponents.Discussion.Public") : "Private".equals(discType) ? EnoviaResourceBundle.getProperty(context,"emxComponentsStringResource",new Locale(languageStr),"emxComponents.Discussion.Private") : discType; return discType; } /** * getDiscussionSubjectValue - Displays the Subject for discussion object * @param context the eMatrix <code>Context</code> object * @return String[] args containing parammap and requestmap * @throws Exception if the operation fails * @since R212 */ public String getDiscussionSubjectValue(Context context, String[] args) throws Exception { HashMap programMap = (HashMap)JPO.unpackArgs(args); Map requestMap = (Map)programMap.get("requestMap"); String objectId = (String)requestMap.get("objectId"); String subject = ""; if(!UIUtil.isNullOrEmpty(objectId)) { Message message = (Message) DomainObject.newInstance(context,DomainConstants.TYPE_MESSAGE); message.setId(objectId); if(DomainConstants.TYPE_MESSAGE.equals(message.getInfo(context, DomainConstants.SELECT_TYPE))){ String existingSub = (String)message.getInfo(context, message.SELECT_MESSAGE_SUBJECT); if (existingSub != null && existingSub.startsWith("Re ")){ subject = existingSub; } else { subject += "Re "; subject += existingSub; } } } return subject; } public void setDiscussionSubject(Context context, String[] args) throws Exception { HashMap programMap = (HashMap)JPO.unpackArgs(args); Map requestMap = (Map)programMap.get("requestMap"); Map paramMap = (Map)programMap.get("paramMap"); String objectId = (String)paramMap.get("objectId"); String[] subject = ( String[]) requestMap.get("Subject"); DomainObject message = DomainObject.newInstance(context); message.setId(objectId); /* Temporarily fixed as part of IR-185089V6R2013x Whole function is to be removed but since we are using edit form update function is a must. Public and Private discussions creation to be migrated to create component to avoid the usage of update function and program. As this existing Update function is also a dummy function */ } @com.matrixone.apps.framework.ui.CreateProcessCallable public Map createDiscussionPostProcess(Context context, String[] args) throws Exception { HashMap programMap = (HashMap)JPO.unpackArgs(args); String strSubject = (String) programMap.get("Subject"); String strMessage = (String) programMap.get("Message"); String objectId = (String) programMap.get("objectId"); String visibility = (String) programMap.get("DiscType"); strSubject = FrameworkUtil.findAndReplace(strSubject, "\n", "<br />"); strMessage = FrameworkUtil.findAndReplace(strMessage, "\n", "<br />"); Message message = (Message) DomainObject.newInstance(context,DomainConstants.TYPE_MESSAGE); Route route = (Route)DomainObject.newInstance(context,Route.TYPE_ROUTE); DomainObject domainObject = DomainObject.newInstance(context,objectId); String strType = (String)domainObject.getInfo(context,domainObject.SELECT_TYPE); HashMap retMap = new HashMap(); //Depending on the Private and Public message visibility, corresponding create() method from the Message class should be called String strPrivate = "Private"; String strPublic = "Public"; if(visibility != null){ //Code to convert visibility from "Private Message"/"Public Message" if(visibility.contains(strPrivate)){ //Private message message.create(context, strSubject, strMessage,strPrivate,domainObject); } else{ //Public message message.create(context, strSubject, strMessage,strPublic,domainObject); } } else{ //Public message without visibility parameter message.create(context, strSubject, strMessage,domainObject); } retMap.put("id", message.getId()); return retMap; } }
hellozjf/JPO
emxDiscussionBase_mxJPO.java
248,618
package palsta.db; import java.sql.*; import java.util.*; import palsta.pojo.*; public class AlueDao implements Dao<Alue, Integer> { private Database database; private DateHelper dateHelper; private QueryMaker<Alue> query; private final String selectQueryStart = "" + "SELECT a.tunnus, a.web_tunnus, a.nimi," + " COUNT(v.tunnus) AS viesteja, MAX(v.pvm) AS viimeisin " + "FROM Alue a " + "LEFT JOIN Keskustelu k " + "ON a.tunnus = k.alue " + "LEFT JOIN Viesti v " + "ON k.tunnus = v.keskustelu "; public AlueDao(Database d) throws SQLException { this.database = d; this.dateHelper = new DateHelper(d.hasTimestampType()); Aluekeraaja keraaja = new Aluekeraaja(this.dateHelper); this.query = new QueryMaker<>(database.getConnection(), keraaja); } public int countDiscussions(Integer key) throws SQLException { return query.queryInteger("SELECT COUNT(*) FROM Keskustelu WHERE alue = ?", key); } public boolean nameExists(String nimi) throws SQLException { return query.queryInteger("SELECT COUNT(*) FROM Alue WHERE nimi = ?", nimi) > 0; } public int insert(String webTunnus, String nimi) throws SQLException { return query.insert("INSERT INTO Alue(web_tunnus, nimi) VALUES (?, ?)", webTunnus, nimi); } public Alue findOne(String webTunnus) throws SQLException { List<Alue> lista = query.queryAndCollect(selectQueryStart + "WHERE a.web_tunnus = ? " + "GROUP BY a.tunnus", webTunnus); if (lista.isEmpty()) { return null; } return lista.get(0); } @Override public Alue findOne(Integer key) throws SQLException { List<Alue> lista = query.queryAndCollect(selectQueryStart + "WHERE a.tunnus = ? " + "GROUP BY a.tunnus", key); if (lista.isEmpty()) { return null; } return lista.get(0); } @Override public List<Alue> findAll() throws SQLException { return query.queryAndCollect(selectQueryStart + "GROUP BY a.tunnus " + "ORDER BY a.nimi"); } }
mriekkinen/palsta
src/main/java/palsta/db/AlueDao.java
248,620
package Process.models; import java.util.Date; public class Pep { Integer pepNumber; Date startDate; Date endDate; Date votingStartDate; Date votingEndDate; Date alternateVotingStartDate; Date alternateVotingEndDate; Date alternateVotingResultsDate; Date discussionStartDate; Date discussionEndDate; Integer stateCounter; //private States [] states; //private Message [] messages; States[] states = new States[100]; public Message[] messages = new Message[10000]; public Pep(){ // this.votingStartDate = null; this.stateCounter = 0; for (int i=0; i< 100;i++){ states[i] = new States(); } for (int j=0; j< 10000;j++){ messages[j] = new Message(); } } public void destruct(){ for (int i=0; i< 100;i++){ states[i] = null; } for (int j=0; j< 10000;j++){ messages[j] = null; } } public void displayMessageClassifier(){ Boolean discussionOn = false; Boolean discussionStart = null; Boolean discussionEnd = null; Integer discussionMessageCounter = 0; for (int j=0; j< 10000;j++){ if(messages[j].getClassifier() == "Discussion") { if (discussionOn == true) { discussionMessageCounter++; } else { discussionOn = true; System.out.println(this.pepNumber + " Discussion start" + messages[j].getClassifierDate()); } } else { if(discussionMessageCounter>5) { System.out.println(this.pepNumber + " Discussion start" + messages[j].getClassifierDate()); } discussionMessageCounter=0; discussionOn = false; } // do nothing //if !=discussion //next //see last //if last = discussion and tis discussion //do nothing //if last != discussion and this = discussion // set it tp start dis } } public void addState(String v_state, String v_date){ states[this.stateCounter].setState(v_state); states[this.stateCounter].setDate(v_date); this.stateCounter++; } public String outputStates(){ String add = null; for (int i=0; i< stateCounter;i++){ System.out.println("\n " + pepNumber + states[i].getState() + " " + states[i].getDate() ); add += "\n " + pepNumber + states[i].getState() + " " + states[i].getDate() ; } return add; } public void setPepNumber(Integer v_pepNumber) { this.pepNumber = v_pepNumber; } public int getPepNumber() { return this.pepNumber; } public Boolean setvotingStartDate(Date v_votingStartDate) { if (this.votingStartDate == null) { this.votingStartDate = v_votingStartDate; return true; //return boolean to indicate first voting instance and therefore output } if (v_votingStartDate.before(this.votingStartDate)){ this.votingStartDate = v_votingStartDate; } return false; // System.out.println("-------------------------added voting start date " + this.votingStartDate); } public void setvotingEndDate(Date v_votingEndDate) { if (this.votingEndDate == null) this.votingEndDate = v_votingEndDate; if (v_votingEndDate.after(this.votingEndDate)) this.votingEndDate = v_votingEndDate; // System.out.println("-------------------------added voting end date " + this.votingEndDate); } public void setalternateVotingStartDate(Date v_alternateVotingStartDate) { if (this.alternateVotingStartDate == null) this.alternateVotingStartDate = v_alternateVotingStartDate; if (v_alternateVotingStartDate.before(this.votingStartDate)){ this.alternateVotingStartDate = v_alternateVotingStartDate; } System.out.println("-------------------------added alternate voting start date " + this.alternateVotingStartDate); } public void setalternateVotingEndDate(Date v_alternateVotingEndDate) { if (this.alternateVotingEndDate == null) this.alternateVotingEndDate = v_alternateVotingEndDate; if (v_alternateVotingEndDate.after(this.votingEndDate)) this.alternateVotingEndDate = v_alternateVotingEndDate; System.out.println("-------------------------added alternate voting end date " + this.alternateVotingEndDate); } public void setalternateVotingResultsDate(Date v_alternateVotingResultsDate) { if (this.alternateVotingResultsDate == null) this.alternateVotingResultsDate = v_alternateVotingResultsDate; if (v_alternateVotingResultsDate.after(this.alternateVotingResultsDate)) this.alternateVotingResultsDate = v_alternateVotingResultsDate; } public void setdiscussionStartDate(Date v_discussionStartDate) { this.discussionStartDate = v_discussionStartDate; } public void setdiscussionEndDate(Date v_discussionEndDate) { this.discussionEndDate = discussionEndDate; } public Date getalternateVotingStartDate(){ return alternateVotingStartDate; } public Date getalternateVotingEndDate(){ return alternateVotingEndDate; } public Date getVotingStartDate(){ return votingStartDate; } public Date getVotingEndDate(){ return votingEndDate; } public Date getDiscussionStartDate(){ return discussionStartDate; } public Date getDiscussionEndDate(){ return discussionEndDate; } public Date getAlternativeVoteResultsDate(){ return alternateVotingResultsDate; } public String getState(Integer index){ return states[index].getState(); } public String getDate(Integer index){ return states[index].getDate(); } class PepIterator { private int messageIndex = 0; public boolean hasMoreMessages () { return messageIndex < messages.length; } public Object nextMessage () { return !hasMoreMessages () ? null : messages [messageIndex++]; } } }
sharmapn/DeMapMiner
src/process/models/Pep.java
248,621
package com.company; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /* selon le type de feature activé des commandes supplémentaires seront accessibles. si la feature n'est pas activée et que la commande est appelée alors il y aura un message d'erreur Command List : create_user user_name create user with name user_name add_friend user_name friend_name user_name add friend friend_name to user user_name send_message user_name1 user_name2 "message" send a from user_name1 to user_name2 create_call [ui]* create call with optional users name activate_feature feature_name activate the feature_name (Call,Mute,Message_muter,Call_muter) mute_calls user_name mute the calls for this user_name unmute_calls user_name unmute the calls for this user_name mute_messages user_name mute messages for user_name unmute_messages user_name mute messages for user_name exit end and close app // if the message send is the first we should create a new discussion, if not just add the message to the discussion */ public static List<User> users; public static List<Discussion> discussions; public static List<Call> calls; //features public static boolean hasCall=false; public static boolean hasMute=false; public static boolean hasCallMuter=false; public static boolean hasMessageMuter=false; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); users = new ArrayList<>(); discussions = new ArrayList<>(); calls = new ArrayList<>(); while(true) { System.out.print("Enter a command: "); String input = scanner.nextLine(); // send_message user_name1 user_name2 "message" : send a from user_name1 to user_name2 if (input.startsWith("send_message")) { sendMessage(input); } //exit and close else if (input.startsWith("exit")) { break; } // create_user user_name : create user with name user_name else if (input.startsWith("create_user")) { createUser(input); } // activate_feature feature_name : activate the feature_name (Call,Mute,Message_muter,Call_muter) else if (input.startsWith("activate_feature")) { activateFeature(input); } // create_call [ui]*: create call with optional users name else if (input.startsWith("create_call")) { //check if feature is enabled if(hasCall){ createCall(input); } else{ System.out.println("Invalid command : The Call feature is not activated"); } } //mute_calls user_name : mute the calls for this user_name else if (input.startsWith("mute_calls")) { //check if feature is enabled if(hasCallMuter){ muteCall(input); } else{ System.out.println("Invalid command : The Call muter feature is not activated"); } } //unmute_calls user_name : unmute the calls for this user_name else if (input.startsWith("unmute_calls")) { //check if feature is enabled if(hasCallMuter){ unmuteCall(input); } else{ System.out.println("Invalid command : The Call muter feature is not activated"); } } //mute_messages user_name : mute messages for user_name else if(input.startsWith("mute_messages")){ //check if feature is enabled if(hasMessageMuter){ muteMessage(input); } else{ System.out.println("Invalid command : The Message muter feature is not activated"); } } //unmute_messages user_name : mute messages for user_name else if (input.startsWith("unmute_messages")) { //check if feature is enabled if(hasMessageMuter){ unmuteMessage(input); } else{ System.out.println("Invalid command : The Message muter feature is not activated"); } } else { System.out.println("Invalid command"); } } scanner.close(); } //mute_messages user_name : mute messages for user_name public static void muteMessage(String input){ Pattern pattern = Pattern.compile("mute_messages\\s+(\\w+)"); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { String user_name = matcher.group(1); for (Call c: calls) { c.usersMessagesMute.add(user_name); } } else { System.out.println("Invalid command"); } } //unmute_messages user_name : mute messages for user_name public static void unmuteMessage(String input){ Pattern pattern = Pattern.compile("unmute_messages\\s+(\\w+)"); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { String user_name = matcher.group(1); for (Call c: calls) { c.usersMessagesMute.remove(user_name); } } else { System.out.println("Invalid command"); } } //mute_calls user_name : mute the calls for this user_name public static void muteCall(String input){ Pattern pattern = Pattern.compile("mute_calls\\s+(\\w+)"); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { String user_name = matcher.group(1); for (Call c: calls) { c.usersCallMute.add(user_name); } } else { System.out.println("Invalid command"); } } public static void unmuteCall(String input){ Pattern pattern = Pattern.compile("unmute_calls\\s+(\\w+)"); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { String user_name = matcher.group(1); for (Call c: calls) { c.usersCallMute.remove(user_name); } } else { System.out.println("Invalid command"); } } // activate_feature feature_name : activate the feature_name (Call,Mute,Message_muter,Call_muter) public static void activateFeature(String input){ Pattern pattern = Pattern.compile("activate_feature\\s+(\\w+)"); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { String feature_name = matcher.group(1); if(feature_name.equals("Call")){hasCall=true;} if(feature_name.equals("Mute")){hasMute=true;} if(feature_name.equals("Message_muter")){hasMessageMuter=true;} if(feature_name.equals("Call_muter")){hasCallMuter=true;} } else { System.out.println("Invalid command"); } } public static void createCall(String input){ Pattern pattern = Pattern.compile( "create_call(?:\\s+\\w+)*"); Matcher matcher = pattern.matcher(input); String[] users_in_call = new String[0]; if (matcher.find()) { String usersString = matcher.group(1); users_in_call = usersString.split("\\s+"); Call new_call = new Call(hasMute,hasCallMuter,hasMessageMuter); new_call.users.addAll(Arrays.asList(users_in_call)); calls.add(new_call); } else { System.out.println("Invalid command"); } } // create_user user_name : create user with name user_name public static void createUser(String input){ Pattern pattern = Pattern.compile("create_user\\s+(\\w+)"); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { String name = matcher.group(1); // Check if the name is unique boolean isUnique = users.stream().noneMatch(user -> user.getName().equals(name)); if (isUnique) { User newUser = new User(name); users.add(newUser); System.out.println("New user added: " + name); } else { System.out.println("User with the same name already exists."); } } else { System.out.println("Invalid create_user command format. It should be: create_user user_name"); } } //send_message user_name1 user_name2 message : send a from user_name1 to user_name2 public static void sendMessage(String input) { Pattern pattern = Pattern.compile("send_message\\s+(\\w+)\\s+(\\w+)\\s+\"([^\"]+)\""); Matcher matcher = pattern.matcher(input); boolean d_exist = false; if (matcher.matches()) { String user1 = matcher.group(1); String user2 = matcher.group(2); String message = matcher.group(3); // check if user1 or user2 dont exist boolean u1_exist = false; boolean u2_exist = false; for (User user: users) { if (user1.equals(user.name)) u1_exist = true; if (user2.equals(user.name)) u2_exist = true; } if(!u1_exist) System.out.println("user " + user1 + " does not exist"); if(!u2_exist) System.out.println("user " + user2 + " does not exist"); // create message Message m = new Message(); // m.date= new Date(); m.content = message; //check if the discussion between the two user already exists //TODO for the moment here a discussion can have only two user //TODO verifiy if the contains correctly checks if the discussion exists and contain the users /* for (Discussion discussion: discussions) { if (discussion.users_name.size()!=2 || !discussion.users_name.contains(user1) || !discussion.users_name.contains(user2)){ d_exist = true; //discusison already exist discussion.messages.put(m,m.date); } } if(!d_exist){ //discussion dont exist, we must create it Discussion discussion = new Discussion(); discussion.discussion(user1,user2); discussion.messages.put(m,m.date); discussions.add(discussion); } */ System.out.println("Sending from: " + user1 + " to: " + user2 + " with message: " + message); } else { System.out.println("Invalid send command format, must look like : send_message user_name1 user_name2 \"message\" "); } } public static User getUserByName(String name) { for (User user : users) { if (user.getName().equals(name)) { return user; } } return null; } /* public static Discussion findDiscussionByUsers(String user1, String user2) { for (Discussion discussion : discussions) { List<String> users = discussion.getUsers(); if (users.contains(user1) && users.contains(user2)) { return discussion; } } return null; }*/ }
Darmok72/LINGI2252-Smart_message_system
src/com/company/Main.java
248,622
public class PowerOfTwo { public boolean isPowerOfTwo(int n) { char[] chars = Integer.toString(n,2).toCharArray(); int count = 0; for (char value: chars) { if (value == '1') count++; } return n > 0 && count <= 1; } public boolean isPowerOfTwo_fromDiscussions(int n) { return n > 0 && ((n & (n-1)) == 0); } }
aTan-aka-Xellos/leetcode
june_challange/src/PowerOfTwo.java
248,623
package java2e.appendixa.set8; class Q2 { public static void main(String[] args) { System.out.println("***Set8.Q2***"); System.out.println("***Discussions on Switch ***"); int myNumber = 6; switch (myNumber) { case 1:case 5: System.out.println("One or Five"); break; default: System.out.println("Default"); break; case 2:case 6:case 8: System.out.println("Two or Six or Eight"); break; } } }
Apress/interactive-object-oriented-programming-java-2e
appendixa/set8/Q2.java
248,624
package java2e.appendixa.set8; class Q3 { public static void main(String[] args) { System.out.println("***Set8.Q3***"); System.out.println("***Discussions on Switch ***"); char myChoice = 'e'; switch (myChoice) { case 'b': System.out.println("b"); break; default: System.out.println("Default"); break; case 'a': System.out.println("a"); break; } } }
Apress/interactive-object-oriented-programming-java-2e
appendixa/set8/Q3.java
248,625
package java2e.appendixa.set8; class Q4 { public static void main(String[] args) { System.out.println("***Set8.Q4***"); System.out.println("***Discussions on Switch ***"); boolean value = true; /* switch (value) // compile-time error { case true: System.out.println("true"); break; case false: System.out.println("false"); break; default: System.out.println("Default"); break; } */ } }
Apress/interactive-object-oriented-programming-java-2e
appendixa/set8/Q4.java
248,626
package tethys.pamdata; import org.w3c.dom.Document; /** * object for a Tethys Schema. This may just be a very simple * wrapper around an XML string, or a JAXB object or something, * but may get more sophisticated. TBD in discussions with SDSU */ @Deprecated public class TethysSchema { private Document schemaDoc; public TethysSchema(Document doc) { this.setXsd(doc); } /** * @return the xsd */ public Document getXsd() { return schemaDoc; } /** * @param xsd the xsd to set */ public void setXsd(Document xsd) { this.schemaDoc = xsd; } }
PAMGuard/PAMGuard
src/tethys/pamdata/TethysSchema.java
248,627
/* * emxTeamDiscussionBase.java * * Copyright (c) 1992-2016 Dassault Systemes. * * All Rights Reserved. * This program contains proprietary and trade secret information of * MatrixOne, Inc. Copyright notice is precautionary only and does * not evidence any actual or intended publication of such program. * */ import com.matrixone.apps.common.Message; import com.matrixone.apps.common.Route ; import com.matrixone.apps.common.Workspace ; import com.matrixone.apps.common.WorkspaceVault; import com.matrixone.apps.common.Document ; import com.matrixone.apps.domain.DomainConstants; import com.matrixone.apps.domain.DomainObject; import com.matrixone.apps.domain.util.*; import com.matrixone.servlet.Framework; import com.matrixone.apps.common.Person ; import java.io.IOException; import java.io.PrintStream; import java.util.*; import matrix.db.*; import matrix.util.*; public class emxTeamDiscussionBase_mxJPO { /** * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments * @throws Exception if the operation fails * @since Team Central 10-7-0-0 next * @grade 0 */ public emxTeamDiscussionBase_mxJPO () throws Exception { } static final StringList EMPTY_STRING_LIST = new StringList(0).unmodifiableCopy(); /** * This method returns the Discussion in a Workspace/Folder/Project * * @param context the eMatrix <code>Context</code> object * @param args holds no arguments * @returns MapList containing discussions * @throws Exception if the operation fails * @since Team Central 10-7-0-0 next */ public MapList getDiscussions(Context context,String args[]) throws Exception { HashMap programMap = (HashMap)JPO.unpackArgs(args); String sLanguage = (String)context.getSession().getLanguage(); String objectId=(String)programMap.get("objectId"); String workspaceId = (String)programMap.get("workspaceId"); String folderId = (String)programMap.get("folderId"); String discussion = (String)programMap.get("discussion"); com.matrixone.apps.common.Person person = (com.matrixone.apps.common.Person) DomainObject.newInstance(context, DomainConstants.TYPE_PERSON); if(objectId != null && !"".equals(objectId)) { userIsAuthenticated(context,objectId , sLanguage); } Message message = (Message) DomainObject.newInstance(context,DomainConstants.TYPE_MESSAGE,DomainConstants.TEAM); DomainObject BaseObject = DomainObject.newInstance(context,objectId); String sReadAccess = "current.access[read]"; StringList baseObjectSelects = new StringList(); baseObjectSelects.addElement(BaseObject.SELECT_TYPE); baseObjectSelects.addElement(sReadAccess); Map baseMap = BaseObject.getInfo(context, baseObjectSelects); String strType = (String) baseMap.get(BaseObject.SELECT_TYPE); String sCurrentReadAccess = (String) baseMap.get(sReadAccess); if(strType.equals(BaseObject.TYPE_WORKSPACE)) { workspaceId = objectId; } String sDocument = PropertyUtil.getSchemaProperty(context, "type_Document"); String sFolder = PropertyUtil.getSchemaProperty(context, "type_ProjectVault"); String domainObjectId = null; StringList objectSelects = new StringList(); //MessageManager messagemgr = null; DomainObject baseObject = DomainObject.newInstance(context, objectId);; MapList discussionList = new MapList(); domainObjectId = objectId; if(sCurrentReadAccess.equalsIgnoreCase("TRUE")) { objectSelects.add(BaseObject.SELECT_ID); objectSelects.add(BaseObject.SELECT_RELATIONSHIP_ID); MapList totalresultList = null; totalresultList = message.list(context,objectSelects,null, null, baseObject); discussionList=totalresultList; objectSelects = new StringList(); objectSelects.add(Message.SELECT_MESSAGE_SUBJECT); objectSelects.add(BaseObject.SELECT_OWNER); objectSelects.add(BaseObject.SELECT_MODIFIED); objectSelects.add(BaseObject.SELECT_ID); objectSelects.add(Message.SELECT_MESSAGE_COUNT); objectSelects.add(sReadAccess); Iterator discussionIdItr = discussionList.iterator(); StringList disIdList = new StringList(); while(discussionIdItr.hasNext()) { Map disMap = (Map) discussionIdItr.next(); String disId = (String) disMap.get(BaseObject.SELECT_ID); if(!disIdList.contains(disId)) { disIdList.addElement(disId); } } discussionList = DomainObject.getInfo(context, (String [])disIdList.toArray(new String []{}), objectSelects); } return discussionList; } /** * This method verified whether the user is authenticated. * * @param context the eMatrix <code>Context</code> object * @param objectId holds the objectId * @returns nothing * @throws Exception if the operation fails * @since Team Central 10-7-0-0 next */ public void userIsAuthenticated(Context context, String objectId , String sLanguage) throws Exception { i18nNow loc = new i18nNow(); String hasReadAccess = null; try { DomainObject BaseObject = DomainObject.newInstance(context , objectId); BaseObject.setId(objectId); hasReadAccess = BaseObject.getInfo(context, "current.access[read,checkout]"); } catch(Exception e) { throw new MatrixException((String)loc.GetString("emxTeamCentralStringResource" ,"emxTeamCentral.Common.PageAccessDenied", sLanguage)); } if(!hasReadAccess.equals("TRUE")) { throw new MatrixException((String)loc.GetString("emxTeamCentralStringResource" ,"emxTeamCentral.Common.PageAccessDenied", sLanguage)); } } // End of class definition }
hellozjf/JPO
emxTeamDiscussionBase_mxJPO.java
248,628
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; public class App extends JFrame { protected static JLabel LABEL_ID; protected static JLabel LABEL_FIRSTNAME; protected static JLabel LABEL_LASTNAME; protected static JLabel LABEL_BIRTHDAY; protected static JLabel LABEL_HomeWorkScore; protected static JLabel LABEL_DiscussionScore; protected static JLabel LABEL_FrequentScore; protected static JLabel LABEL_FinalScore; protected static JLabel LABEL_MediumScore; public static JLabel LABEL_CHECK; public static JLabel LABEL_SHOWDATA; protected static JTextField ID; protected static JTextField FIRSTNAME; protected static JTextField LASTNAME; protected static JTextField BIRTHDAY; protected static JFormattedTextField HomeWorkScore; protected static JFormattedTextField DiscussionScore; protected static JFormattedTextField FinalScore; protected static JFormattedTextField FrequentScore; protected static JTextField MediumScore; protected static JTextArea ShowData = new JTextArea(10,10); protected static JTable TABLE = new JTable(); protected JScrollPane PANE; protected static JFormattedTextField Check_MediumScore; protected static DefaultTableModel AddData; protected static JFrame SCREEN = new JFrame("Quản lý sinh viên"); JScrollBar SCROLLBAR = new JScrollBar(JScrollBar.HORIZONTAL); protected static String PATH_TXT = "Data.txt"; static JDialog MESSENGER = new JDialog(App.SCREEN, "Messenger box"); static JDialog MESSENGER2 = new JDialog(App.SCREEN, "Messenger box"); protected static Object[] COLUMN = new String[]{ "ID","Firstname","Lastname","Birthday","HomeWorkScore", "DiscussionScore","FrequentScore","FinalScore","MediumScore" }; public App(){ JPanel panel = new JPanel(); LABEL_ID = new JLabel("Input ID : "); LABEL_ID.setBounds(10, 25, 100, 25); LABEL_ID.setForeground(Color.red); panel.add(LABEL_ID); ID = new JTextField("2342345345"); ID.setBounds(130,30,150,20); panel.add(ID); LABEL_FIRSTNAME = new JLabel("Input FirstName : "); LABEL_FIRSTNAME.setBounds(10, 55, 100, 25); LABEL_FIRSTNAME.setForeground(Color.red); panel.add(LABEL_FIRSTNAME); FIRSTNAME = new JTextField("Nguyễn Văn"); FIRSTNAME.setBounds(130, 60, 150, 20); panel.add(FIRSTNAME); LABEL_LASTNAME = new JLabel("Input LastName : "); LABEL_LASTNAME.setBounds(10, 85, 100, 25); LABEL_LASTNAME.setForeground(Color.red); panel.add(LABEL_LASTNAME); LASTNAME = new JTextField("A"); LASTNAME.setBounds(130, 90, 150, 20); panel.add(LASTNAME); LABEL_BIRTHDAY = new JLabel("Input Birthday : "); LABEL_BIRTHDAY.setBounds(10, 115, 100, 25); LABEL_BIRTHDAY.setForeground(Color.red); panel.add(LABEL_BIRTHDAY); BIRTHDAY = new JTextField("19/12/2022"); BIRTHDAY.setBounds(130, 120, 150, 20); panel.add(BIRTHDAY); LABEL_HomeWorkScore = new JLabel("Input HomeWorkScore : "); LABEL_HomeWorkScore.setBounds(10, 145, 100, 25); LABEL_HomeWorkScore.setForeground(Color.red); panel.add(LABEL_HomeWorkScore); HomeWorkScore = new JFormattedTextField(); HomeWorkScore.setValue(0); HomeWorkScore.setBounds(130, 150, 150, 20); panel.add(HomeWorkScore); LABEL_DiscussionScore = new JLabel("Input DiscussionScore : "); LABEL_DiscussionScore.setBounds(10, 175, 100, 25); LABEL_DiscussionScore.setForeground(Color.red); panel.add(LABEL_DiscussionScore); DiscussionScore = new JFormattedTextField(); DiscussionScore.setValue(0); DiscussionScore.setBounds(130, 180, 150, 20); panel.add(DiscussionScore); LABEL_FrequentScore = new JLabel("Input FrequentScore : "); LABEL_FrequentScore.setBounds(10, 205, 100, 25); LABEL_FrequentScore.setForeground(Color.red); panel.add(LABEL_FrequentScore); FrequentScore = new JFormattedTextField(); FrequentScore.setValue(0); FrequentScore.setBounds(130, 210, 150, 20); panel.add(FrequentScore); LABEL_FinalScore = new JLabel("Input FinalScore : "); LABEL_FinalScore.setBounds(10, 235, 100, 25); LABEL_FinalScore.setForeground(Color.red); panel.add(LABEL_FinalScore); FinalScore = new JFormattedTextField(); FinalScore.setValue(0); FinalScore.setBounds(130, 240, 150, 20); panel.add(FinalScore); LABEL_MediumScore = new JLabel("MediumScore is : "); LABEL_MediumScore.setBounds(10, 265, 100, 25); LABEL_MediumScore.setForeground(Color.red); panel.add(LABEL_MediumScore); MediumScore = new JTextField("Điểm trung bình"); MediumScore.setBounds(130, 270, 150, 20); panel.add(MediumScore); LABEL_CHECK = new JLabel("Check MediumScore"); LABEL_CHECK.setBounds(140, 420, 200, 25); LABEL_CHECK.setForeground(Color.red); panel.add(LABEL_CHECK); Check_MediumScore = new JFormattedTextField(); Check_MediumScore.setValue(0); Check_MediumScore.setBounds(130, 450, 150, 25); panel.add(Check_MediumScore); JScrollPane SCROLL = new JScrollPane(ShowData,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); SCROLL.setBounds(300, 500, 750, 150); SCREEN.getContentPane().add(SCROLL); JButton BUTTON = new JButton("ADD"); BUTTON.setBounds(150, 380, 100, 25); BUTTON.setForeground(Color.CYAN); BUTTON.setBackground(new Color(20, 50, 50)); ActionListener listener1 = new Handle_Button_Event_ADD(this); BUTTON.addActionListener(listener1); panel.add(BUTTON); JButton BUTTON_CLEAN = new JButton("DELETE"); BUTTON_CLEAN.setBounds(10, 380, 100, 25); BUTTON_CLEAN.setForeground(Color.CYAN); BUTTON_CLEAN.setBackground(new Color(20, 50, 50)); ActionListener listener_clean = new Handle_Button_Event_Clean(); BUTTON_CLEAN.addActionListener(listener_clean); panel.add(BUTTON_CLEAN); JButton BUTTON_CHECK = new JButton("CHECK"); BUTTON_CHECK.setBounds(10, 450, 100, 25); BUTTON_CHECK.setForeground(Color.CYAN); BUTTON_CHECK.setBackground(new Color(20, 50, 50)); ActionListener listener_check = new Handle_Button_Event_Check(); BUTTON_CHECK.addActionListener(listener_check); panel.add(BUTTON_CHECK); JButton BUTTON_WRITEFILE = new JButton("SAVE"); BUTTON_WRITEFILE.setBounds(10, 520, 100, 25); BUTTON_WRITEFILE.setForeground(Color.CYAN); BUTTON_WRITEFILE.setBackground(new Color(20, 50, 50)); ActionListener listener_WriteFile = new Handle_Button_Event_WriteFile(); BUTTON_WRITEFILE.addActionListener(listener_WriteFile); panel.add(BUTTON_WRITEFILE); JButton BUTTON_READFILE = new JButton("SHOW DATA"); BUTTON_READFILE.setBounds(130, 520, 150, 25); BUTTON_READFILE.setForeground(Color.CYAN); BUTTON_READFILE.setBackground(new Color(20, 50, 50)); ActionListener listener_ReadFile = new Handle_Button_Event_READFILE(); BUTTON_READFILE.addActionListener(listener_ReadFile); panel.add(BUTTON_READFILE); PANE = new JScrollPane(TABLE); PANE.setBounds(300,31,750,445); panel.add(PANE); panel.setLayout(null); AddData = (DefaultTableModel) TABLE.getModel(); AddData.setColumnIdentifiers(COLUMN); SCREEN.setSize(1100,710); SCREEN.add(panel); SCREEN.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SCREEN.setVisible(true); } public void show(){ System.out.println("*** Developer Clearlove7 ***"); } public static void main(String[] args){ new App(); } }
tuongclearlove7/WorkingJava
Sell_Project_Game/src/App.java
248,629
/***************************************************************************** * Copyright 2011-2012 INRIA * Copyright 2011-2012 Universidade Nova de Lisboa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ package swift.dc; import static sys.net.api.Networking.Networking; import static sys.utils.Threading.lock; import static sys.utils.Threading.unlock; import java.lang.management.LockInfo; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import swift.clocks.CausalityClock; import swift.clocks.ClockFactory; import swift.clocks.Timestamp; import swift.crdt.IntegerCRDT; import swift.crdt.core.CRDT; import swift.crdt.core.CRDTIdentifier; import swift.crdt.core.CRDTObjectUpdatesGroup; import swift.crdt.core.CRDTOperationDependencyPolicy; import swift.crdt.core.ManagedCRDT; import swift.dc.db.DCNodeDatabase; import swift.dc.db.StatsNodeDatabaseWrapper; import swift.proto.DHTExecCRDT; import swift.proto.DHTExecCRDTReply; import swift.proto.DHTGetCRDT; import swift.proto.DHTGetCRDTReply; import swift.proto.ObjectUpdatesInfo; import swift.proto.SwiftProtocolHandler; import swift.pubsub.DataServerPubSubService; import swift.pubsub.SurrogatePubSubService; import swift.pubsub.UpdateNotification; import swift.utils.FutureResultHandler; import sys.dht.DHT_Node; import sys.net.api.Endpoint; import sys.net.api.rpc.RpcEndpoint; import sys.net.api.rpc.RpcHandle; import sys.net.api.rpc.RpcMessage; import sys.scheduler.PeriodicTask; import sys.utils.Threading; /** * Class to maintain data in the server. * * @author preguica, smduarte */ final class DCDataServer { private static Logger logger = Logger.getLogger(DCDataServer.class.getName()); Map<CRDTIdentifier, LockInfo> locks; Map<String, Map<String, CRDTData<?>>> db; CausalityClock version; CausalityClock cltClock; String localSurrogateId; DCNodeDatabase dbServer; final int pruningInterval; Set<CRDTData<?>> modified; SurrogatePubSubService suPubSub; DataServerPubSubService dsPubSub; ExecutorService executor = Executors.newCachedThreadPool(); RpcEndpoint dhtEndpoint; DCSurrogate surrogate; CRDTIdentifier heartBeat = new CRDTIdentifier("heart", "beat"); DCDataServer(final DCSurrogate surrogate, Properties props, SurrogatePubSubService suPubSub, int dhtPort) { sys.dht.DHT_Node.DHT_PORT = dhtPort; this.surrogate = surrogate; this.localSurrogateId = surrogate.getId(); this.dsPubSub = new DataServerPubSubService(localSurrogateId, executor, surrogate); this.suPubSub = suPubSub; final String pruningIntervalString = props.getProperty(DCConstants.PRUNING_INTERVAL_PROPERTY); if (pruningIntervalString != null) { pruningInterval = Integer.valueOf(pruningIntervalString); } else { pruningInterval = DCConstants.DEFAULT_PRUNING_INTERVAL_MS; } final String notificationPeriodString = props.getProperty(DCConstants.NOTIFICATION_PERIOD_PROPERTY); final int notificationPeriodMillis; if (notificationPeriodString != null) { notificationPeriodMillis = Integer.valueOf(notificationPeriodString); } else { notificationPeriodMillis = DCConstants.DEFAULT_NOTIFICATION_PERIOD_MS; } initStore(); initData(props); initDHT(); if (logger.isLoggable(Level.INFO)) { logger.info("Data server ready..."); } dsPubSub.subscribe(heartBeat, suPubSub); new PeriodicTask(1.0, notificationPeriodMillis * 0.001) { public void run() { dsPubSub.publish(new UpdateNotification(surrogate.surrogateId, new ObjectUpdatesInfo(heartBeat), surrogate.getEstimatedDCVersionCopy())); } }; } /** * Start background thread that dumps to disk */ void initStore() { Thread t = new Thread() { public void run() { for (;;) { try { List<CRDTData<?>> list = null; synchronized (modified) { list = new ArrayList<CRDTData<?>>(modified); } Iterator<CRDTData<?>> it = list.iterator(); while (it.hasNext()) { CRDTData<?> obj = it.next(); lock(obj.id); try { synchronized (modified) { modified.remove(obj); } } finally { unlock(obj.id); } writeCRDTintoDB(obj); } logger.info("Flushed store to disk..."); Thread.sleep(DCConstants.SYNC_PERIOD); } catch (Exception e) { // do nothing } } } }; t.setDaemon(true); t.start(); } /** * Start DHT subsystem... */ @SuppressWarnings({ "unchecked", "rawtypes" }) void dhtRequest(Endpoint dst, final RpcMessage req, final FutureResultHandler rh) { dhtEndpoint.send(dst, req, new SwiftProtocolHandler() { public void onReceive(DHTExecCRDTReply reply) { rh.onResult(reply.getResult()); } public void onReceive(DHTGetCRDTReply reply) { rh.onResult(reply.getObject()); } }, 0); } @SuppressWarnings("unchecked") <V> V dhtRequest(Endpoint dst, final RpcMessage req) { final AtomicReference<Object> result = new AtomicReference<Object>(req); for (; result.get() == req;) { synchronized (result) { dhtEndpoint.send(dst, req, new SwiftProtocolHandler() { public void onReceive(DHTExecCRDTReply reply) { result.set(reply.getResult()); Threading.synchronizedNotifyAllOn(result); } public void onReceive(DHTGetCRDTReply reply) { result.set(reply.getObject()); Threading.synchronizedNotifyAllOn(result); } }, 0); Threading.waitOn(result, 100); } } return (V) result.get(); } void initDHT() { dhtEndpoint = Networking.rpcConnect().toDefaultService(); Networking.rpcBind(DHT_Node.DHT_PORT).toService(0, new SwiftProtocolHandler() { public void onReceive(RpcHandle con, DHTGetCRDT request) { if (logger.isLoggable(Level.INFO)) { logger.info("DHT data server: get CRDT : " + request.getId()); } con.reply(new DHTGetCRDTReply(localGetCRDTObject(con.remoteEndpoint(), request))); } public void onReceive(RpcHandle con, DHTExecCRDT request) { if (logger.isLoggable(Level.INFO)) { logger.info("DHT data server: exec CRDT : " + request.getGrp().getTargetUID()); } con.reply(new DHTExecCRDTReply(localExecCRDT(request.getGrp(), request.getSnapshotVersion(), request.getTrxVersion(), request.getTxTs(), request.getCltTs(), request.getPrvCltTs(), request.getCurDCVersion()))); } }); } private void initData(Properties props) { this.db = new HashMap<String, Map<String, CRDTData<?>>>(); this.locks = new HashMap<CRDTIdentifier, LockInfo>(); // this.notifications = new LinkedList<NotificationRecord>(); this.modified = new HashSet<CRDTData<?>>(); this.version = ClockFactory.newClock(); this.cltClock = ClockFactory.newClock(); initDB(props); if (dbServer.ramOnly()) { CRDTIdentifier id = new CRDTIdentifier("e", "1"); ManagedCRDT<IntegerCRDT> i = new ManagedCRDT<IntegerCRDT>(id, new IntegerCRDT(id), version.clone(), true); localPutCRDT(i); CRDTIdentifier id2 = new CRDTIdentifier("e", "2"); ManagedCRDT<IntegerCRDT> i2 = new ManagedCRDT<IntegerCRDT>(id2, new IntegerCRDT(id2), version.clone(), true); localPutCRDT(i2); } } /********************************************************************************************** * DATABASE FUNCTIONS *********************************************************************************************/ void initDB(Properties props) { try { final DCNodeDatabase realDbServer = (DCNodeDatabase) Class.forName( props.getProperty(DCConstants.DATABASE_CLASS)).newInstance(); dbServer = new StatsNodeDatabaseWrapper(realDbServer, surrogate.siteId); } catch (Exception e) { throw new RuntimeException("Cannot start underlying database", e); } dbServer.init(props); } CRDTData<?> readCRDTFromDB(CRDTIdentifier id) { return (CRDTData<?>) dbServer.read(id); } void writeCRDTintoDB(CRDTData<?> data) { lock(data.id); try { dbServer.write(data.id, data); } finally { unlock(data.id); } } /** * Returns database entry. If create, creates a new empty database entry. It * assumes that the given entry has been locked. * * @param table * @param key * @param create * @return */ CRDTData<?> getDatabaseEntry(CRDTIdentifier id) { // TODO: this synchronization could be replaced with an optimistic // multiton pattern + ConcurrentHashMap.putIfAbsent Map<String, CRDTData<?>> m; synchronized (db) { m = db.get(id.getTable()); if (m == null) { m = new HashMap<String, CRDTData<?>>(); db.put(id.getTable(), m); } } CRDTData<?> data = null; synchronized (m) { data = (CRDTData<?>) m.get(id.getKey()); if (data != null) return data; } data = readCRDTFromDB(id); synchronized (m) { if (data == null) data = new CRDTData(id); m.put(id.getKey(), data); return data; } } private void setModifiedDatabaseEntry(CRDTData<?> crdt) { synchronized (modified) { modified.add(crdt); } } Endpoint resolve(CRDTIdentifier id) { return DHT_Node.resolveKey(id.toString()); } /** * Executes operations in the given CRDT * * @return returns true if the operation could be executed. */ <V extends CRDT<V>> ExecCRDTResult execCRDT(CRDTObjectUpdatesGroup<V> grp, CausalityClock snapshotVersion, CausalityClock trxVersion, Timestamp txTs, Timestamp cltTs, Timestamp prvCltTs, CausalityClock curDCVersion) { Endpoint dst = DHT_Node.resolveKey(grp.getTargetUID().toString()); if (dst == null) return localExecCRDT(grp, snapshotVersion, trxVersion, txTs, cltTs, prvCltTs, curDCVersion); else { return dhtRequest(dst, new DHTExecCRDT(grp, snapshotVersion, trxVersion, txTs, cltTs, prvCltTs, curDCVersion)); } } /** * Return null if CRDT does not exist * * If clock equals to null, just return full CRDT * * @param subscribe * Subscription type * @return null if cannot fulfill request */ void getCRDT(final CRDTIdentifier id, CausalityClock knownClk, CausalityClock clk, String clientId, boolean sendMoreRecentUpdates, boolean isSubscribed, FutureResultHandler<ManagedCRDT> rh) { Endpoint dst = DHT_Node.resolveKey(id.toString()); if (dst == null) { rh.onResult(localGetCRDTObject(id, knownClk, clk, clientId, sendMoreRecentUpdates, isSubscribed)); } else { dhtRequest(dst, new DHTGetCRDT(id, knownClk, clk, clientId, sendMoreRecentUpdates, isSubscribed), rh); } } /** * Return null if CRDT does not exist * * If clock equals to null, just return full CRDT * * @param subscribe * Subscription type * @return null if cannot fulfill request */ ManagedCRDT getCRDT(final CRDTIdentifier id, CausalityClock knownClk, CausalityClock clk, String clientId, boolean sendMoreRecentUpdates, boolean isSubscribed) { Endpoint dst = DHT_Node.resolveKey(id.toString()); if (dst == null) { return localGetCRDTObject(id, knownClk, clk, clientId, sendMoreRecentUpdates, isSubscribed); } else { return dhtRequest(dst, new DHTGetCRDT(id, knownClk, clk, clientId, sendMoreRecentUpdates, isSubscribed)); } } /** * Return null if CRDT does not exist */ <V extends CRDT<V>> CRDTData<V> localPutCRDT(ManagedCRDT<V> crdt) { lock(crdt.getUID()); try { @SuppressWarnings("unchecked") CRDTData<V> data = (CRDTData<V>) this.getDatabaseEntry(crdt.getUID()); if (data.empty) { data.initValue(crdt, crdt.getClock(), crdt.getPruneClock(), ClockFactory.newClock()); } else { // FIXME: this is an outcome of change to the op-based model and // discussions over e-mail. // It's unclear whether this should ever happen given reliable // DCDataServer. logger.warning("Unexpected concurrent put of the same object at the DCDataServer"); // TODO: this should better be encapsulated IMHO data.crdt.merge(crdt); // if (DCDataServer.prune) { // data.prunedCrdt.merge(crdt); // } data.clock.merge(crdt.getClock()); data.pruneClock.merge(crdt.getPruneClock()); synchronized (this.cltClock) { // FIXME: WHAT IS THIS??? NO-OP? this.cltClock.merge(cltClock); } } setModifiedDatabaseEntry(data); return data; } finally { unlock(crdt.getUID()); } } @SuppressWarnings("unchecked") <V extends CRDT<V>> ExecCRDTResult localExecCRDT(CRDTObjectUpdatesGroup<V> grp, CausalityClock _snapshotVersion, CausalityClock _trxVersion, Timestamp _txTs, Timestamp cltTs, Timestamp prvCltTs, CausalityClock curDCVersion) { CRDTIdentifier id = grp.getTargetUID(); lock(id); try { CRDTData<?> data = localGetCRDT(id); if (data == null) { if (!grp.hasCreationState()) { logger.warning("No creation state provided by client for an object that does not exist " + grp.getTargetUID()); return new ExecCRDTResult(false); } V creationState = grp.getCreationState(); // TODO: check clocks CausalityClock clk = grp.getDependency(); if (clk == null) { clk = ClockFactory.newClock(); } else { clk = clk.clone(); } final ManagedCRDT<V> crdt = new ManagedCRDT<V>(grp.getTargetUID(), creationState, clk, true); // FIXME: It used to say "will merge if object exists" - not so // sure after the switch to op-based. data = localPutCRDT(crdt); } data.pruneIfPossible(pruningInterval + surrogate.timeSmootherRandom.get().nextInt(pruningInterval)); // crdt.augumentWithScoutClock(new Timestamp(clientId, clientTxs)) // // // ensures that execute() has enough information to ensure tx // idempotence // crdt.execute(updates...) // crdt.discardScoutClock(clientId) // critical to not polute all // data // nodes and objects with big vectors, unless we want to do it until // pruning if (prvCltTs != null) data.crdt.augmentWithScoutClockWithoutMappings(prvCltTs); // Assumption: dependencies are checked the server, prior to // execution... data.crdt.execute((CRDTObjectUpdatesGroup) grp, CRDTOperationDependencyPolicy.RECORD_BLINDLY); data.crdt.augmentWithDCClockWithoutMappings(curDCVersion); /* * if (DCDataServer.prune) { if (prvCltTs != null) * data.prunedCrdt.augmentWithScoutClock(prvCltTs); * data.prunedCrdt.execute((CRDTObjectUpdatesGroup) grp, * CRDTOperationDependencyPolicy.RECORD_BLINDLY); * data.prunedCrdt.augmentWithDCClock(curDCVersion); * data.prunedCrdt.prune(data.clock, false); * data.prunedCrdt.discardScoutClock(cltTs.getIdentifier()); * data.pruneClock = data.clock; } */ data.crdt.discardScoutClock(cltTs.getIdentifier()); data.clock = data.crdt.getClock(); setModifiedDatabaseEntry(data); synchronized (this.cltClock) { this.cltClock.recordAllUntil(cltTs); if (logger.isLoggable(Level.INFO)) { logger.info("Data Server: for crdt : " + data.id + "; clk = " + data.clock + " ; cltClock = " + cltClock + "; snapshotVersion = " + _snapshotVersion + "; cltTs = " + cltTs); } } ObjectUpdatesInfo info = new ObjectUpdatesInfo(id, data.pruneClock.clone(), grp); dsPubSub.publish(new UpdateNotification(surrogate.surrogateId, info, surrogate.getEstimatedDCVersionCopy())); return new ExecCRDTResult(true, id, info); } finally { unlock(id); } } private ManagedCRDT localGetCRDTObject(Endpoint remote, DHTGetCRDT req) { if (req.subscribesUpdates()) dsPubSub.subscribe(req.getId(), remote); // else // dsPubSub.unsubscribe(req.getId(), remote); return localGetCRDTObject(req.getId(), req.getKnownVersion(), req.getVersion(), req.getCltId(), req.sendMoreRecentUpdates(), false); } /** * Return null if CRDT does not exist * * If clock equals to null, just return full CRDT * * @param version * * @param subscribe * Subscription type * @return null if cannot fulfill request */ ManagedCRDT localGetCRDTObject(CRDTIdentifier id, CausalityClock knownVersion, CausalityClock version, String clientId, boolean sendMoreRecentUpdates, boolean subscribeUpdates) { if (subscribeUpdates) dsPubSub.subscribe(id, surrogate.suPubSub); // else // dsPubSub.unsubscribe(localSurrogateId, id, suPubSub); lock(id); try { CRDTData<?> data = localGetCRDT(id); if (data == null) return null; // 1) let int clientTxs = // clientTxClockService.getAndLockNumberOfCommitedTxs(clientId) // // probably it could be done better, lock-free // 2) // let crdtCopy = retrieve(oid).copy() // crdtCopy.augumentWithScoutClock(new Timestamp(clientId, // clientTxs)) // 3) clientTxClockService.unlock(clientId) // 4) return crdtCopy /* * if( DCDataServer.prune) { CMP_CLOCK cmp = version.compareTo( * data.pruneClock); if( cmp == CMP_CLOCK.CMP_EQUALS || cmp == * CMP_CLOCK.CMP_DOMINATES) this.crdt = data.prunedCrdt.copy(); else * this.crdt = data.crdt.copy(); } else; */ if (!sendMoreRecentUpdates && knownVersion != null && !data.crdt.mayContainUpdatesBetween(knownVersion, version)) { return null; } // Bandwidth optimization: prune as much as possible before sending. // FIXME: this leaves out records covered by client clock (not in // "version") Timestamp ts = null; synchronized (cltClock) { ts = cltClock.getLatest(clientId); } final ManagedCRDT crdt = data.crdt.copyWithRestrictedVersioning(version, ts); // FIXME: when failing over between DCs, notifications for the // same update may reach the client with two different DC // timestamps. // To avoid duplicates, the notifications/fetch from a target // DC, need to filter out duplicates when necessary, which // happens only by side-effect of an implementation as of // 497a60a. if (ts != null) crdt.augmentWithScoutClockWithoutMappings(ts); return crdt; } finally { unlock(id); } } /** * Return null if CRDT does not exist * * If clock equals to null, just return full CRDT * * @param subscribe * Subscription type * @return null if cannot fulfill request */ CRDTData<?> localGetCRDT(CRDTIdentifier id) { lock(id); try { CRDTData<?> data = this.getDatabaseEntry(id); if (data.empty) return null; return data; } finally { unlock(id); } } }
SyncFree/SwiftCloud
src-core/swift/dc/DCDataServer.java
248,630
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package pkg5009cem_assignment; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author sjjde */ public class MFeedbackForumMain extends javax.swing.JFrame { /** * Creates new form FeedbackForumMain */ public MFeedbackForumMain() { initComponents(); displayDiscussions(); } //variable declaration private String username; public MFeedbackForumMain(String username){ initComponents(); this.username = username; displayDiscussions(); } //close entire UI window when navbtn clicked public void close() { dispose(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jDesktopPane1 = new javax.swing.JDesktopPane(); newDis_btn = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); mForumDis_table = new javax.swing.JTable(); visitorTrack_navbtn = new javax.swing.JButton(); forum_navbtn = new javax.swing.JButton(); paymentTrack_navbtn = new javax.swing.JButton(); residentAcc_navbtn = new javax.swing.JButton(); logout_btn = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setMaximumSize(new java.awt.Dimension(595, 370)); setMinimumSize(new java.awt.Dimension(595, 370)); setResizable(false); jPanel1.setMaximumSize(new java.awt.Dimension(857, 497)); jPanel1.setMinimumSize(new java.awt.Dimension(857, 497)); jPanel1.setPreferredSize(new java.awt.Dimension(857, 497)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jDesktopPane1.setMaximumSize(new java.awt.Dimension(720, 460)); jDesktopPane1.setMinimumSize(new java.awt.Dimension(720, 460)); jDesktopPane1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); newDis_btn.setText("+ new discussion"); newDis_btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newDis_btnActionPerformed(evt); } }); jDesktopPane1.add(newDis_btn, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 20, -1, -1)); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Discussions: Management Forum"); jDesktopPane1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, -1, -1)); mForumDis_table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Discussions" } ) { Class[] types = new Class [] { java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); //making the table row clickable mForumDis_table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if(!e.getValueIsAdjusting()) { int selected = mForumDis_table.getSelectedRow(); if (selected != -1) { String discussion = (String) mForumDis_table.getValueAt(selected,0); close(); MOngoingDis pi = new MOngoingDis(discussion, username); pi.setTitle(discussion); pi.setLocationRelativeTo(null); //center the form pi.setVisible(true); } } } }); jScrollPane1.setViewportView(mForumDis_table); jDesktopPane1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 680, 340)); jPanel1.add(jDesktopPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 40, 720, 460)); visitorTrack_navbtn.setText("Visitor Tracking"); visitorTrack_navbtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { visitorTrack_navbtnActionPerformed(evt); } }); jPanel1.add(visitorTrack_navbtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 130, -1)); forum_navbtn.setText("Feedback Forum"); jPanel1.add(forum_navbtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 130, -1)); paymentTrack_navbtn.setText("Bill Payment Tracking"); paymentTrack_navbtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { paymentTrack_navbtnActionPerformed(evt); } }); jPanel1.add(paymentTrack_navbtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 120, 130, -1)); residentAcc_navbtn.setText("Resident Accounts"); residentAcc_navbtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { residentAcc_navbtnActionPerformed(evt); } }); jPanel1.add(residentAcc_navbtn, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 160, 130, -1)); logout_btn.setText("Logout"); logout_btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logout_btnActionPerformed(evt); } }); jPanel1.add(logout_btn, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 460, -1, -1)); jLabel2.setText("Feedback Forum"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents //when user clicks on the button to navigate to 'Visitor Tracking' private void visitorTrack_navbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_visitorTrack_navbtnActionPerformed close(); MVisitorTrackingMain pi = new MVisitorTrackingMain(username); pi.setTitle("Visitor Tracking"); pi.setLocationRelativeTo(null); //center the form pi.setVisible(true); }//GEN-LAST:event_visitorTrack_navbtnActionPerformed //when user clicks on the button to navigate to 'Bill Payment Tracking' private void paymentTrack_navbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_paymentTrack_navbtnActionPerformed close(); MBillPayTrackingMain pi = new MBillPayTrackingMain(username); pi.setTitle("Bill Payment Tracking"); pi.setLocationRelativeTo(null); //center the form pi.setVisible(true); }//GEN-LAST:event_paymentTrack_navbtnActionPerformed //when user clicks on the button to navigate to 'Resident Accounts' private void residentAcc_navbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_residentAcc_navbtnActionPerformed close(); MResidentAccountsMain pi = new MResidentAccountsMain(username); pi.setTitle("Resident Accounts"); pi.setLocationRelativeTo(null); //center the form pi.setVisible(true); }//GEN-LAST:event_residentAcc_navbtnActionPerformed //when user clicks on the 'logout' button private void logout_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logout_btnActionPerformed int res = JOptionPane.showConfirmDialog(logout_btn, "Are you sure you want to sign out?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (res == JOptionPane.YES_OPTION) { dispose(); MainLogin login = new MainLogin(); login.setTitle("Main Login Page"); login.setLocationRelativeTo(null); //center the form login.setVisible(true); } else { dispose(); MFeedbackForumMain pi = new MFeedbackForumMain(username); pi.setTitle("Resident Accounts"); pi.setLocationRelativeTo(null); //center the form pi.setVisible(true); } }//GEN-LAST:event_logout_btnActionPerformed //when user clicks on '+ new discussion' to open the new discussion page private void newDis_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newDis_btnActionPerformed close(); MNewDis pi = new MNewDis(username); pi.setTitle("New management forum discussion"); pi.setLocationRelativeTo(null); //center the form pi.setVisible(true); }//GEN-LAST:event_newDis_btnActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MFeedbackForumMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MFeedbackForumMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MFeedbackForumMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MFeedbackForumMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MFeedbackForumMain().setVisible(true); } }); } //sini sini //display discussions private void displayDiscussions() { Connection conn = ConnectDB.connectDB(); if (conn != null) { try { //Statement st = conn.createStatement(); PreparedStatement pst = (PreparedStatement) conn.prepareStatement("SELECT * FROM manager_forum"); //pst.setString(1, "title"); //telling the system to query for data inside "title" ResultSet rs = pst.executeQuery(); DefaultTableModel model = (DefaultTableModel) mForumDis_table.getModel(); model.setRowCount(0); while (rs.next()) { String disTitle = rs.getString("title"); //add data to the table model.addRow(new Object[]{disTitle}); } rs.close(); pst.close(); conn.close(); } catch (SQLException ex) { Logger.getLogger(MFeedbackForumMain.class.getName()).log(Level.SEVERE, null, ex); } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton forum_navbtn; private javax.swing.JDesktopPane jDesktopPane1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton logout_btn; private javax.swing.JTable mForumDis_table; private javax.swing.JButton newDis_btn; private javax.swing.JButton paymentTrack_navbtn; private javax.swing.JButton residentAcc_navbtn; private javax.swing.JButton visitorTrack_navbtn; // End of variables declaration//GEN-END:variables }
daryllim22/5009CEM-GROUP-ASSIGNMENT
MFeedbackForumMain.java
248,631
// // $Id$ package client.frame; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Image; import com.threerings.msoy.web.gwt.Args; import com.threerings.msoy.web.gwt.Pages; import com.threerings.msoy.web.gwt.Tabs; import client.shell.CShell; import client.shell.ShellMessages; import client.ui.MsoyUI; import client.util.BillingUtil; import client.util.Link; /** * Displays our sub-navigation. */ public class SubNaviPanel extends FlowPanel { /** * Creates subnav for the given tab. */ public SubNaviPanel (Tabs tab) { reset(tab); } /** * Creates subnav for being in a game or in the world. */ public SubNaviPanel () { reset(null); } /** * Resets the subnavigation to the default for the specified tab. If tab is null, create sub * navigation for either being in a scene or being in a game according to the specified value. */ public void reset (Tabs tab) { clear(); int memberId = CShell.getMemberId(); if (tab == null) { return; } switch (tab) { case ME: if (CShell.isGuest()) { addLink(null, "Home", Pages.LANDING); } else { addImageLink("/images/me/menu_home.png", "Home", Pages.WORLD, Args.compose("m" + memberId)); if (!CShell.getClientMode().isMinimal()) { addLink(null, "My Rooms", Pages.PEOPLE, "rooms", memberId); } if (CShell.isRegistered()) { addLink(null, "Friends", Pages.PEOPLE); addLink(null, "Account", Pages.ACCOUNT, "edit"); } if (CShell.isSupport()) { addLink(null, "Admin", Pages.ADMINZ); } } break; case BILLING: addExternalLink("http://wiki.whirled.com/Billing_FAQ", "Billing FAQ", true); if (CShell.isSupport()) { addLink(null, "Billing Admin", Pages.BILLING, "admin"); } break; case STUFF: break; case GAMES: if (CShell.isMember()) { addLink(null, "My Trophies", Pages.GAMES, "t", memberId); addLink(null, "My Games", Pages.EDGAMES, "m"); } addLink(null, "New Games", Pages.GAMES, "g", -2, "newest"); // -2 is all, ugh if (CShell.isSupport()) { addLink(null, "Edit Arcades", Pages.EDGAMES, "ea"); } break; case ROOMS: if (!CShell.getClientMode().isMinimal() && CShell.isMember()) { addImageLink("/images/me/menu_home.png", "Home", Pages.WORLD, Args.compose("m" + memberId)); addLink(null, "My Rooms", Pages.PEOPLE, "rooms", memberId); } break; case GROUPS: if (CShell.isRegistered()) { addLink(null, "My Groups", Pages.GROUPS, "mygroups"); addLink(null, "My Discussions", Pages.GROUPS, "unread"); if (CShell.isSupport()) { addLink(null, "Issues", Pages.ISSUES); addLink(null, "My Issues", Pages.ISSUES, "mine"); } } break; case SHOP: addLink(null, "My Favorites", Pages.SHOP, "f"); if (CShell.isRegistered()) { addLink(null, "Transactions", Pages.ME, "transactions"); } break; case HELP: addLink(null, "Contact Us", Pages.SUPPORT); addLink(null, "Report Bug", Pages.GROUPS, "f", 72); if (CShell.isSupport()) { addLink(null, "Admin", Pages.SUPPORT, "admin"); } break; default: // nada break; } } public void addLink (String iconPath, String label, Pages page, Object... args) { addLink(iconPath, label, true, page, args); } public void addLink (String iconPath, String label, boolean sep, Pages page, Object... args) { addSeparator(sep); if (iconPath != null) { add(MsoyUI.createActionImage(iconPath, Link.createHandler(page, args))); add(new HTML("&nbsp;")); } add(Link.create(label, page, args)); } public void addExternalLink (String url, String label, boolean sep) { addSeparator(sep); add(MsoyUI.createExternalAnchor(url, label)); } public void addContextLink (String label, Pages page, Args args, int position) { // sanity check the position if (position > getWidgetCount()) { position = getWidgetCount(); } insert(new HTML("&nbsp;&nbsp;|&nbsp;&nbsp;"), position++); insert(Link.create(label, page, args), position); } public Image addImageLink (String path, String tip, Pages page, Args args) { return addImageLink(path, tip, Link.createHandler(page, args), true); } public Image addImageLink (String path, String tip, ClickHandler clickHandler, boolean sep) { addSeparator(sep); Image icon = MsoyUI.createActionImage(path, clickHandler); icon.setTitle(tip); add(icon); return icon; } protected void addSeparator (boolean sep) { if (getWidgetCount() > 0) { add(new HTML("&nbsp;&nbsp;" + (sep ? "|&nbsp;&nbsp;" : ""))); } } protected static final ShellMessages _msgs = GWT.create(ShellMessages.class); }
greyhavens/msoy
src/gwt/client/frame/SubNaviPanel.java
248,632
/* The MIT License (MIT) Copyright (c) Terry Evans Vaughn All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.blueseer.adm; import bsmf.MainFrame; import static bsmf.MainFrame.bslog; import static bsmf.MainFrame.hidate; import com.blueseer.utl.BlueSeerUtils; import com.blueseer.utl.OVData; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingWorker; import oshi.SystemInfo; import oshi.hardware.HardwareAbstractionLayer; import oshi.hardware.NetworkIF; import oshi.software.os.OperatingSystem; /** * * @author vaughnte */ public class About extends javax.swing.JPanel { String currenttext = ""; /** * Creates new form AboutPanel */ public About() { initComponents(); currenttext = jTextArea2.getText(); } class Task extends SwingWorker<Void, Void> { /* * Main task. Executed in background thread. */ @Override public Void doInBackground() { logSysInfo(); return null; } /* * Executed in event dispatch thread */ public void done() { BlueSeerUtils.endTask(new String[]{"0","System info is complete"}); // now pull sysinfo from app/sys.log file generated at startup (bsmf.MainFrame.logSysInfo()) BufferedReader fsr; try { fsr = new BufferedReader(new FileReader(new File("data/sys.log"))); String line = ""; while ((line = fsr.readLine()) != null) { jTextArea2.append(line + "\n"); } fsr.close(); } catch (FileNotFoundException ex) { MainFrame.bslog(ex); jTextArea2.append("File not found at data/sys.log"); } catch (IOException ex) { MainFrame.bslog(ex); } } } public static void logSysInfo() { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); long availableMemory = hal.getMemory().getAvailable(); String Text = "INIT DATE: " + hidate + "\n"; Text += "Locale: " + Locale.getDefault().toString() + "\n"; Text += "Version: " + MainFrame.ver + "\n"; Text += "DataBase: " + MainFrame.db + "\n"; Text += "DataBaseType: " + MainFrame.dbtype + "\n"; Text += "DataBaseDriver: " + MainFrame.driver + "\n"; Text += "Available memory (bytes): " + (availableMemory == Long.MAX_VALUE ? "no limit" : availableMemory) + "\n"; long totalMemory = hal.getMemory().getTotal(); Text += "Total memory (bytes): " + (totalMemory == Long.MAX_VALUE ? "no limit" : totalMemory) + "\n"; Text += "Processor: " + si.getHardware().getProcessor().getName() + "\n"; Text += "Processor Vendor: " + si.getHardware().getProcessor().getVendor() + "\n"; Text += "Processor Model: " + si.getHardware().getProcessor().getModel() + "\n"; Text += "Processor Logical Count: " + si.getHardware().getProcessor().getLogicalProcessorCount() + "\n"; Text += "Processor Physical Count: " + si.getHardware().getProcessor().getPhysicalProcessorCount() + "\n"; OperatingSystem os = si.getOperatingSystem(); Text += "Operating System: " + os + "\n"; Text += "OS Family: " + os.getFamily() + "\n"; Text += "OS Manufacturer: " + os.getManufacturer() + "\n"; Text += "OS Version: " + os.getVersion().getVersion() + "\n"; Text += "OS Bit: " + os.getBitness() + "\n"; Text += "OS Build: " + os.getVersion().getBuildNumber() + "\n"; Text += "OS Codename: " + os.getVersion().getCodeName() + "\n"; Text += "OS FileSystem: " + os.getFileSystem() + "\n"; NetworkIF[] s = si.getHardware().getNetworkIFs(); for (NetworkIF x : s) { Text += "Network: " + x.getName() + " / " + String.join(", ", x.getIPv4addr()) + "\n"; } Text += "Java Version: " + System.getProperty("java.version") + "\n"; Text += "Java VM: " + System.getProperty("java.vm.name") + "\n"; Text += "Java VM Version: " + System.getProperty("java.vm.version") + "\n"; Text += "Java Runtime Name: " + System.getProperty("java.runtime.name") + "\n"; Text += "Java Runtime Version: " + System.getProperty("java.runtime.version") + "\n"; Text += "Java Class Version: " + System.getProperty("java.class.version") + "\n"; Text += "Java Compiler: " + System.getProperty("sun.management.compiler") + "\n"; // now get patch info...created from git command : git rev-parse HEAD /* BufferedReader fsr; try { fsr = new BufferedReader(new FileReader(new File(".patch"))); String line = ""; while ((line = fsr.readLine()) != null) { Text += "Patch: " + line; } fsr.close(); } catch (FileNotFoundException ex) { MainFrame.bslog(ex); } catch (IOException ex) { MainFrame.bslog(ex); } */ // now write to app.log try(FileWriter fileWriter = new FileWriter("data/sys.log", false) ){ fileWriter.write(Text); } catch (IOException ex) { bslog(ex); } } public void getSysInfo() { /* Total number of processors or cores available to the JVM */ jTextArea2.setText(""); BlueSeerUtils.startTask(new String[]{"","Retrieving System Info..."}); Task task = new Task(); task.execute(); } public void initvars(String[] arg) { if (arg != null && arg.length > 0 && arg[0].equals("SysInfo")) { getSysInfo(); } else { jTextArea2.setText(currenttext); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); setLayout(new java.awt.BorderLayout()); jTextArea2.setEditable(false); jTextArea2.setColumns(20); jTextArea2.setRows(5); jTextArea2.setText("\nBlueSeer ERP was developed to provide the open source community with a free alternative to proprietary ERPs\nwith regards to both cost and customization capability. For more information, you can visit the application project\nsite hosted on github or the primary website shown below. There exists forums to submit issues, discussions, or feedback\nat these locations.\n\nWebsite:\t\twww.blueseer.com\nProject Site:\t\thttps://github.com/BlueSeerERP \nEmail:\t\[email protected]\nCreator:\t\tTerry Evans Vaughn\nLanguage:\t\tJava\nDatabase:\t\tSQLite,MySQL\nSource:\t\thttps://github.com/BlueSeerERP/blueseer\n"); jScrollPane2.setViewportView(jTextArea2); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 989, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 844, Short.MAX_VALUE) ); add(jPanel1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea jTextArea2; // End of variables declaration//GEN-END:variables }
blueseerERP/blueseer
src/com/blueseer/adm/About.java
248,634
package root; import javax.swing.ImageIcon; /** * @author https://www.github.com/thuongtruong1009/Snake-Game-OOP */ public class Root { // meta data public String author = "https://github.com/thuongtruong1009"; public String version = "v8.0 (user setup)"; public String date = "Wednesday, 3 November 2021"; public String language = "JavaSwing"; public String JDK = "14x"; public String OS = "Window_NT x64 10.0"; public String frameTitle = "Snake Game OOP"; public int PANEL_WIDTH = 600; public int PANEL_HEIGHT = 600; // Image icons public ImageIcon fileMenu = new ImageIcon("./src/image/file2.png"); public ImageIcon levelMenu = new ImageIcon("./src/image/level2.png"); public ImageIcon moreMenu = new ImageIcon("./src/image/more2.png"); public ImageIcon helpMenu = new ImageIcon("./src/image/help2.png"); public ImageIcon icon = new ImageIcon("./src/image/snake_icon.png"); public ImageIcon ic1 = new ImageIcon("./src/image/high_score.png"); public ImageIcon ic2 = new ImageIcon("./src/image/new_game.png"); public ImageIcon ic3 = new ImageIcon("./src/image/quit.png"); public ImageIcon icn1 = new ImageIcon("./src/image/fork.png"); public ImageIcon icn2 = new ImageIcon("./src/image/discuss2.png"); public ImageIcon icn3 = new ImageIcon("./src/image/license.png"); public ImageIcon icn4 = new ImageIcon("./src/image/contact.png"); public ImageIcon Icn1 = new ImageIcon("./src/image/how_to_play.png"); public ImageIcon Icn2 = new ImageIcon("./src/image/bug.png"); public ImageIcon Icn3 = new ImageIcon("./src/image/love_icon.png"); public ImageIcon Icn4 = new ImageIcon("./src/image/about.png"); public ImageIcon download = new ImageIcon("./src/image/download.png"); // Images Path In Array public String[] list = { "./src/backgrounds/background1.jpeg", "./src/backgrounds/background2.jpg", "./src/backgrounds/background3.jpg", "./src/backgrounds/background4.jpg", "./src/backgrounds/background5.jpg", "./src/backgrounds/background1.jpeg" }; public String[] array2 = { "./src/image/easy.png", "./src/image/medium.png", "./src/image/difficult.png" }; // buttons labels public String restartBtn = "./src/buttons/restartButton.png"; public String pauseBtn = "./src/buttons/pauseButton.png"; public String resumeBtn = "./src/buttons/resumeButton.png"; public String quitBtn = "./src/buttons/quitButton.png"; public String playBtn = "./src/buttons/playButton.png"; public String newGameBtn = "./src/buttons/newGameButton.png"; public String highScoreBtn = "./src/buttons/highScoreButton.png"; public String loveBtn = "./src/buttons/loveButton.png"; // music path public String introSound = "../musics/music.wav"; public String eatAppleSound = "../musics/eat.wav"; public String bombSound = "../musics/bomb.wav"; public String winSound = "../musics/win.wav"; public String failSound = "../musics/fail.wav"; public String outroSound = "../musics/outro.wav"; // link to broswer public String contact = "mailto:[email protected]"; public String discuss = "https://github.com/thuongtruong1009/Snake-Game-OOP/discussions"; public String fork = "https://github.com/thuongtruong1009/Snake-Game-OOP/fork"; public String bug = "https://github.com/thuongtruong1009/Snake-Game-OOP/issues"; public String how_to_play = "https://github.com/thuongtruong1009/Snake-Game-OOP/blob/main/README.md#-how-to-play-this-game"; public String scorePath = "./src/files/dataScore.txt"; public String scoreTitle = "history"; public String licensePath = "./src/files/LICENSE.txt"; public String licenseTitle = "ECL-2.0 LICENSE"; public String paypalLink = "https://paypal.me/thuongtruong1009"; public String momoLink = "https://nhantien.momo.vn/0917085937"; public String kofiLink = "https://ko-fi.com/thuongtruong1009"; public String donateTitle = "Confirm"; public String donateMessage = "Thank you for your donation!\nPlease choose one of below payment methods"; public String downloadDisc = "Your file has been downloaded successfully!\nCheck at C:/Users/PC/Downloads/"; public String downloadTitle = "message"; // URL must be absolute path // public String downloadURL = "https://www.w3.org/TR/PNG/iso_8859-1.txt"; public String downloadURL = "src/files/dataScore.txt"; public String downloadAddress = "C:\\Users\\PC\\Downloads\\your_score.txt"; public String deleteDisc = "This action will delete all your score history"; public String deleteTitle = "Warning"; public String aboutTitle = "About"; public String aboutDesc = "SNAKE-GAME-OOP\n" + "\nAuthor: " + author + "\nVersion: " + version + "\nDate: " + date + "\nLanguage: " + language + "\nJDK: " + JDK + "\nOS: " + OS; }
thuongtruong1009/Snake-Game-OOP
src/root/Root.java
248,635
class Main { int id = 0; String name = "Kyra"; static void printEmployee() { int age = 22; String name = "Vishnu"; System.out.println("ID: " + id); System.out.println("Name: " + name);       System.out.println("Name: " + this.name); System.out.println("age: "+ this.age); } public static void main(String args[]) { printEmployee(); } }
modernlabrat/UMGC
CMSC330/Discussions/main.java
248,636
package swisseph; /** * This class implements a TransitCalculator for one planets * position or speed.<p> * You would create a TransitCalculator from this class and * use the SwissEph.getTransit() methods to actually calculate * a transit, e.g.:<p> * <pre> * SwissEph sw = new SwissEph(...); * ... * int flags = SweConst.SEFLG_SWIEPH | * SweConst.SEFLG_TRANSIT_LONGITUDE | * SweConst.SEFLG_TRANSIT_SPEED; * boolean backwards = false; * * TransitCalculator tc = new TCPlanet( * sw, * SweConst.SE_SATURN, * flags, * 0); * ... * double nextTransitET = sw.getTransitET(tc, jdET, backwards); * </pre> * This would calculate the (ET-) date, when the Saturn will * change from retrograde to direct movement or vice versa. */ public class TCPlanet extends TransitCalculator implements java.io.Serializable { private int planet; private int idx = 0; // The index into the xx[] array in swe_calc() to use: private int tflags = 0; // The transit flags private int flags = 0; // The calculation flags for swe_calc() private double min = 0; private double max = 0; // The y = f(x) value to reach, speaking mathematically... private double offset = 0.; double minVal = 0., maxVal = 0.; // Thinking about it... /** * Creates a new TransitCalculator for transits of any of the planets * positions (longitudinal / latitudinal and distance) or speeds, be * it in the geocentric or topocentric coordinate system, or in tropical * or sidereal zodiac.<p> * @param sw A SwissEph object, if you have one available. May be null. * @param planet The transiting planet or object number.<br> * Planets from SweConst.SE_SUN up to SweConst.SE_INTP_PERG (with the * exception of SweConst.SE_EARTH) have their extreme speeds saved, so * these extreme speeds will be used on calculation.<br>Other objects * calculate extreme speeds by randomly calculating by default 200 speed * values and multiply them by 1.4 as a safety factor.<br> * ATTENTION: be sure to understand that you might be able to miss some * transit or you might get a rather bad transit time in very rare * circumstances.<br> * Use SweConst.SE_AST_OFFSET + asteroid number for planets with a * planet number not defined by SweConst.SEFLG_*. * @param flags The calculation type flags (SweConst.SEFLG_TRANSIT_LONGITUDE, * SweConst.SEFLG_TRANSIT_LATITUDE or SweConst.SEFLG_TRANSIT_DISTANCE in * conjunction with SweConst.SEFLG_TRANSIT_SPEED for transits over a speed * value).<br><br> * Also flags modifying the basic planet calculations, these are * SweConst.SEFLG_TOPOCTR, SweConst.SEFLG_EQUATORIAL, SweConst.SEFLG_HELCTR, * SweConst.SEFLG_TRUEPOS, and SweConst.SEFLG_SIDEREAL, plus the * optional ephemeris flags SweConst.SEFLG_MOSEPH, SweConst.SEFLG_SWIEPH or * SweConst.SEFLG_JPLEPH optionally. * <br>For <i>right ascension</i> use <code>SEFLG_TRANSIT_LONGITUDE | SEFLG_EQUATORIAL</code>, * for <i>declination</i> <code>SEFLG_TRANSIT_LATITUDE | SEFLG_EQUATORIAL</code>.<br> * @param offset This is the desired transit degree or distance in AU or transit speed * in deg/day. * @see swisseph.TCPlanetPlanet#TCPlanetPlanet(SwissEph, int, int, int, double) * @see swisseph.TCPlanet#TCPlanet(SwissEph, int, int, double, int, double) * @see swisseph.SweConst#SEFLG_TRANSIT_LONGITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_LATITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_DISTANCE * @see swisseph.SweConst#SEFLG_TRANSIT_SPEED * @see swisseph.SweConst#SEFLG_YOGA_TRANSIT * @see swisseph.SweConst#SE_AST_OFFSET * @see swisseph.SweConst#SEFLG_TOPOCTR * @see swisseph.SweConst#SEFLG_EQUATORIAL * @see swisseph.SweConst#SEFLG_HELCTR * @see swisseph.SweConst#SEFLG_TRUEPOS * @see swisseph.SweConst#SEFLG_SIDEREAL * @see swisseph.SweConst#SEFLG_MOSEPH * @see swisseph.SweConst#SEFLG_SWIEPH * @see swisseph.SweConst#SEFLG_JPLEPH */ public TCPlanet(SwissEph sw, int planet, int flags, double offset) { this(sw, planet, flags, offset, 200, 1.4); } /** * Creates a new TransitCalculator for transits of any of the planets * positions (longitudinal / latitudinal and distance) or speeds, be * it in the geocentric or topocentric coordinate system, or in tropical * or sidereal zodiac.<p> * @param sw A SwissEph object, if you have one available. May be null. * @param planet The transiting planet or object number.<br> * Planets from SweConst.SE_SUN up to SweConst.SE_INTP_PERG (with the * exception of SweConst.SE_EARTH) have their extreme speeds saved, so * these extreme speeds will be used on calculation.<br>Other objects * calculate extreme speeds by randomly calculating by default 200 speed * values and multiply them by 1.4 as a safety factor.<br> * Changing the 200 calculations will give higher or lower startup time * on <code>new TCPlanet(...)</code>, changing the 1.4 safety factor will * change each single calculation time.<br> * ATTENTION: be sure to understand that you might be able to miss some * transit on these other objects or you might get a rather bad transit * time in very rare circumstances.<br> * Use SweConst.SE_AST_OFFSET + asteroid number for planets with a * planet number not defined by SweConst.SEFLG_*. * @param flags The calculation type flags (SweConst.SEFLG_TRANSIT_LONGITUDE, * SweConst.SEFLG_TRANSIT_LATITUDE or SweConst.SEFLG_TRANSIT_DISTANCE in * conjunction with SweConst.SEFLG_TRANSIT_SPEED for transits over a speed * value).<br><br> * Also flags modifying the basic planet calculations, these are * SweConst.SEFLG_TOPOCTR, SweConst.SEFLG_EQUATORIAL, SweConst.SEFLG_HELCTR, * SweConst.SEFLG_TRUEPOS, and SweConst.SEFLG_SIDEREAL, plus the (optional) * ephemeris flags SweConst.SEFLG_MOSEPH, SweConst.SEFLG_SWIEPH or * SweConst.SEFLG_JPLEPH. * <br>For <i>right ascension</i> use <code>SEFLG_TRANSIT_LONGITUDE | SEFLG_EQUATORIAL</code>, * for <i>declination</i> <code>SEFLG_TRANSIT_LATITUDE | SEFLG_EQUATORIAL</code>.<br> * @param offset This is the desired transit degree or distance (in AU) or transit speed * (in deg/day or AU/day). * @param precalcCount When calculating planets without saved extreme speeds, * you may change the default value of 200 random calculations to search for the * extreme speeds here. * @param precalcSafetyfactor When calculating planets without saved extreme speeds, * you may change the default value of 1.4 as a safety factor to be multiplied with * the found extreme speeds here. * @see swisseph.TCPlanetPlanet#TCPlanetPlanet(SwissEph, int, int, int, double) * @see swisseph.SweConst#SEFLG_TRANSIT_LONGITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_LATITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_DISTANCE * @see swisseph.SweConst#SEFLG_TRANSIT_SPEED * @see swisseph.SweConst#SEFLG_YOGA_TRANSIT * @see swisseph.SweConst#SE_AST_OFFSET * @see swisseph.SweConst#SEFLG_TOPOCTR * @see swisseph.SweConst#SEFLG_EQUATORIAL * @see swisseph.SweConst#SEFLG_HELCTR * @see swisseph.SweConst#SEFLG_TRUEPOS * @see swisseph.SweConst#SEFLG_SIDEREAL * @see swisseph.SweConst#SEFLG_MOSEPH * @see swisseph.SweConst#SEFLG_SWIEPH * @see swisseph.SweConst#SEFLG_JPLEPH */ public TCPlanet(SwissEph sw, int planet, int flags, double offset, int precalcCount, double precalcSafetyfactor) { // Check parameter: ////////////////////////////////////////////////////// // List of all valid flags: this.tflags = flags; int vFlags = SweConst.SEFLG_EPHMASK | SweConst.SEFLG_TOPOCTR | SweConst.SEFLG_EQUATORIAL | SweConst.SEFLG_HELCTR | SweConst.SEFLG_NOABERR | SweConst.SEFLG_NOGDEFL | SweConst.SEFLG_SIDEREAL | SweConst.SEFLG_TRUEPOS | SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE | SweConst.SEFLG_TRANSIT_SPEED; // NOABERR and NOGDEFL is allowed for HELCTR, as they get set // anyway. if ((flags & SweConst.SEFLG_HELCTR) != 0) { vFlags |= SweConst.SEFLG_NOABERR | SweConst.SEFLG_NOGDEFL; } if ((flags&~vFlags) != 0) { throw new IllegalArgumentException("Invalid flag(s): "+(flags&~vFlags)); } // Allow only one of SEFLG_TRANSIT_LONGITUDE, SEFLG_TRANSIT_LATITUDE, SEFLG_TRANSIT_DISTANCE: int type = flags&(SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE); if (type != SweConst.SEFLG_TRANSIT_LONGITUDE && type != SweConst.SEFLG_TRANSIT_LATITUDE && type != SweConst.SEFLG_TRANSIT_DISTANCE) { throw new IllegalArgumentException("Invalid flag combination '" + flags + "': specify exactly one of SEFLG_TRANSIT_LONGITUDE (" + SweConst.SEFLG_TRANSIT_LONGITUDE + "), SEFLG_TRANSIT_LATITUDE (" + SweConst.SEFLG_TRANSIT_LATITUDE + "), SEFLG_TRANSIT_DISTANCE (" + SweConst.SEFLG_TRANSIT_DISTANCE + ")."); } if ((flags & SweConst.SEFLG_HELCTR) != 0 && (planet == SweConst.SE_MEAN_APOG || planet == SweConst.SE_OSCU_APOG || planet == SweConst.SE_MEAN_NODE || planet == SweConst.SE_TRUE_NODE)) { throw new IllegalArgumentException( "Unsupported planet number " + planet + " (" + sw.swe_get_planet_name(planet) + ") for heliocentric " + "calculations"); } this.planet = planet; this.sw = sw; if (this.sw == null) { this.sw = new SwissEph(); } // The index into the xx[] array in swe_calc() to use: if ((flags&SweConst.SEFLG_TRANSIT_LATITUDE) != 0) { // Calculate latitudinal transits idx = 1; } else if ((flags&SweConst.SEFLG_TRANSIT_DISTANCE) != 0) { // Calculate distance transits idx = 2; } if ((flags&SweConst.SEFLG_TRANSIT_SPEED) != 0) { // Calculate speed transits idx += 3; flags |= SweConst.SEFLG_SPEED; } // Eliminate SEFLG_TRANSIT_* flags for use in swe_calc(): flags &= ~(SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE | SweConst.SEFLG_TRANSIT_SPEED); this.flags = flags; rollover = (idx == 0); // Ok - idx==1 as well, but the range will be from -90 to +90 // then, which does not fit the scheme. We need a rolloverMin // value or similar for this to work this.offset = checkOffset(offset); max = getSpeed(false); min = getSpeed(true); if (Double.isInfinite(max) || Double.isInfinite(min)) { // Trying to find some reasonable min- and maxSpeed by randomly testing some speed values. // Limited to ecliptical(?) non-speed calculations so far: if (idx < 3) { double[] minmax = getTestspeed(planet, idx, precalcCount, precalcSafetyfactor); min = minmax[0]; max = minmax[1]; } } //System.err.println("speeds: " + min + " - " + max); if (Double.isInfinite(max) || Double.isInfinite(min)) { int planetno = (planet > SweConst.SE_AST_OFFSET ? planet - SweConst.SE_AST_OFFSET : planet); throw new IllegalArgumentException( ((flags&SweConst.SEFLG_TOPOCTR)!=0?"Topo":((flags&SweConst.SEFLG_HELCTR)!=0?"Helio":"Geo")) + "centric transit calculations of planet number " + planetno + " ("+ sw.swe_get_planet_name(planet) + ") not possible: (extreme) " + ((flags & SweConst.SEFLG_SPEED) != 0 ? "accelerations" : "speeds") + " of the planet " + ((flags & SweConst.SEFLG_EQUATORIAL) != 0 ? "in equatorial system " : "") + "not available."); } } /** * @return Returns true, if one position value is identical to another * position value. E.g., 360 degree is identical to 0 degree in * circular angles. * @see #rolloverVal */ public boolean getRollover() { return rollover; } /** * This sets the degree or other value for the position or speed of * the planet to transit. It will be used on the next call to getTransit(). * @param value The desired offset value. * @see #getOffset() */ public void setOffset(double value) { offset = checkOffset(value); } /** * This returns the degree or other value of the position or speed of * the planet to transit. * @return The currently set offset value. * @see #setOffset(double) */ public double getOffset() { return offset; } /** * This returns the planet number as an Integer object. * @return An array of identifiers identifying the calculated objects. */ public Object[] getObjectIdentifiers() { return new Integer[]{planet}; } ////////////////////////////////////////////////////////////////////////////// protected double calc(double jdET) { StringBuffer serr = new StringBuffer(); double[] xx = new double[6]; int ret = sw.swe_calc(jdET, planet, flags, xx, serr); if (ret<0) { int type = SwissephException.UNDEFINED_ERROR; if (serr.toString().matches("jd 2488117.1708818264 > Swiss Eph. upper limit 2487932.5;")) { type = SwissephException.BEYOND_USER_TIME_LIMIT; } throw new SwissephException(jdET, type, "Calculation failed with return code "+ret+":\n"+serr.toString()); } return xx[idx]; } protected double getMaxSpeed() { return max; } protected double getMinSpeed() { return min; } protected double getTimePrecision(double degPrec) { // Recalculate degPrec to mean the minimum time, in which the planet can // possibly move that degree: double maxTimePerDeg = SMath.max(SMath.abs(min),SMath.abs(max)); if (maxTimePerDeg != 0.) { return degPrec / maxTimePerDeg; } return 1E-9; } protected double getDegreePrecision(double jd) { // Calculate the planet's minimum movement regarding the maximum available // precision. // // For all calculations, we assume the following minimum exactnesses // based on the discussions on http://www.astro.com/swisseph, even though // these values are nothing more than very crude estimations which should // leave us on the save side always, even more, when seeing that we always // consider the maximum possible speed / acceleration of a planet in the // transit calculations and not the real speed. // // Take degPrec to be the minimum exact degree in longitude double degPrec = 0.005; if (idx>2) { // Speed // "The speed precision is now better than 0.002" for all planets" degPrec = 0.002; } else { // Degrees // years 1980 to 2099: 0.005" // years before 1980: 0.08" (from sun to jupiter) // years 1900 to 1980: 0.08" (from saturn to neptune) (added: nodes) // years before 1900: 1" (from saturn to neptune) (added: nodes) // years after 2099: same as before 1900 // if (planet>=SweConst.SE_SUN && planet<=SweConst.SE_JUPITER) { if (jd<1980 || jd>2099) { degPrec = 0.08; } } else { if (jd>=1900 && jd<1980) { degPrec = 0.08; } else if (jd<1900 || jd>2099) { // Unclear about true nodes... degPrec = 1; } } } degPrec/=3600.; degPrec*=0.5; // We take the precision to BETTER THAN ... as it is stated somewhere // We recalculate these degrees to the minimum time difference that CAN // possibly give us data differing more than the above given precision. switch (idx) { case 0: // Longitude case 1: // Latitude case 3: // Speed in longitude case 4: // Speed in latitude break; case 2: // Distance case 5: // Speed in distance // We need to recalculate the precision in degrees to a distance value. // For this we need the maximum distance to the centre of calculation, // which is the barycentre for the main planets. if (planet >= sw.ext.maxBaryDist.length) { degPrec *= 0.05; // Rather random value??? } else { degPrec *= sw.ext.maxBaryDist[planet]; } } return degPrec; // Barycentre: // 0.981683040 1.017099581 (Barycenter of the earth!) // Sun: 0.982747149 AU 1.017261973 AU // Moon: 0.980136691 AU 1.019846623 AU // Mercury: 0.307590579 AU 0.466604085 AU // Venus: 0.717960758 AU 0.728698831 AU // Mars: 1.382830768 AU 0.728698831 AU // Jupiter: 5.448547595 AU 4.955912195 AU // Saturn: 10.117683425 AU 8.968685733 AU // Uranus: 18.327870391 AU 19.893326756 AU // Neptune: 29.935653168 AU 30.326750627 AU // Pluto: 29.830132096 AU 41.499626899 AU // MeanNode: 0.002569555 AU 0.002569555 AU // TrueNode: 0.002361814 AU 0.002774851 AU // // Minimum and maximum (barycentric) distances: // Sun: 0.000095 AU 0.01034 AU // Moon: 0.972939 AU 1.02625 AU // Mercury: 0.298782 AU 0.47569 AU // Venus: 0.709190 AU 0.73723 AU // Mars: 1.370003 AU 1.67685 AU // Jupiter: 4.912031 AU 5.47705 AU // Saturn: 8.948669 AU 10.13792 AU // Uranus: 18.257511 AU 20.12033 AU // Neptune: 29.780622 AU 30.36938 AU // Pluto: 29.636944 AU 49.43648 AU // MeanNode: - AU - AU ? // TrueNode: - AU - AU ? // Maximum and minimum (geocentric) distances: // Sun: 1.016688129 AU 0.983320477 AU // Moon: 0.002710279 AU 0.002439921 AU // Mercury: 0.549188094 AU 1.448731236 AU // Saturn: 7.84 / 7.85 AU 11.25/11.26 AU // Uranus: 21.147/21.148 AU AU } ////////////////////////////////////////////////////////////////////////////// private double checkOffset(double val) { // Similar rollover considerations for the latitude will be necessary, if // swe_calc() would return latitudinal values beyond -90 and +90 degrees. if (rollover) { // Longitude from 0 to 360 degrees: while (val < 0.) { val += 360.; } val %= 360.; minVal = 0.; maxVal = 360.; } else if (idx == 1) { // Latitude from -90 to +90 degrees: while (val < -90.) { val += 180.; } while (val > 90.) { val -= 180.; } minVal = -90.; maxVal = +90.; } return val; } private double getSpeed(boolean min) { boolean lon = ((tflags&SweConst.SEFLG_TRANSIT_LONGITUDE) != 0); boolean lat = ((tflags&SweConst.SEFLG_TRANSIT_LATITUDE) != 0); boolean dist = ((tflags&SweConst.SEFLG_TRANSIT_DISTANCE) != 0); boolean speed = ((tflags&SweConst.SEFLG_TRANSIT_SPEED) != 0); boolean topo = ((tflags&SweConst.SEFLG_TOPOCTR) != 0); boolean helio = ((tflags&SweConst.SEFLG_HELCTR) != 0); boolean rect = ((tflags&SweConst.SEFLG_EQUATORIAL) != 0 && !lat && !dist); boolean decl = ((tflags&SweConst.SEFLG_EQUATORIAL) != 0 && lat); try { // Some topocentric speeds are very different to the geocentric // speeds, so we use other values than for geocentric calculations: if (topo) { if (!sw.swed.geopos_is_set) { throw new IllegalArgumentException("Geographic position is not set for "+ "requested topocentric calculations."); } // if (sw.swed.topd.geoalt>50000.) { // throw new IllegalArgumentException("Topocentric transit calculations "+ // "are restricted to a maximum "+ // "altitude of 50km so far."); // } else if (sw.swed.topd.geoalt<-12000000) { // throw new IllegalArgumentException("Topocentric transit calculations "+ // "are restricted to a minimum "+ // "altitude of -12000km so far."); // } if (sw.swed.topd.geoalt>50000. || sw.swed.topd.geoalt<-12000000) { return 1./0.; } if (speed) { if (rect) { return (min?SwephData.minTopoRectAccel[planet]:SwephData.maxTopoRectAccel[planet]); } else if (decl) { return (min?SwephData.minTopoDeclAccel[planet]:SwephData.maxTopoDeclAccel[planet]); } else if (lat) { return (min?SwephData.minTopoLatAccel[planet]:SwephData.maxTopoLatAccel[planet]); } else if (dist) { return (min?SwephData.minTopoDistAccel[planet]:SwephData.maxTopoDistAccel[planet]); } else if (lon) { return (min?SwephData.minTopoLonAccel[planet]:SwephData.maxTopoLonAccel[planet]); } } else { if (rect) { return (min?SwephData.minTopoRectSpeed[planet]:SwephData.maxTopoRectSpeed[planet]); } else if (decl) { return (min?SwephData.minTopoDeclSpeed[planet]:SwephData.maxTopoDeclSpeed[planet]); } else if (lat) { return (min?SwephData.minTopoLatSpeed[planet]:SwephData.maxTopoLatSpeed[planet]); } else if (dist) { return (min?SwephData.minTopoDistSpeed[planet]:SwephData.maxTopoDistSpeed[planet]); } else if (lon) { return (min?SwephData.minTopoLonSpeed[planet]:SwephData.maxTopoLonSpeed[planet]); } } } // Heliocentric speeds are very different to the geocentric speeds, so // we use other values than for geocentric calculations: if (helio) { if (speed) { if (rect) { return (min?SwephData.minHelioRectAccel[planet]:SwephData.maxHelioRectAccel[planet]); } else if (decl) { return (min?SwephData.minHelioDeclAccel[planet]:SwephData.maxHelioDeclAccel[planet]); } else if (lat) { return (min?SwephData.minHelioLatAccel[planet]:SwephData.maxHelioLatAccel[planet]); } else if (dist) { return (min?SwephData.minHelioDistAccel[planet]:SwephData.maxHelioDistAccel[planet]); } else if (lon) { return (min?SwephData.minHelioLonAccel[planet]:SwephData.maxHelioLonAccel[planet]); } } else { if (rect) { return (min?SwephData.minHelioRectSpeed[planet]:SwephData.maxHelioRectSpeed[planet]); } else if (decl) { return (min?SwephData.minHelioDeclSpeed[planet]:SwephData.maxHelioDeclSpeed[planet]); } else if (lat) { return (min?SwephData.minHelioLatSpeed[planet]:SwephData.maxHelioLatSpeed[planet]); } else if (dist) { return (min?SwephData.minHelioDistSpeed[planet]:SwephData.maxHelioDistSpeed[planet]); } else if (lon) { return (min?SwephData.minHelioLonSpeed[planet]:SwephData.maxHelioLonSpeed[planet]); } } } // Geocentric: if (speed) { if (rect) { return (min?SwephData.minRectAccel[planet]:SwephData.maxRectAccel[planet]); } else if (decl) { return (min?SwephData.minDeclAccel[planet]:SwephData.maxDeclAccel[planet]); } else if (lat) { return (min?SwephData.minLatAccel[planet]:SwephData.maxLatAccel[planet]); } else if (dist) { return (min?SwephData.minDistAccel[planet]:SwephData.maxDistAccel[planet]); } else if (lon) { return (min?SwephData.minLonAccel[planet]:SwephData.maxLonAccel[planet]); } } else { if (rect) { return (min?SwephData.minRectSpeed[planet]:SwephData.maxRectSpeed[planet]); } else if (decl) { return (min?SwephData.minDeclSpeed[planet]:SwephData.maxDeclSpeed[planet]); } else if (lat) { return (min?SwephData.minLatSpeed[planet]:SwephData.maxLatSpeed[planet]); } else if (dist) { return (min?SwephData.minDistSpeed[planet]:SwephData.maxDistSpeed[planet]); } else if (lon) { return (min?SwephData.minLonSpeed[planet]:SwephData.maxLonSpeed[planet]); } } return 1./0.; } catch (Exception e) { return 1./0.; } } // This routine returns extreme speed values by randomly calculating the speed // of the planet. Doesn't work for accelerations so far. double[] getTestspeed(int planet, int idx, int precalcCount, double precalcSafetyfactor) { StringBuffer serr = new StringBuffer(); double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; double[] timerange = new double[] { SwephData.MOSHPLEPH_START, SwephData.MOSHPLEPH_END }; if (planet > SweConst.SE_AST_OFFSET) { // get filename: String fn = SwissLib.swi_gen_filename(2457264.5 /* doesn't matter */, planet); // Unfortunately, the name from swi_gen_filename may be slightly different, // so we have to test opening the filename and change the filename if // the file does not exist or is not readable: FilePtr fptr = null; SwissephException se = null; try { fptr = sw.swi_fopen(SwephData.SEI_FILE_ANY_AST, fn, sw.swed.ephepath, serr); } catch (SwissephException se1) { se = se1; } if (fptr == null) { /* * try also for short files (..s.se1) */ if (fn.indexOf("s.") <= 0) { fn = fn.substring(0, fn.indexOf(".")) + "s." + SwephData.SE_FILE_SUFFIX; } try { fptr = sw.swi_fopen(SwephData.SEI_FILE_ANY_AST, fn, sw.swed.ephepath, serr); } catch (SwissephException se2) { se = se2; } } if (fptr == null) { throw se; } try { fptr.close(); } catch (Exception e) { } // Now finally we have a filename for which we can get the time range, // if the file can be found and is readable: try { timerange = sw.getDatafileTimerange(fn); } catch (SwissephException se3) { } } java.util.Random rd = new java.util.Random(); double[] xx = new double[6]; for(int f = 0; f < precalcCount; f++) { double jdET = rd.nextDouble(); jdET = jdET * (timerange[1] - timerange[0]) + timerange[0]; int ret = sw.swe_calc(jdET, planet, flags | SweConst.SEFLG_SPEED, xx, serr); if (ret<0) { // throw new SwissephException(jdET, SwissephException.UNDEFINED_ERROR, // "Calculation failed with return code "+ret+":\n"+serr.toString()); continue; } if (min > xx[idx+3]) { min = xx[idx+3]; } if (max < xx[idx+3]) { max = xx[idx+3]; } } if (min == max || min == Double.MAX_VALUE || max == -Double.MAX_VALUE) { min = 1./0.; // Use as flag } else { // Apply safety factor for randomly calculated extreme speeds: switch ((int)Math.signum(min)) { case -1 : min *= precalcSafetyfactor; break; case 0 : min = -0.1; break; case 1 : min /= precalcSafetyfactor; break; } switch ((int)Math.signum(max)) { case -1 : max /= precalcSafetyfactor; break; case 0 : max = 0.1; break; case 1 : max *= precalcSafetyfactor; break; } } return new double[] {min, max}; } public String toString() { return "[Planet:" + planet + "];Offset:" + getOffset(); } }
Kibo/AstroAPI
src/main/java/swisseph/TCPlanet.java
248,637
package enums; public enum ResourceTypes { // CONTRIBUTION_IDEA, // Contributions are resources that are introduced in the system by single users // CONTRIBUTION_QUESTION, // CONTRIBUTION_COMMENT, // CONTRIBUTION_ISSUE, PROPOSAL, // Proposals are created and edited by Working Groups // DISCUSSION, // Discussions are created and edited by Assemblies or Working Groups // ELECTION, // Discussions are created and edited by Assemblies // BALLOT, // Ballots are created by Assemblies // VOTE, // Votes are created by single Users // PROPOSAL_TEMPLATE, // Templates are created and edited by Assemblies // EXTERNAL // External resources can be anything that has a URL PICTURE, VIDEO, PAD, TEXT, WEBPAGE, FILE, AUDIO, CONTRIBUTION_TEMPLATE }
rebearteta/appcivist-platform
app/enums/ResourceTypes.java
248,638
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; public final class UnknownName extends RTIexception { public UnknownName(String msg) { super(msg); } } //end UnknownName
hla-certi/jcerti1516e
src/hla/rti1516/UnknownName.java
248,639
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * * Public exception class IllegalName * */ public final class IllegalName extends RTIexception { public IllegalName(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/IllegalName.java
248,640
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * LogicalTime declares an interface to an immutable time value */ public interface LogicalTime extends Comparable, java.io.Serializable { boolean isInitial(); boolean isFinal(); /** * Returns a LogicalTime whose value is (this + val). */ LogicalTime add(LogicalTimeInterval val) throws IllegalTimeArithmetic; /** * Returns a LogicalTime whose value is (this - val). */ LogicalTime subtract(LogicalTimeInterval val) throws IllegalTimeArithmetic; /** * Returns a LogicalTimeInterval whose value is the time interval between this * and val. */ LogicalTimeInterval distance(LogicalTime val); @Override int compareTo(Object other); /** * Returns true iff this and other represent the same logical time Supports * standard Java mechanisms. */ @Override boolean equals(Object other); /** * Two LogicalTimes for which equals() is true should yield same hash code */ @Override int hashCode(); @Override String toString(); int encodedLength(); void encode(byte[] buffer, int offset); }// end LogicalTime
hla-certi/jcerti1516e
src/hla/rti1516/LogicalTime.java
248,641
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAbyte extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the byte value of this element. * * @return value */ byte getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAbyte.java
248,642
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; public final class RangeBounds implements java.io.Serializable { public RangeBounds(long l, long u) { lower = l; upper = u; } public long lower; public long upper; @Override public boolean equals(Object other) { if (other != null && other instanceof RangeBounds) { RangeBounds otherRangeBounds = (RangeBounds) other; return lower == otherRangeBounds.lower && upper == otherRangeBounds.upper; } else { return false; } } @Override public int hashCode() { return (int) (lower + upper); } } //end RangeBounds
hla-certi/jcerti1516e
src/hla/rti1516/RangeBounds.java
248,643
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAoctet extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the byte value of this element. * * @return value */ byte getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAoctet.java
248,644
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * * Public exception class NameNotFound * */ public final class NameNotFound extends RTIexception { public NameNotFound(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/NameNotFound.java
248,645
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; public interface RegionHandle extends java.io.Serializable { /** * @return true if this refers to the same Region as other handle */ @Override boolean equals(Object otherRegionHandle); /** * @return int. All instances that refer to the same Region should return the * same hashcode. */ @Override int hashCode(); @Override String toString(); } //end RegionHandle //File: RegionHandleSet.java
hla-certi/jcerti1516e
src/hla/rti1516/RegionHandle.java
248,646
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Superclass of all exceptions thrown by the RTI. All RTI exceptions must be * caught or specified. */ public class RTIexception extends Exception { public RTIexception(String msg) { super(msg); } } //end RTIexception
hla-certi/jcerti1516e
src/hla/rti1516/RTIexception.java
248,647
package PamUtils; import java.io.File; import java.util.zip.ZipOutputStream; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.zip.ZipEntry; //example by pitchoun from http://www.theserverside.com/discussions/thread.tss?thread_id=34906 //FolderZipper provide a static method to zip a folder. /** * Description of the Class * * @author cjb22 * @created 22 September 2009 */ public class FolderZipper { /** * Zip the srcFolder into the destFileZipFile. All the folder subtree of the src folder is added to the destZipFile * archive. * * TODO handle the usecase of srcFolder being en file. * * @param srcFolder String, the path of the srcFolder * @param destZipFile String, the path of the destination zipFile. This file will be created or erased. * @param useFolderNameAsRootInZip Description of the Parameter */ public static void zipFolder(String srcFolder, String destZipFile, boolean useFolderNameAsRootInZip) { ZipOutputStream zip = null; FileOutputStream fileWriter = null; try { fileWriter = new FileOutputStream(destZipFile); zip = new ZipOutputStream(fileWriter); } catch (Exception ex) { ex.printStackTrace(); // System.exit(0); } if (useFolderNameAsRootInZip) { addToZip(null, srcFolder, zip); } else { File folder = new File(srcFolder); String fileList[] = folder.list(); try { int i = 0; while (true) { addToZip( null, srcFolder + File.separator + fileList[i], zip); i++; } } catch (Exception ex) { } } try { zip.flush(); zip.close(); fileWriter.close(); } catch (Exception ex) { ex.printStackTrace(); } } /** * Write the content of srcFile in a new ZipEntry, named path+srcFile, of the zip stream. The result * is that the srcFile will be in the path folder in the generated archive. * * @param path String, the relatif path with the root archive. * @param srcFile String, the absolute path of the file to add * @param zip ZipOutputStram, the stream to use to write the given file. */ private static void addToZip(String path, String srcFile, ZipOutputStream zip) { File folder = new File(srcFile); String newEntry; System.out.println("addToZip:" + path + ":" + srcFile); if (folder.isDirectory()) { if (path !=null) { newEntry=path + File.separator + folder.getName(); } else { newEntry= folder.getName(); } addFolderToZip(path, srcFile, zip); } else { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; try { FileInputStream in = new FileInputStream(srcFile); if (path !=null) { newEntry=path + File.separator + folder.getName(); } else { newEntry= folder.getName(); } zip.putNextEntry(new ZipEntry(newEntry)); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } in.close(); } catch (Exception ex) { ex.printStackTrace(); //in.close(); } } } /** * add the srcFolder to the zip stream. * * @param path String, the relatif path with the root archive. * @param zip ZipOutputStram, the stream to use to write the given file. * @param srcFolder The feature to be added to the FolderToZip attribute */ private static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) { File folder = new File(srcFolder); String fileList[] = folder.list(); String newEntry; System.out.println("addFolderToZip:" + path + ":" + srcFolder); try { for(int i=0;i<fileList.length;i++) {//was while true and exception was not displayed if (path !=null) { newEntry=path + File.separator + folder.getName(); } else { newEntry= folder.getName(); } addToZip(newEntry, srcFolder + File.separator + fileList[i], zip); } } catch (Exception ex) { ex.printStackTrace(); } } }
PAMGuard/PAMGuard
src/PamUtils/FolderZipper.java
248,648
package utils; import model.TUser; import java.util.EnumMap; import static utils.TextUtils.*; /** * @author Denis Danilin | [email protected] * 15.05.2020 * tfs ☭ sweat and blood */ public class LangMap { private static final EnumMap<Value, String> enData, ruData; static { ruData = new EnumMap<>(Value.class); enData = new EnumMap<>(Value.class); init(Value.LS_HELP, mdBold("Folder view mode.") + "\n" + escapeMd("First row show folder path, if exists below are shown all notes which are placed here.\nFirst row buttons:\n") + escapeMd(Strings.Uni.goUp + " - go to the parent folder. ") + mdItalic("doesnt shown if you're in a root folder") + "\n" + escapeMd(Strings.Uni.label + " - make note in the current folder. ") + mdItalic("you have to type note's text after click") + "\n" + escapeMd(Strings.Uni.mkdir + " - make subfolder in the current folder. ") + mdItalic("you have to type subfolder's name after click") + "\n" + escapeMd(Strings.Uni.gear + " - go to 'folder edit mode'. ") + mdItalic("provides possibility to rename, delete or share access to the current folder") + "\n\n" + escapeMd("Entire content of the current folder (subfolders and files) is displayed with buttons (max. 10 buttons per page).\n\n" + "If entry is folder it will have " + Strings.Uni.folder + " icon before its name. Click the button to get into the folder.\n" + "Click the file's button to view the file.\n\n " + "If the current folder contains more than 10 childs then last row of buttons will contain navigation buttons: " + Strings.Uni.rewind + " - 10 " + "entries back and " + Strings.Uni.forward + " - 10 entries further"), mdBold("Режим просмотра папки.") + "\n" + escapeMd("Первой строкой указан путь к текущей папке, ниже, если есть, показаны все заметки, которые были заведены в ней.\nПервая строка кнопок:\n") + escapeMd(Strings.Uni.goUp + " - переход в родительскую папку. ") + mdItalic("не показывается, если текущая директория - корневая") + "\n" + escapeMd(Strings.Uni.label + " - создание заметки в текущей папке. ") + mdItalic("после нажатия нужно будет ввести текст заметки") + "\n" + escapeMd(Strings.Uni.mkdir + " - создание подпапки в текущей папке. ") + mdItalic("после нажатия нужно будет ввести имя новой папки") + "\n" + escapeMd(Strings.Uni.gear + " - переход в режим управления папкой. ") + mdItalic("предоставляет доступ к переименованию, удалению и предоставлению публичного и " + "персонального доступа к текущей папке") + "\n\n" + escapeMd("Содержимое текущей папки (подпапки и файлы) отображено кнопками (макс. 10 штук).\n\n" + "Если элемент - папка, то перед его именем стоит иконка " + Strings.Uni.folder + ". Нажатие на кнопку приводит к переходу в эту папку.\n" + "Нажатие на кнопку файла позволяет просмотреть этот файл.\n\n Если текущая папка содержит больше 10 элементов, то последней строкой отображаются " + "две кнопки перехода по страницам: " + Strings.Uni.rewind + " - назад на 10 файлов и " + Strings.Uni.forward + " - вперёд на 10 файлов")); init(Value.FILE_HELP, mdBold("File view mode\n") + escapeMd("First of all file's body is shown. Below is file's path, after that control buttons are:\n" + Strings.Uni.goUp + " - go to the parent folder.\n" + Strings.Uni.keyLock + " - set/clear password on file.\n" + Strings.Uni.share + " - go to the access share management.\n" + Strings.Uni.edit + " - rename the file. ") + mdItalic("you have to type new file's name after click. Be aware that file wont be actually renamed " + "in a cloud. Only display name will be changed after that.\n") + escapeMd(Strings.Uni.drop + " - drop the file. ") + mdItalic("File will be permanently deleted."), mdBold("Режим просмотра файла\n") + escapeMd("Первым отображается тело самого файла. Ниже указан путь файла, затем идёт ряд кнопок управления:\n" + Strings.Uni.goUp + " - переход в родительскую папку.\n" + Strings.Uni.keyLock + " - установить/снять пароль на доступ к файлу.\n" + Strings.Uni.share + " - переход к управлению правами доступа к файлу.\n" + Strings.Uni.edit + " - переименование файла. ") + mdItalic("после нажатия нужно будет ввести новое имя файла. Внимание, сам файл физически не будет " + "переименован, будет изменено только имя под которым он отображается в боте.\n") + escapeMd(Strings.Uni.drop + " - удаление файла. ") + mdItalic("после нажатия файл будет безвозвратно удалён.")); init(Value.SEARCHED_HELP, mdBold("Search results mode\n") + escapeMd("Search query and search folder are show at first, followed by search results quantity.\nNext is button " + Strings.Uni.goUp + ": exit search - " + "after click you will get into 'view mode' of the element where you started searching.\n\nIf bot found more than nothing then all results are " + "shown as buttons. Each button is signed with entry's relative path, relative to the your current folder\n\n") + mdItalic("Be aware that found notes, unlike the 'view mode', are also shown with buttons.\n\n") + escapeMd("Click to any result button takes you to the view mode according to the element's type, but return button (" + Strings.Uni.goUp + ") will " + "lead back to the search results.\n"), mdBold("Просмотр результатов поиска\n") + escapeMd("Первой строкой показаны поисковый запрос и папка начала поиска, затем общее количество результатов поиска.\nЗатем следует строка с кнопкой выхода из " + "режима поиска: " + Strings.Uni.goUp + " - нажатие приводит к возврату в режим просмотра того элемента, где был начат поиск.\n\nЕсли количество " + "результатов отлично от нуля, то все они показываются ниже кнопками. Каждая кнопка подписана согласно локальному пути элемента, относительно текущей папки\n\n") + mdItalic("Обратите внимание, что найденные заметки, в отличие от обычного режима, здесь показываются тоже кнопками, наравне с файлами и папками.\n\n") + escapeMd("Нажатие на любую кнопку приводит к переходу в режим обычного просмотра выбранного элемента, согласно его типу, но в этом просмотре кнопка выхода " + "из просмотра (" + Strings.Uni.goUp + ") будет вести обратно к результатам поиска.\n")); init(Value.ROOT_HELP, mdBold("Root folder\n") + escapeMd("You are in the root folder of the TeleFS.\n\n" + "Bot allows to create, edit and delete folders and files just like you do it on your home PC, only hierarchy is available immediately via all " + "your devices with your telegram account.\n" + "Physically files are in the telegram's cloud and its real content is unaccessible to neither bot nor somebody else, untill you decide to share " + "it.\n" + "Bot follows 'one window' policy, that means, that any time you see single message from it where content depends on your mode and " + "performed commands; e.g. if you searched for something then you see search results, if you changed a folder - you see folder's content in same " + "message and so on.\n\n" + "Regardless of modes and actions, four actions are available to you at any given time:\n") + mdBold("1. ") + mdItalic("files upload") + escapeMd(" bot's main goal is to keep access to your folders and files according to your structure. Any time " + "you can extend your collection just simple send any number of files, all of it will be stored in a current folder, where you are while send it.. " + "No special command or action is required, just send files to bot and thats it. ") + mdItalic( "Be aware, simple 'documents' are saved with original filenames, but its not so for media files - unfortunately, telegram loses its filenames, so" + " bot have to construct it from the file's types.\n" + "Hint: if you will apply a comment while sending a file, then bot will use it as filename\n\n") + mdBold("2. ") + escapeMd("'/reset' command - reset bot's state if it is unconscious and takes you here, to the root folder.\n\n") + mdBold("3. ") + escapeMd("'/help' - context help, reflects on your actions and current position. If you're missed and dont know what to do - use this " + "command.\n\n") + mdBold("4. ") + mdItalic("search by filename") + escapeMd(" - you can start search anywhere at full hierarchy depth from where you are, just send a " + "query text. ") + mdItalic("The search is always case-insensitive and for any part of the name\n\n") + escapeMd("These buttons are available at the root folder:\n") + escapeMd(Strings.Uni.label + " - make a note. ") + mdItalic("you will have to type a note's text after click") + "\n" + escapeMd(Strings.Uni.mkdir + " - make a subfolder. ") + mdItalic("you will have to type a new subfolder's name after click") + "\n" + escapeMd(Strings.Uni.gear + " - go to the 'notes manage mode'. ") + mdItalic("you will be able to manage existed notes in the root folder"), mdBold("Домашняя папка\n") + escapeMd("Вы находитесь в домашней папке вашей файловой системы TeleFS.\n\n" + "Бот позволяет создавать, изменять и удалять папки и файлы также, как вы делаете это на своём компьютере, только эта иерархия сразу доступна на всех" + " ваших устройствах, где запущен telegram под вашим аккаунтом.\n" + "Файлы физически находятся в облаке telegram и их содержимое недоступно ни боту, ни кому-либо ещё, до тех пор, пока вы не решите поделиться доступом с " + "кем-либо.\n" + "Бот работает в режиме 'единого окна', это означает, что в любой момент времени вы видите только одно сообщение от бота, в котором содержимое " + "соответствует режиму и командам, принятым от вас; то есть, если вы что-то искали - вы видите результаты поиска, если вы перешли в директорию - " + "содержимое сообщения изменится на список содержимого этой директории и так далее.\n\n" + "Независимо от режимов и действий, в любой момент времени вам доступны четыре действия:\n") + mdBold("1. ") + mdItalic("добавление файлов") + escapeMd(" главная задача бота - хранить доступ к вашим файлам, согласно созданной вами структуре. Вы в любой " + "момент можете пополнить вашу коллекцию просто отправив любое количество файлов боту, они будут сохранены в той папке, где вы находитесь в момент отправки. " + "Никаких специальных комманд или действий не требуется - просто посылайте файлы. ") + mdItalic("Обратите внимание, что документы сохраняются с теми " + "именами, с которыми они были посланы, но это не касается фотографий, видео и аудио материалов - к сожалению, telegram не передаёт их имена, потому бот называет " + "полученные файлы согласно их типам.\n" + "Подсказка: если вы посылаете файл и в комментарии напишете что-либо, то комментарий будет использован в качестве имени файла\n\n") + mdBold("2. ") + escapeMd("команда '/reset' - если отклик бота неадекватен или отсутствует. Это сбрасывает ваше взаимодействие с ботом и возвращает вас " + "на начальную точку - сюда, в домашнюю папку.\n\n") + mdBold("3. ") + escapeMd("команда '/help' - контекстная помощь, в зависимости от того, где вы сейчас находитесь и что делали. Если вы запутались и не знаете " + "куда нажать - отправьте эту команду.\n\n") + mdBold("4. ") + mdItalic("поиск по имени") + escapeMd(" - в любом месте файловой системы вы можете искать файлы и папки по имени, вглубь по всей иерархии, " + "начиная с того места, где вы находитесь. Просто отправьте сообщение с частью искомого имени из любого места. ") + mdItalic("Поиск всегда происходит без учёта " + "регистра и по любой части имени\n\n") + escapeMd("В домашней папке вам доступны следующие кнопки управления:\n") + escapeMd(Strings.Uni.label + " - создание заметки в текущей папке. ") + mdItalic("после нажатия нужно будет ввести текст заметки") + "\n" + escapeMd(Strings.Uni.mkdir + " - создание подпапки в текущей папке. ") + mdItalic("после нажатия нужно будет ввести имя новой папки") + "\n" + escapeMd(Strings.Uni.gear + " - переход в режим управления метками. ") + mdItalic("предоставляет доступ к редактированию и удалению меток в домашней папке") ); init(Value.SHARE_DIR_HELP, mdBold("Manage folder's access sharing\n") + escapeMd("In TeleFS you can share folder in two ways: public anonymous link and personal grants..\n\n" + "Anonymous access is granted via public http-link. You can achieve it with click on " + Strings.Uni.link + " button. Second click removes public " + "link." + "With clicking on this link a user achieves a 'read-only' access to your folder.\n\n" + "Personal access is granted individually for every user. If you click a " + Strings.Uni.mkGrant + " button, then bot will ask you to share with " + "it contact of the person you want grant access to. It means that a person must be telegram user and you must have him in contacts. " + "After contact received bot will display a button with person's name in a share management list.\n" + "Personal access can be 'read-only' or 'full'. 'Full' means that a person could change or even delete your folder's entire content, be careful " + "with it. You can change access type with simple clicking person's button.\n" + "Right of each personal access's button there is drop button with " + Strings.Uni.drop + " icon - if you click it this person's access will be " + "immediately removed.\n" + Strings.Uni.cancel + " - return to the folder view mode."), mdBold("Управление доступом к папке\n") + escapeMd("В TeleFS вы можете предоставлять доступ к своим папкам и файлам двумя способами: публичная ссылка и персональный доступ.\n\n" + "Публичный анонимный доступ предоставляется путём создания http-ссылки на папку. Это делается нажатием на кнопку " + Strings.Uni.link + ". Повторное нажатие удаляет " + "ранее созданную ссылку. При переходе по данной ссылке любой пользователь telegram получает доступ 'только для чтения' к вашей папке.\n\n" + "Персональный доступ предоставляется индивидуально для каждого человека. После нажатия кнопки " + Strings.Uni.mkGrant + " вам будет " + "предложено прислать боту контакт человека, с которым вы хотите поделиться содержимым папки. Это означает, что человек должен быть " + "пользователем telegram и он должен быть у вас в контактах. После получения контакта, кнопка с именем пользователя будет отображена в " + "списке управления доступом. Персональный доступ может быть как 'только для чтения' так и 'полный доступ'; второй вариант означает, что" + " этот пользователь сможет изменять и удалять содержимое папки, будьте осторожны в предоставлении такого варианта. Для изменения режима " + "предоставления доступа достаточно один раз кликнуть на кнопку с именем пользователя.\n" + "Справа от каждой кнопки персонального доступа находится кнопка удаления с иконкой " + Strings.Uni.drop + " - при клике на неё доступ к " + "данной папке для данного пользователя будет сразу же аннулирован.\n" + Strings.Uni.cancel + " - кнопка возврата к режиму просмотра папки.") ); init(Value.SHARE_FILE_HELP, mdBold("Manage file's access sharing\n") + escapeMd("In TeleFS you can share file in two ways: public anonymous link and personal grants..\n\n" + "Anonymous access is granted via public http-link. You can achieve it with click on " + Strings.Uni.link + " button. Second click removes public " + "link." + "With clicking on this link a user achieves a 'read-only' access to your file.\n\n" + "Personal access is granted individually for every user. If you click a " + Strings.Uni.mkGrant + " button, then bot will ask you to share with " + "it contact of the person you want grant access to. It means that a person must be telegram user and you must have him in contacts. " + "After contact received bot will display a button with person's name in a share management list.\n" + "Personal access can be 'read-only' or 'full'. 'Full' means that a person could change or even delete your file, be careful " + "with it. You can change access type with simple clicking person's button.\n" + "Right of each personal access's button there is drop button with " + Strings.Uni.drop + " icon - if you click it this person's access will be " + "immediately removed.\n" + Strings.Uni.cancel + " - return to the file view mode."), mdBold("Управление доступом к файлу\n") + escapeMd("В TeleFS вы можете предоставлять доступ к своим папкам и файлам двумя способами: публичная ссылка и персональный доступ.\n\n" + "Публичный анонимный доступ предоставляется путём создания http-ссылки на файл. Это делается нажатием на кнопку " + Strings.Uni.link + ". Повторное нажатие удаляет " + "ранее созданную ссылку. При переходе по данной ссылке любой пользователь telegram получает доступ 'только для чтения' к вашему файлу" + ".\n\nПерсональный доступ предоставляется индивидуально для каждого человека. После нажатия кнопки " + Strings.Uni.mkGrant + " вам будет " + "предложено прислать боту контакт человека, с которым вы хотите поделиться данным файлом. Это означает, что человек должен быть " + "пользователем telegram и он должен быть у вас в контактах. После получения контакта, кнопка с именем пользователя будет отображена в " + "списке управления доступом. Персональный доступ может быть как 'только для чтения' так и 'полный доступ'; второй вариант означает, что" + " этот пользователь сможет переименовать или удалить файл, будьте осторожны в предоставлении такого варианта. Для изменения режима " + "предоставления доступа достаточно один раз кликнуть на кнопку с именем пользователя.\n" + "Справа от каждой кнопки персонального доступа находится кнопка удаления с иконкой " + Strings.Uni.drop + " - при клике на неё доступ к " + "данному файлу для данного пользователя будет сразу же аннулирован.\n" + Strings.Uni.cancel + " - кнопка возврата к режиму просмотра файла.") ); init(Value.GEAR_HELP, mdBold("Folder manage mode\n") + escapeMd("Navigation is unavailable in this mode, only folder's management.\n\nFirst row is a control buttons:" + Strings.Uni.keyLock + " - set/clear access password.\n" + Strings.Uni.share + " - share folder's access.\n" + Strings.Uni.edit + " - rename the folder. ") + mdItalic("you will have to type new folder's name after click.\n") + escapeMd(Strings.Uni.drop + " - delete the folder. ") + mdItalicU("folder will be deleted after click " + mdBold("with its entire content\n")) + escapeMd(Strings.Uni.cancel + " - back to the view mode\n\n" + "If notes are found in the folder it will be displayed with buttons, below control buttons.\n" + "Click on the note button will take you in the note's management mode." ), mdBold("Режим управления папкой\n") + escapeMd("В данном режиме недоступна навигация ни вверх ни вниз по иерархии.\n\nВ первой строке находятся кнопки управления самой папкой:\n" + Strings.Uni.keyLock + " - задать/снять пароль на доступ к папке.\n" + Strings.Uni.share + " - управление правами доступа к папке.\n" + Strings.Uni.edit + " - переименование папки. ") + mdItalic("после нажатия нужно будет ввести новое имя папки.\n") + escapeMd(Strings.Uni.drop + " - удаление папки. ") + mdItalicU("после нажатия папка будет безвозвратно удалена " + mdBold("вместе со всем содержимым\n")) + escapeMd(Strings.Uni.cancel + " - выход из режима управления\n\n" + "Если в папке имеются заметки, то они будут отображены кнопками, ниже ряда кнопок управления.\n" + "Клик по кнопке заметки приводит к переходу в режим управления этой заметкой." )); init(Value.LABEL_HELP, mdBold("Note management mode\n") + escapeMd("Here you can edit or delete a note with these buttons:\n" + Strings.Uni.edit + " - edit note. ") + mdItalic("You will have to type new note's text after click\n") + escapeMd(Strings.Uni.drop + " - delete note. ") + mdItalic("Note will be permanently deleted after click.\n") + escapeMd(Strings.Uni.goUp + " - back to the parent's folder view mode. "), mdBold("Режим управления заметкой\n") + escapeMd("Здесь вы можете отредактировать или удалить заметку, с помощью соответствующих кнопок:\n" + Strings.Uni.edit + " - редактирование заметки. ") + mdItalic("После нажатия нужно будет ввести новый текст заметки\n") + escapeMd(Strings.Uni.drop + " - удаление заметки. ") + mdItalic("После нажатия заметка будет безвозвратно удалена.\n") + escapeMd(Strings.Uni.goUp + " - выход из режима управления. ") + mdItalic("После нажатаия вы будете возвращены в режим просмотра родительской папки.") ); init(Value.GEARING, "Manage folder '%s'", "Управление папкой '%s'"); init(Value.CANT_MKDIR, "cannot create directory ‘%s’: File exists", "Невозможно создать папку '%s': файл уже существует"); init(Value.CANT_RN_TO, "cannot rename to ‘%s’: File exists", "Невозможно переименовать в '%s': файл уже существует"); init(Value.CANT_MKLBL, "cannot create label ‘%s’: File exists", "Невозможно создать заметку '%s': файл уже существует"); init(Value.NO_RESULTS, "Nothing found", "Ничего не найдено"); init(Value.RESULTS_FOUND, "Found entries:", "Результаты:"); init(Value.TYPE_RENAME, "Type new name for '%s':", "Напиши новое имя для '%s':"); init(Value.TYPE_FOLDER, "Type new folder name:", "Напиши имя новой папки"); init(Value.CD, "cd %s", "переход в %s"); init(Value.PAGE, "page #%s", "страница #'%s'"); init(Value.NORMAL_MODE, "Normal mode", "Нормальный режим"); init(Value.EDIT_MODE, "Edit mode.", "Режим редактирования."); init(Value.DELETED_MANY, "%s entry(s) deleted", "%s файл(ов) удалено"); init(Value.DELETED, "Entry deleted", "Файл удалён"); init(Value.MOVE_DEST, "Choose destination folder.", "Необходимо выбрать папку для переноса."); init(Value.DESELECTED, "deselected", "Отмена выбора"); init(Value.SELECTED, "selected", "Файл(ы) выбран(ы)"); init(Value.MOVED, "Moved %s entry(s)", "Перенесено %s файл(ов)"); init(Value.TYPE_LABEL, "Type label:", "Текст заметки:"); init(Value.NO_CONTENT, "No content here yet. Send me some files.", "В этой папке пока ничего нет."); init(Value.NO_CONTENT_START, "No content here yet. You can store some files here or create subfolders.\nHelp context anywhere: /help", "В этой папке пока ничего нет" + ".\nСюда можно сложить файлы или создать поддиректории.\nПодсказка доступна в любом месте: /help"); init(Value.LANG_SWITCHED, "Switched to English", "Используется русский язык"); init(Value.SEARCHED, "Search for '%s' in '%s'", "Поиск '%s' в '%s'"); init(Value.UPLOADED, "File stored '%s'", "Файл сохранён '%s'"); init(Value.CHECK_ALL, "*", "*"); init(Value.NO_GLOBAL_LINK, "No public link", "Нет публичной ссылки"); init(Value.NO_PERSONAL_GRANTS, "No personal grants", "Нет личных приглашений"); init(Value.LINK, "Link: %s", "Ссылка: %s"); init(Value.PASS_RESET, "Reset passw", "Сбросить пароль"); init(Value.PASS_SET, "Set passw", "Установить пароль"); init(Value.PASS_DROP, "Drop passw", "Удалить пароль"); init(Value.PASSWORD_SET, "Password: _set_", "Пароль: _установлен_"); init(Value.PASSWORD_SET_TXT, "Password setted", "Пароль установлен"); init(Value.PASSWORD_NOT_SET, "Password: _not set_", "Пароль: _не установлен_"); init(Value.VALID_ONETIME, "Validity: _one time access_", "Срок действия: _одноразовая ссылка_"); init(Value.VALID_UNTILL, "Validity: _open untill %s_", "Срок действия: _ссылка действительна до %s_"); init(Value.VALID_CANCEL, "Reset validity", "Удалить срок"); init(Value.VALID_NOT_SET, "Validity: _unlimited_", "Срок действия: _без ограничений_"); init(Value.VALID_SET_OTU, "Set OneTime", "Сделать одноразовой"); init(Value.VALID_SET_UNTILL, "Set expiration", "Установить срок"); init(Value.LINK_DELETED, "Link deleted", "Ссылка удалена"); init(Value.LINK_SAVED, "Link saved", "Ссылка сохранена"); init(Value.TYPE_PASSWORD, "Type password:", "Новый пароль:"); init(Value.TYPE_PASSWORD2, "Type password again:", "Новый пароль (повтор):"); init(Value.PASSWORD_NOT_MATCH, "Password doesnt match", "Пароль не подходит"); init(Value.PASSWORD_CLEARED, "Password removed", "Пароль выключен"); init(Value.VALID_CLEARED, "Validity limit removed", "Ограничения сняты"); init(Value.OTU_SET, "Validity limited up to one time", "Ссылка ограничена одним срабатыванием"); init(Value.SEND_CONTACT_DIR, "Send me a contact or TelegramID of the person you want to grant access to folder '%s'", "Пришли мне контакт или TelegramID того, кому хочешь предоставить доступ к папке '%s'"); init(Value.SEND_CONTACT_FILE, "Send me a contact or TelegramID of the person you want to grant access to file '%s'", "Пришли мне контакт или TelegramID того, кому хочешь предоставить доступ к файлу '%s'"); init(Value.CANT_GRANT, "Access already granted to %s", "%s: доступ уже предоставлен"); init(Value.SHARE_RW, Strings.Uni.mkGrant + " %s [Read/Write]", Strings.Uni.mkGrant + " %s [полный доступ]"); init(Value.SHARE_RO, Strings.Uni.mkGrant + " %s [Read only]", Strings.Uni.mkGrant + " %s [только чтение]"); init(Value.SHARES, "Network", "Сеть"); init(Value.SHARES_ANONYM, "common", "общие"); init(Value.NOT_ALLOWED, "You're not allowed to do it here", "Это действие запрещено в текущей папке"); init(Value.NOT_ALLOWED_THIS, "You're not allowed to do it to this entry", "Это действие запрещено в для данного элемента"); init(Value.FILE_ACCESS, "Grant access to file %s", "Доступ к файлу %s"); init(Value.DIR_ACCESS, "Grant access to folder %s", "Доступ к папке %s"); init(Value.TYPE_EDIT_LABEL, "Write new text for label:", "Напиши новый текст заметки:"); init(Value.TYPE_LOCK_DIR, "Type a new password for folder '%s'", "Напиши новый пароль для папки '%s'"); init(Value.TYPE_LOCK_FILE, "Type a new password for file '%s'", "Напиши новый пароль для файла '%s'"); init(Value.TYPE_PASSWORD_FILE, "File '%s' is protected with password, type it:", "Доступ к Файлу '%s' ограничен, напиши пароль:"); init(Value.TYPE_PASSWORD_DIR, "Folder '%s' is protected with password, type it:", "Доступ к папке '%s' ограничен, напиши пароль:"); init(Value.PASSWORD_FAILED, "Wrong password", "Неверный пароль"); init(Value.SEARCH, "Book search", "Поиск книг"); init(Value.BOOKS_GENRES, "Genres", "По жанру"); init(Value.BOOKS_AUTHORS, "Authors", "По автору"); init(Value.BOOKS_ABC, "Titles", "По названию"); init(Value.OPDS_DONE, "OPDS catalog '%s' synchronization done", "Синхронизация OPDS каталога '%s' завершена"); init(Value.OPDS_STARTED, "OPDS synchronization for folder '%s' started. You'll be notified when it get done", "Синхронизация OPDS каталога '%s' начата. По завершению вы получите уведомление."); init(Value.OPDS_FAILED, "OPDS synchronization failed. Try to repeat later.", "Синхронизация с OPDS каталогом не получилась. Повтори попытку немного позже."); init(Value.WELCOME, "Welcome! All questions and discussions are here: @tfsbot_group", "Добро пожаловать! Со всеми вопросами и обсуждениями сюда пожалуйста: @tfsbot_group"); init(Value.IS_BOOK_STORE, "Folder '%s' is now your Book Store", "Теперь папка '%s' будет библиотекой"); init(Value.IS_NOT_BOOK_STORE, "Folder '%s' is not your Book Store any more", "Папка '%s' больше не будет библиотекой"); init(Value.CONFIRM_DROP_DIR, "Are you sure you want to delete folder '%s' with all its content?", "Точно удалить папку '%s' со всем содержимым?"); init(Value.CONFIRM_DROP_FILE, "Are you sure you want to delete file '%s'?", "Точно удалить файл '%s'?"); init(Value.NO_BOOKSTORE, "Before search you have to mark any folder as 'Bookstore " + Strings.Uni.bookStore + "'", "Для того, чтобы пользоваться поиском необходимо пометить какую-то (любую) папку как" + " 'библиотека " + Strings.Uni.bookStore + "'"); } private static void init(final Value key, final String en, final String ru) { enData.put(key, en); ruData.put(key, ru); } public enum Value { SEARCHED_HELP, ROOT_HELP, SHARE_FILE_HELP, GEAR_HELP, LS_HELP, FILE_HELP, LABEL_HELP, CANT_MKDIR, CANT_RN_TO, CANT_MKLBL, NO_RESULTS, TYPE_RENAME, TYPE_FOLDER, CD, PAGE, NORMAL_MODE, EDIT_MODE, DELETED, DELETED_MANY, MOVE_DEST, DESELECTED, SELECTED, MOVED, TYPE_LABEL, SEARCHED, NO_CONTENT, LANG_SWITCHED, RESULTS_FOUND, UPLOADED, None, CHECK_ALL, NO_GLOBAL_LINK, NO_PERSONAL_GRANTS, GEARING, PASS_RESET, PASS_DROP, PASSWORD_SET, PASSWORD_NOT_SET, VALID_ONETIME, VALID_UNTILL, VALID_CANCEL, VALID_NOT_SET, VALID_SET_OTU, VALID_SET_UNTILL, LINK_DELETED, LINK_SAVED, PASS_SET, TYPE_PASSWORD, TYPE_PASSWORD2, PASSWORD_SET_TXT, PASSWORD_NOT_MATCH, PASSWORD_CLEARED, VALID_CLEARED, OTU_SET, SEND_CONTACT_DIR, SEND_CONTACT_FILE, CANT_GRANT, SHARE_RW, SHARE_RO, SHARES, SHARES_ANONYM, NOT_ALLOWED, NOT_ALLOWED_THIS, LINK, FILE_ACCESS, TYPE_EDIT_LABEL, SHARE_DIR_HELP, TYPE_LOCK_DIR, TYPE_LOCK_FILE, TYPE_PASSWORD_FILE, TYPE_PASSWORD_DIR, PASSWORD_FAILED, OPDS_DONE, OPDS_STARTED, OPDS_FAILED, WELCOME, IS_NOT_BOOK_STORE, IS_BOOK_STORE, CONFIRM_DROP_FILE, CONFIRM_DROP_DIR, NO_CONTENT_START, NO_BOOKSTORE, SEARCH, BOOKS_GENRES, BOOKS_AUTHORS, BOOKS_ABC, DIR_ACCESS } public static String v(final Value name, final TUser user, final Object... args) { return v(name, notNull(user.lng, "ru"), args); } public static String v(final Value name, final String langTag, final Object... args) { try { if (name == Value.None) return ""; final String value = (langTag.equalsIgnoreCase("ru") ? ruData : enData).getOrDefault(name, name.name()); return TextUtils.isEmpty(args) ? value : String.format(value, args); } catch (final Exception ignore) {} return name.name(); } }
vugluskr/tfsbot
app/utils/LangMap.java
248,649
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * An enumerated type (not a Java Enumeration!) */ public final class SaveStatus implements java.io.Serializable { private int _value; // each instance's value private static final int _lowestValue = 1; private static int _nextToAssign = _lowestValue; // begins at lowest /** * This is the only public constructor. Each user-defined instance of a * SaveStatus must be initialized with one of the defined static values. * * @param otherSaveStatusValue must be a defined static value or another * instance. */ public SaveStatus(SaveStatus otherSaveStatusValue) { _value = otherSaveStatusValue._value; } /** * Private to class */ private SaveStatus() { _value = _nextToAssign++; } SaveStatus(int value) throws RTIinternalError { _value = value; if (value < _lowestValue || value >= _nextToAssign) throw new RTIinternalError("SaveStatus: illegal value " + value); } /** * @return String with value "SaveStatus(n)" where n is value */ @Override public String toString() { return "SaveStatus(" + _value + ")"; } /** * Allows comparison with other instance of same type. * * @return true if supplied object is of type SaveStatus and has same value; * false otherwise */ @Override public boolean equals(Object otherSaveStatusValue) { if (otherSaveStatusValue instanceof SaveStatus) return _value == ((SaveStatus) otherSaveStatusValue)._value; else return false; } @Override public int hashCode() { return _value; } static public final SaveStatus NO_SAVE_IN_PROGRESS = new SaveStatus(); static public final SaveStatus FEDERATE_INSTRUCTED_TO_SAVE = new SaveStatus(); static public final SaveStatus FEDERATE_SAVING = new SaveStatus(); static public final SaveStatus FEDERATE_WAITING_FOR_FEDERATION_TO_SAVE = new SaveStatus(); }
hla-certi/jcerti1516e
src/hla/rti1516/SaveStatus.java
248,650
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Public exception class InvalidRegion */ public final class InvalidRegion extends RTIexception { public InvalidRegion(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/InvalidRegion.java
248,651
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; import java.util.Iterator; public interface HLAhandle extends DataElement { int size(); byte get(int index); Iterator iterator(); @Override void encode(ByteWrapper byteWrapper); @Override void decode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override int getOctetBoundary(); byte[] getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAhandle.java
248,652
/* * Copyright 2015 Chidiebere Okwudire. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Original implementation adapted from Thiago Locatelli's Parse4J project * (see https://github.com/thiagolocatelli/parse4j) */ package com.parse4cn1; import ca.weblite.codename1.json.JSONArray; import ca.weblite.codename1.json.JSONObject; import com.codename1.l10n.DateFormat; import com.codename1.l10n.SimpleDateFormat; import com.codename1.ui.Display; import com.parse4cn1.operation.ParseOperationUtil; import com.parse4cn1.operation.ParseOperationDecoder; import com.parse4cn1.util.ParseRegistry; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The Parse class contains static functions, classes and interfaces that handle * global configuration for the Parse library. */ public class Parse { public enum EPlatform { IOS, ANDROID, WINDOWS_PHONE, BLACKBERRY, JAVA_ME, UNKNOWN } /** * An interface for a persistable entity. */ public interface IPersistable { /** * An object is dirty if a change has been made to it that requires it * to be persisted. * * @return {@code true} if the object is dirty; otherwise {@code false}. */ boolean isDirty(); /** * Sets the dirty flag. * * @param dirty {@code true} if the object should be marked as dirty; * otherwise {@code false}. */ void setDirty(boolean dirty); /** * Checks whether this persistable object has any data. This data may * (isDirty() = true) or may not (isDirty() = false) need to be * persisted. * * @return {@code true} if this object has data. */ boolean isDataAvailable(); /** * Saves the object. Calling this method on an object that is not dirty * should have no side effects. * * @throws ParseException if anything goes wrong during the save * operation. */ void save() throws ParseException; } /** * A factory for instantiating ParseObjects of various concrete types */ public interface IParseObjectFactory { /** * Creates a Parse object of the type matching the provided class name. * Defaults to the base ParseObject, i.e., call must always return a * non-null object. * * @param <T> The type of ParseObject to be instantiated * @param className The class name associated with type T * @return The newly created Parse object. */ <T extends ParseObject> T create(final String className); } /** * A factory for instantiating reserved Parse Object classes such as users, * roles, installations and sessions. Such a factory is used to instantiate * the correct type upon retrieval of data, for example, via a query. */ public static class DefaultParseObjectFactory implements IParseObjectFactory { public <T extends ParseObject> T create(String className) { T obj; if (ParseConstants.ENDPOINT_USERS.equals(className) || ParseConstants.CLASS_NAME_USER.equals(className)) { obj = (T) new ParseUser(); } else if (ParseConstants.ENDPOINT_ROLES.equals(className) || ParseConstants.CLASS_NAME_ROLE.equals(className)) { obj = (T) new ParseRole(); } else if (ParseConstants.CLASS_NAME_INSTALLATION.equals(className)) { obj = (T) new ParseInstallation(); } else { obj = (T) new ParseObject(className); } // TODO: Extend with other 'default' parse object subtypes // e.g. Session and Installation. return obj; } } /** * Retrieves the current platform * * @return A literal matching the current platform or * {@link EPlatform#UNKNOWN} */ public static EPlatform getPlatform() { final String platformStr = Display.getInstance().getPlatformName().toLowerCase(); EPlatform platform = EPlatform.UNKNOWN; if ("and".equals(platformStr)) { platform = EPlatform.ANDROID; } else if ("ios".equals(platformStr)) { platform = EPlatform.IOS; } else if ("me".equals(platformStr)) { platform = EPlatform.JAVA_ME; } else if ("rim".equals(platformStr)) { platform = EPlatform.BLACKBERRY; } else if ("win".equals(platformStr)) { platform = EPlatform.WINDOWS_PHONE; } return platform; } private static String mApplicationId = null; private static String mClientKey = null; private static String mApiEndpoint = null; private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); /** * Authenticates this client as belonging to your application. * <p> * It also initializes internal state required for the library to function * properly, e.g., enabling persistence to CN1 storage. * <p> * This method must be called before your application can use the Parse * library. The recommended way is to put a call to Parse.initialize in your * CN1 Application's state machine as follows: * <pre> * <code> * public class StateMachine extends StateMachineBase { * protected void initVars(Resources res) { * Parse.initialize(API_ENDPOINT, APP_ID, APP_REST_API_ID); * } * } * </code> * </pre> * * @param apiEndpoint The path to the Parse backend, e.g. * "your_parse_backend_website_url"/parse. * @param applicationId The application id of your parse backend. * @param clientKey The client key of your parse backend if applicable. If not, * pass null and it will be ignored. * <p> * <b>Note:</b> Developers are advised to use the CLIENT KEY instead of * using the REST API in production code (cf. * <a href='https://parse.com/docs/rest#general-callfromclient'>https://parse.com/docs/rest#general-callfromclient</a>). * Hence, the latter is not exposed via this library. The same security * consideration explains why the MASTER KEY is not exposed either. */ static public void initialize(String apiEndpoint, String applicationId, String clientKey) { mApiEndpoint = apiEndpoint; mApplicationId = applicationId; mClientKey = clientKey; if (mApiEndpoint != null && mApiEndpoint.endsWith("/")) { mApiEndpoint = mApiEndpoint.substring(0, mApiEndpoint.length() - 2); } ParseRegistry.registerDefaultSubClasses(); ParseRegistry.registerExternalizableClasses(); ParseOperationDecoder.registerDefaultDecoders(); /* This is a workaround to prevent the over-zealous stripping away of unused classed by the CN1 VM during iOS builds which results in a compilation error when ParsePush is not explicitly used in an app that includes this library. Apparently, the stripper has a bug that causes usage of ParsePush in iOS native code not to be detected, hence the class is stripped which subsquently results in a 'file not found' error while compiling the iOS native code that imports it. The workaround is to make the following 'harmless' call so that ParsePush is considered used and thus not stripped out during iOS compilation. See also:https://groups.google.com/d/msg/codenameone-discussions/r1svrNwVOA8/6d1QmMVfBQAJ */ ParsePush.isUnprocessedPushDataAvailable(); } /** * Retrieves the Parse API endpoint without a trailing '/'. * @return The Parse backend API endpoint if one has been set or null. * @see #initialize(java.lang.String, java.lang.String, java.lang.String) */ static public String getApiEndpoint() { return mApiEndpoint; } /** * @return The application ID if one has been set or null. * @see #initialize(java.lang.String, java.lang.String, java.lang.String) */ static public String getApplicationId() { return mApplicationId; } /** * @return The client key if one has been set or null. * @see #initialize(java.lang.String, java.lang.String, java.lang.String) */ static public String getClientKey() { return mClientKey; } /** * Checks if the library has been initialized. * <p> * <em>Note:</em> The optional client key (cf. {@link #getClientKey()}) * is no longer taken into account. * @return {@code true} if the library has been initialized; otherwise, * returns {@code false}. * @see #initialize(java.lang.String, java.lang.String, java.lang.String) */ static public boolean isInitialized() { return !(isEmpty(getApiEndpoint()) || isEmpty(getApplicationId())); } /** * Creates a valid Parse REST API URL using the predefined * {@code apiEndpoint} provided in {@link #initialize(java.lang.String, java.lang.String, java.lang.String)}. * * @param endPoint The target endpoint/class name. * @return The created URL. */ static public String getParseAPIUrl(String endPoint) { return getApiEndpoint() + "/" + (!isEmpty(endPoint) ? endPoint : ""); } /** * Encodes the provided date in the format required by Parse. * * @param date The date to be encoded. * @return {@code date} expressed in the format required by Parse. * @see <a href='https://www.parse.com/docs/rest#objects-types'>Parse date * type</a>. */ static public synchronized String encodeDate(Date date) { return dateFormat.format(date); } /** * Converts a Parse date string value into a Date object. * * @param dateString A string matching the Parse date type. * @return The date object corresponding to {@code dateString}. * @see <a href='https://www.parse.com/docs/rest#objects-types'>Parse date * type</a>. */ public static synchronized Date parseDate(String dateString) { boolean parsed = false; Date parsedDate = null; // As at July 2015, the CN1 port for Windows Phone is not quite mature // For example, using the SimpleDateFormat.format() method raises an // org.xmlvm._nNotYetImplementedException (cf. https://groups.google.com/d/topic/codenameone-discussions/LHZeubG-sf0/discussion) // As a workaround, Parse dates are manually parsed if they meet the // expected format: // // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" e.g. "2015-07-14T15:55:52.133Z" // Note that a regex-based approach is not taken because it's simply // not necessary and regexes will mean yet another cn1lib dependency. if (dateString.length() == 24) { try { int year = Integer.valueOf(dateString.substring(0, 4)); int month = Integer.valueOf(dateString.substring(5, 7)); int day = Integer.valueOf(dateString.substring(8, 10)); int hour = Integer.valueOf(dateString.substring(11, 13)); int min = Integer.valueOf(dateString.substring(14, 16)); int sec = Integer.valueOf(dateString.substring(17, 19)); int milli = Integer.valueOf(dateString.substring(20, 23)); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month - 1); // month is 0-based. cal.set(Calendar.DAY_OF_MONTH, day); cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, min); cal.set(Calendar.SECOND, sec); cal.set(Calendar.MILLISECOND, milli); parsedDate = cal.getTime(); parsed = true; } catch (NumberFormatException ex) { parsedDate = null; parsed = false; } } try { if (!parsed) { // Fallback to default and hope for the best parsedDate = dateFormat.parse(dateString); } } catch (com.codename1.l10n.ParseException e) { parsedDate = null; } return parsedDate; } /** * Checks if the provided {@code key} is a key with a special meaning in * Parse, for example {@code objectId}. * * @param key The key to be checked. * @return {@code true} if and only if {@code key} is a reserved key. */ public static boolean isReservedKey(String key) { return ParseConstants.FIELD_OBJECT_ID.equals(key) || ParseConstants.FIELD_CREATED_AT.equals(key) || ParseConstants.FIELD_UPDATED_AT.equals(key); } /** * Checks if the provided {@code endPoint} is the name of an in-built Parse * end point, for examples (users and /classes/_User). * * @param endPoint The endpoint to be checked. * @return {@code true} if {@code endPoint} is a reserved class end point. */ public static boolean isReservedEndPoint(String endPoint) { // Parse-reserved end points and classes // TODO: Extend with other endpoints when implemented. return ParseConstants.CLASS_NAME_USER.equals(endPoint) || ParseConstants.CLASS_NAME_ROLE.equals(endPoint) || ParseConstants.ENDPOINT_USERS.equals(endPoint) || ParseConstants.ENDPOINT_ROLES.equals(endPoint) || ParseConstants.ENDPOINT_SESSIONS.equals(endPoint); } /** * Checks if the provided type is a valid type for a Parse Object or any one * of its fields. * * @param value The object to be checked * @return {@code true} if {@code value} is valid as per the data types * supported by ParseObjects and their child fields. */ public static boolean isValidType(Object value) { return (value instanceof JSONObject) || (value instanceof JSONArray) || (value instanceof String) || (ParseOperationUtil.isSupportedNumberType(value) || (value instanceof Boolean) || (value == JSONObject.NULL) || (value instanceof ParseObject) || (value instanceof ParseFile) || (value instanceof ParseRelation) || (value instanceof ParseGeoPoint) || (value instanceof Date) || (value instanceof byte[]) || (value instanceof List) || (value instanceof Map)); } /** * Utility to concatenate the strings in {@code items} using the provided * {@code delimieter}. * * @param items The strings to be concatenated. * @param delimiter The delimiter. * @return The concatenated string. */ public static String join(final Collection<String> items, final String delimiter) { StringBuilder buffer = new StringBuilder(); Iterator iter = items.iterator(); if (iter.hasNext()) { buffer.append((String) iter.next()); while (iter.hasNext()) { buffer.append(delimiter); buffer.append((String) iter.next()); } } return buffer.toString(); } public static boolean isEmpty(String str) { return (str == null || str.length() == 0); } /** * Retrieves the default ID to be used for serialization of objects. * * @return A default serialization id (=1). * @see com.codename1.io.Externalizable#getVersion() */ public static int getSerializationVersion() { return 1; } }
sidiabale/parse4cn1
src/com/parse4cn1/Parse.java
248,653
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; public final class CouldNotDecode extends RTIexception { public CouldNotDecode(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/CouldNotDecode.java
248,654
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Type-safe handle for a federate handle. Generally these are created by the * RTI and passed to the user. */ public interface FederateHandle extends java.io.Serializable { /** * @return true if this refers to the same federate as other handle */ @Override boolean equals(Object otherFederateHandle); /** * @return int. All instances that refer to the same federate should return the * same hashcode. */ @Override int hashCode(); int encodedLength(); void encode(byte[] buffer, int offset); @Override String toString(); } //end FederateHandle //File: FederateHandleFactory.java
hla-certi/jcerti1516e
src/hla/rti1516/FederateHandle.java
248,655
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAboolean extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the boolean value of this element. * * @return value */ boolean getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAboolean.java
248,656
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Public exception class SaveInProgress */ public final class SaveInProgress extends RTIexception { public SaveInProgress(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/SaveInProgress.java
248,657
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; public final class OrderType implements java.io.Serializable { private int _value; // each instance's value private static final int _lowestValue = 1; private static int _nextToAssign = _lowestValue; // begins at lowest /** * This is the only public constructor. Each user-defined instance of a * OrderType must be initialized with one of the defined static values. * * @param otherOrderTypeValue must be a defined static value or another * instance. */ public OrderType(OrderType otherOrderTypeValue) { _value = otherOrderTypeValue._value; } /** * Private to class */ private OrderType() { _value = _nextToAssign++; } OrderType(int value) throws RTIinternalError { _value = value; if (value < _lowestValue || value >= _nextToAssign) throw new RTIinternalError("OrderType: illegal value " + value); } /** * @return String with value "OrderType(n)" where n is value */ @Override public String toString() { return "OrderType(" + _value + ")"; } /** * Allows comparison with other instance of same type. * * @return true if supplied object is of type OrderType and has same value; * false otherwise */ @Override public boolean equals(Object otherOrderTypeValue) { if (otherOrderTypeValue instanceof OrderType) return _value == ((OrderType) otherOrderTypeValue)._value; else return false; } @Override public int hashCode() { return _value; } public int encodedLength() { return 1; } public void encode(byte[] buffer, int offset) { buffer[offset] = (byte) _value; } public static OrderType decode(byte[] buffer, int offset) throws CouldNotDecode { int val = buffer[offset]; OrderType neo; try { neo = new OrderType(val); } catch (RTIinternalError e) { throw new CouldNotDecode(e.getMessage()); } return neo; } static public final OrderType RECEIVE = new OrderType(); static public final OrderType TIMESTAMP = new OrderType(); }
hla-certi/jcerti1516e
src/hla/rti1516/OrderType.java
248,658
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Type-safe handle for an attribute. Generally these are created by the RTI and * passed to the user. */ public interface AttributeHandle extends java.io.Serializable { /** * @return true if this refers to the same attribute as other handle */ @Override boolean equals(Object otherAttributeHandle); /** * @return int. All instances that refer to the same attribute should return the * same hashcode. */ @Override int hashCode(); int encodedLength(); void encode(byte[] buffer, int offset); @Override String toString(); } //end AttributeHandle //File: AttributeHandleFactory.java
hla-certi/jcerti1516e
src/hla/rti1516/AttributeHandle.java
248,659
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Type-safe handle for a parameter. Generally these are created by the RTI and * passed to the user. */ public interface ParameterHandle extends java.io.Serializable { /** * @return true if this refers to the same parameter as other handle */ @Override boolean equals(Object otherParameterHandle); /** * @return int. All instances that refer to the same parameter should return the * same hascode. */ @Override int hashCode(); int encodedLength(); void encode(byte[] buffer, int offset); @Override String toString(); } //end ParameterHandle //File: ParameterHandleFactory.java
hla-certi/jcerti1516e
src/hla/rti1516/ParameterHandle.java
248,660
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; public interface DataElement { /** * Returns the octet boundary of this element. * * @return */ int getOctetBoundary(); /** * Encodes this element into the specified ByteWrapper. * * @param byteWrapper */ void encode(ByteWrapper byteWrapper); /** * Returns the size in bytes of this element's encoding. * * @return size */ int getEncodedLength(); /** * Returns a byte array with this element encoded. * * @return byte array with encoded element */ byte[] toByteArray(); /** * Decodes this element from the ByteWrapper. * * @param byteWrapper */ void decode(ByteWrapper byteWrapper); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/DataElement.java
248,661
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * All Set operations are required, none are optional. add() and remove() should * throw IllegalArgumentException if the argument is not a RegionHandle. * addAll(), removeAll() and retainAll() should throw IllegalArgumentException * if the argument is not a RegionHandleSet */ public interface RegionHandleSet extends java.util.Set, Cloneable, java.io.Serializable { } //end RegionHandleSet //File: RegionHandleSetFactory.java
hla-certi/jcerti1516e
src/hla/rti1516/RegionHandleSet.java
248,662
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; public final class TimeQueryReturn implements java.io.Serializable { public TimeQueryReturn(boolean tiv, LogicalTime lt) { timeIsValid = tiv; time = lt; } public boolean timeIsValid; public LogicalTime time; @Override public boolean equals(Object other) { if (other instanceof TimeQueryReturn) { TimeQueryReturn tqrOther = (TimeQueryReturn) other; if (timeIsValid == false && tqrOther.timeIsValid == false) { return true; } else if (timeIsValid == true && tqrOther.timeIsValid == true) { return time.equals(tqrOther.time); } else { return false; } } else { return false; } } @Override public int hashCode() { return (timeIsValid ? time.hashCode() : 7); } @Override public String toString() { return "" + timeIsValid + " " + time; } } //end TimeQueryReturn
hla-certi/jcerti1516e
src/hla/rti1516/TimeQueryReturn.java
248,663
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Public exception class CouldNotOpenFDD */ public final class CouldNotOpenFDD extends RTIexception { public CouldNotOpenFDD(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/CouldNotOpenFDD.java
248,664
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Type-safe handle for a dimension. Generally these are created by the RTI and * passed to the user. */ public interface DimensionHandle extends java.io.Serializable { /** * @return true if this refers to the same dimension as other handle */ @Override boolean equals(Object otherDimensionHandle); /** * @return int. All instances that refer to the same dimension should return the * same hascode. */ @Override int hashCode(); int encodedLength(); void encode(byte[] buffer, int offset); @Override String toString(); } //end DimensionHandle //File: DimensionHandleFactory.java
hla-certi/jcerti1516e
src/hla/rti1516/DimensionHandle.java
248,665
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Public exception class ErrorReadingFDD */ public final class ErrorReadingFDD extends RTIexception { public ErrorReadingFDD(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/ErrorReadingFDD.java
248,667
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAASCIIchar extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the byte value of this element. * * @return value */ byte getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAASCIIchar.java
248,668
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAfloat32LE extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the float value of this element. * * @return float value */ float getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAfloat32LE.java
248,669
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAfloat64LE extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the double value of this element. * * @return double value */ double getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAfloat64LE.java
248,670
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * * Public exception class SaveNotInitiated * */ public final class SaveNotInitiated extends RTIexception { public SaveNotInitiated(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/SaveNotInitiated.java
248,671
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAfloat64BE extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the double value of this element. * * @return double value */ double getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAfloat64BE.java
248,672
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * * Public exception class InvalidLookahead * */ public final class InvalidLookahead extends RTIexception { public InvalidLookahead(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/InvalidLookahead.java
248,673
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * * Public exception class CouldNotDiscover * */ public final class CouldNotDiscover extends RTIexception { public CouldNotDiscover(String msg) { super(msg); } }
hla-certi/jcerti1516e
src/hla/rti1516/CouldNotDiscover.java
248,674
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * Public exception class RTIinternalError. This is deliberately not a final * class. */ public class RTIinternalError extends RTIexception { public RTIinternalError(String msg) { super(msg); } } //File: RangeBounds.java /** * Record returned by (10.31) getRangeBounds */
hla-certi/jcerti1516e
src/hla/rti1516/RTIinternalError.java
248,675
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * All Set operations are required, none are optional. add() and remove() should * throw IllegalArgumentException if the argument is not a FederateHandleHandle. * addAll(), removeAll() and retainAll() should throw IllegalArgumentException * if the argument is not a FederateHandleSet */ public interface FederateHandleSet extends java.util.Set, java.io.Serializable, Cloneable { } //end FederateHandleSet //File: FederateHandleSetFactory.java
hla-certi/jcerti1516e
src/hla/rti1516/FederateHandleSet.java
248,676
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; import java.util.Iterator; public interface HLAopaqueData extends DataElement { int size(); byte get(int index); Iterator iterator(); @Override void encode(ByteWrapper byteWrapper); @Override void decode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override int getOctetBoundary(); byte[] getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAopaqueData.java
248,677
package swisseph; /** * This class implements a TransitCalculator for two planets * in relative positions or speeds to each other.<p> * You would create a TransitCalculator from this class and * use the SwissEph.getTransit() methods to actually calculate * a transit, e.g.:<p> * <pre> * SwissEph sw = new SwissEph(...); * ... * int flags = SweConst.SEFLG_SWIEPH | * SweConst.SEFLG_TRANSIT_LONGITUDE; * boolean backwards = true; * * TransitCalculator tc = new TCPlanetPlanet( * sw, * SweConst.SE_MERCURY, * SweConst.SE_VENUS, * flags, * 0); * ... * double nextTransitUT = sw.getTransitUT(tc, jdUT, backwards); * </pre> * This would calculate the last (UT-) date, when Mercury and Venus * had the same longitudinal position. */ public class TCPlanetPlanet extends TransitCalculator implements java.io.Serializable { int precalcCount = 50; private int pl1, pl2; private int idx = 0; // The index into the xx[] array in swe_calc() to use: private int tflags = 0; // The transit flags private int flags = 0; // The calculation flags for swe_calc() private boolean calcPartile = false; private boolean calcNonPartile = false; private boolean calcPartileBoth = false; private boolean isPartile = false; private boolean calcYoga = false; private double minSpeed1, maxSpeed1; private double minSpeed2, maxSpeed2; private double minSpeed, maxSpeed; // The y = f(x) value to reach, speaking mathematically... private double offset = 0.; private double lon1=0, lon2=-1000; // For partile aspects only double minVal = 0., maxVal = 0.; // Thinking about it... /** * Creates a new TransitCalculator for relative transits of two different * planets to each other with the option for transits over longitudes, * latitudes, distance or the speed in any of these directions in the * geocentric or topocentric coordinate system, and in tropical or sidereal * zodiac system, both with the sum and difference of both planets positions * and speeds.<p> * Calculation of partile transits is possible now, but it's still a * rather slow calculation and not finally tested.<p> * @param sw A SwissEph object, if you have one available. May be null. * @param pl1 The planet number of the first planet.<br> * Planets from SweConst.SE_SUN up to SweConst.SE_INTP_PERG (with the * exception of SweConst.SE_EARTH) have their extreme speeds saved, so * these extreme speeds will be used on calculation.<br>Other objects * calculate extreme speeds by randomly calculating by default 200 speed * values and multiply them by 1.4 as a safety factor.<br> * ATTENTION: be sure to understand that you might be able to miss some * transit or you might get a rather bad transit time in very rare * circumstances.<br> * Use SweConst.SE_AST_OFFSET + asteroid number for planets with a * planet number not defined by SweConst.SEFLG_*. * @param pl2 The second planet that will be transited by the first planet. * @param flags The calculation type flags (SweConst.SEFLG_TRANSIT_LONGITUDE, * SweConst.SEFLG_TRANSIT_LATITUDE or SweConst.SEFLG_TRANSIT_DISTANCE in * conjunction with SweConst.SEFLG_TRANSIT_SPEED for transits over a speed * value).<br><br> * Also flags modifying the basic planet calculations, these are * SweConst.SEFLG_TOPOCTR, SweConst.SEFLG_EQUATORIAL, SweConst.SEFLG_HELCTR, * SweConst.SEFLG_TRUEPOS, and SweConst.SEFLG_SIDEREAL, plus the ephemeris * flags SweConst.SEFLG_MOSEPH, SweConst.SEFLG_SWIEPH or * SweConst.SEFLG_JPLEPH optionally. * <br>For <i>right ascension</i> use <code>SEFLG_TRANSIT_LONGITUDE | SEFLG_EQUATORIAL</code>, * for <i>declination</i> <code>SEFLG_TRANSIT_LATITUDE | SEFLG_EQUATORIAL</code>.<br><br> * SEFLG_PARTILE_TRANSIT will calculate the next time, when the planets will * have a partile aspect to each other, if they don't have a partile aspect * now. If they do have a partile aspect now, it calculates the next time, * when this partile aspect gets lost.<br> * @param offset This is the desired transit degree or distance in AU or transit speed * in deg/day. * @see swisseph.TCPlanetPlanet#TCPlanetPlanet(SwissEph, int, int, int, double, int, double) * @see swisseph.TCPlanet#TCPlanet(SwissEph, int, int, double) * @see swisseph.TCPlanet#TCPlanet(SwissEph, int, int, double, int, double) * @see swisseph.SweConst#SEFLG_TRANSIT_LONGITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_LATITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_DISTANCE * @see swisseph.SweConst#SEFLG_TRANSIT_SPEED * @see swisseph.SweConst#SE_AST_OFFSET * @see swisseph.SweConst#SEFLG_PARTILE_TRANSIT * @see swisseph.SweConst#SEFLG_PARTILE_TRANSIT_START * @see swisseph.SweConst#SEFLG_PARTILE_TRANSIT_END * @see swisseph.SweConst#SEFLG_YOGA_TRANSIT * @see swisseph.SweConst#SEFLG_TOPOCTR * @see swisseph.SweConst#SEFLG_EQUATORIAL * @see swisseph.SweConst#SEFLG_HELCTR * @see swisseph.SweConst#SEFLG_TRUEPOS * @see swisseph.SweConst#SEFLG_SIDEREAL * @see swisseph.SweConst#SEFLG_MOSEPH * @see swisseph.SweConst#SEFLG_SWIEPH * @see swisseph.SweConst#SEFLG_JPLEPH */ public TCPlanetPlanet(SwissEph sw, int pl1, int pl2, int flags, double offset) { this(sw, pl1, pl2, flags, offset, 200, 1.4); } /** * Creates a new TransitCalculator for relative transits of two different * planets to each other with the option for transits over longitudes, * latitudes, distance or the speed in any of these directions in the * geocentric or topocentric coordinate system, and in tropical or sidereal * zodiac system, both with the sum and difference of both planets positions * and speeds.<p> * Calculation of partile transits is possible now, but it's still a * rather slow calculation and not finally tested.<p> * @param sw A SwissEph object, if you have one available. May be null. * @param pl1 The planet number of the first planet.<br> * Planets from SweConst.SE_SUN up to SweConst.SE_INTP_PERG (with the * exception of SweConst.SE_EARTH) have their extreme speeds saved, so * these extreme speeds will be used on calculation.<br>Other objects * calculate extreme speeds by randomly calculating by default 200 speed * values and multiply them by 1.4 as a safety factor.<br> * ATTENTION: be sure to understand that you might be able to miss some * transit or you might get a rather bad transit time in very rare * circumstances.<br> * Use SweConst.SE_AST_OFFSET + asteroid number for planets with a * planet number not defined by SweConst.SEFLG_*. * @param pl2 The second planet that will be transited by the first planet. * @param flags The calculation type flags (SweConst.SEFLG_TRANSIT_LONGITUDE, * SweConst.SEFLG_TRANSIT_LATITUDE or SweConst.SEFLG_TRANSIT_DISTANCE in * conjunction with SweConst.SEFLG_TRANSIT_SPEED for transits over a speed * value, and SweConst.SEFLG_YOGA_TRANSIT to calculate for the SUM of the * two positions or speeds instead of the difference plus * SweConst.SEFLG_PARTILE_TRANSIT, SweConst.SEFLG_PARTILE_TRANSIT_START or * SweConst.SEFLG_PARTILE_TRANSIT_END to calculate partile aspects).<br><br> * Also flags modifying the basic planet calculations, these are * SweConst.SEFLG_TOPOCTR, SweConst.SEFLG_EQUATORIAL, SweConst.SEFLG_HELCTR, * SweConst.SEFLG_TRUEPOS, and SweConst.SEFLG_SIDEREAL, plus the (optional) * ephemeris flags SweConst.SEFLG_MOSEPH, SweConst.SEFLG_SWIEPH or * SweConst.SEFLG_JPLEPH. * <br><br>For <i>right ascension</i> use <code>SEFLG_TRANSIT_LONGITUDE | SEFLG_EQUATORIAL</code>, * for <i>declination</i> <code>SEFLG_TRANSIT_LATITUDE | SEFLG_EQUATORIAL</code>.<br><br> * SEFLG_PARTILE_TRANSIT will calculate the next time, when the planets will * have a partile aspect to each other, if they don't have a partile aspect * now. If they do have a partile aspect now, it calculates the next time, * when this partile aspect gets lost.<br> * @param offset This is an offset to the exact conjunction transit point. * E.g., when the offset is 180 for longitude calculations, you will get the * dates, when the two planets are opposite to each other. Note: The offset * is related to the FIRST planet, so an offset value of 30 degree will find * the transit points, when the FIRST planet will be 30 degrees after the * position of the second planet.<br> * Specify the desired transit degree or distance (in AU) or transit speed (in * deg/day). * @see swisseph.TCPlanetPlanet#TCPlanetPlanet(SwissEph, int, int, int, double) * @see swisseph.TCPlanet#TCPlanet(SwissEph, int, int, double) * @see swisseph.TCPlanet#TCPlanet(SwissEph, int, int, double, int, double) * @see swisseph.SweConst#SEFLG_TRANSIT_LONGITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_LATITUDE * @see swisseph.SweConst#SEFLG_TRANSIT_DISTANCE * @see swisseph.SweConst#SEFLG_TRANSIT_SPEED * @see swisseph.SweConst#SEFLG_PARTILE_TRANSIT * @see swisseph.SweConst#SEFLG_PARTILE_TRANSIT_START * @see swisseph.SweConst#SEFLG_PARTILE_TRANSIT_END * @see swisseph.SweConst#SEFLG_YOGA_TRANSIT * @see swisseph.SweConst#SE_AST_OFFSET * @see swisseph.SweConst#SEFLG_TOPOCTR * @see swisseph.SweConst#SEFLG_EQUATORIAL * @see swisseph.SweConst#SEFLG_HELCTR * @see swisseph.SweConst#SEFLG_TRUEPOS * @see swisseph.SweConst#SEFLG_SIDEREAL * @see swisseph.SweConst#SEFLG_MOSEPH * @see swisseph.SweConst#SEFLG_SWIEPH * @see swisseph.SweConst#SEFLG_JPLEPH */ public TCPlanetPlanet(SwissEph sw, int pl1, int pl2, int flags, double offset, int precalcCount, double precalcSafetyfactor) { this.sw = sw; if (this.sw == null) { this.sw = new SwissEph(); } // Check parameter: ////////////////////////////////////////////////////// // List of all valid flags: this.tflags = flags; int vFlags = SweConst.SEFLG_EPHMASK | SweConst.SEFLG_TOPOCTR | SweConst.SEFLG_EQUATORIAL | SweConst.SEFLG_HELCTR | SweConst.SEFLG_NOABERR | SweConst.SEFLG_NOGDEFL | SweConst.SEFLG_SIDEREAL | SweConst.SEFLG_TRUEPOS | SweConst.SEFLG_PARTILE_TRANSIT | SweConst.SEFLG_PARTILE_TRANSIT_START | SweConst.SEFLG_PARTILE_TRANSIT_END | SweConst.SEFLG_YOGA_TRANSIT | SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE | SweConst.SEFLG_TRANSIT_SPEED; // NOABERR and NOGDEFL is allowed for HELCTR, as they get set // anyway. if ((flags & SweConst.SEFLG_HELCTR) != 0) { vFlags |= SweConst.SEFLG_NOABERR | SweConst.SEFLG_NOGDEFL; } if ((flags&~vFlags) != 0) { throw new IllegalArgumentException("Invalid flag(s): "+(flags&~vFlags)); } // Allow only one of SEFLG_TRANSIT_LONGITUDE, SEFLG_TRANSIT_LATITUDE, SEFLG_TRANSIT_DISTANCE: int type = flags&(SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE); if (type != SweConst.SEFLG_TRANSIT_LONGITUDE && type != SweConst.SEFLG_TRANSIT_LATITUDE && type != SweConst.SEFLG_TRANSIT_DISTANCE) { throw new IllegalArgumentException("Invalid flag combination '" + flags + "': specify exactly one of SEFLG_TRANSIT_LONGITUDE (" + SweConst.SEFLG_TRANSIT_LONGITUDE + "), SEFLG_TRANSIT_LATITUDE (" + SweConst.SEFLG_TRANSIT_LATITUDE + "), SEFLG_TRANSIT_DISTANCE (" + SweConst.SEFLG_TRANSIT_DISTANCE + ")."); } if ((flags & SweConst.SEFLG_HELCTR) != 0 && (pl1 == SweConst.SE_MEAN_APOG || pl1 == SweConst.SE_OSCU_APOG || pl1 == SweConst.SE_MEAN_NODE || pl1 == SweConst.SE_TRUE_NODE)) { throw new IllegalArgumentException( "Unsupported planet number " + pl1 + " (" + sw.swe_get_planet_name(pl1) + ") for heliocentric " + "calculations"); } if ((flags & SweConst.SEFLG_HELCTR) != 0 && (pl2 == SweConst.SE_MEAN_APOG || pl2 == SweConst.SE_OSCU_APOG || pl2 == SweConst.SE_MEAN_NODE || pl2 == SweConst.SE_TRUE_NODE)) { throw new IllegalArgumentException( "Unsupported planet number " + pl2 + " (" + sw.swe_get_planet_name(pl2) + ") for heliocentric " + "calculations"); } if (pl1 == pl2) { throw new IllegalArgumentException( "Transiting and referred planet have to be different!"); } this.pl1 = pl1; this.pl2 = pl2; calcPartile = ((flags & SweConst.SEFLG_PARTILE_TRANSIT_START) != 0); // Included in partileBoth calcNonPartile = ((flags & SweConst.SEFLG_PARTILE_TRANSIT_END) != 0); // Included in partileBoth calcPartileBoth = (calcPartile && calcNonPartile); calcYoga = ((flags & SweConst.SEFLG_YOGA_TRANSIT) != 0); // The index into the xx[] array in swe_calc() to use: if ((flags&SweConst.SEFLG_TRANSIT_LATITUDE) != 0) { // Calculate latitudinal transits idx = 1; } else if ((flags&SweConst.SEFLG_TRANSIT_DISTANCE) != 0) { // Calculate distance transits idx = 2; } if ((flags&SweConst.SEFLG_TRANSIT_SPEED) != 0) { // Calculate speed transits idx += 3; flags |= SweConst.SEFLG_SPEED; } // Eliminate SEFLG_TRANSIT_* flags for use in swe_calc(): flags &= ~(SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE | SweConst.SEFLG_PARTILE_TRANSIT | SweConst.SEFLG_PARTILE_TRANSIT_START | SweConst.SEFLG_PARTILE_TRANSIT_END | SweConst.SEFLG_YOGA_TRANSIT | SweConst.SEFLG_TRANSIT_SPEED); this.flags = flags; // Calculate basic parameters: /////////////////////////////////////////// rollover = (idx == 0); if (calcPartile || calcNonPartile) { if ((offset % 30) != 0) { throw new IllegalArgumentException( "Wrong offset (" + offset + "). Calculation of partile aspect may have offsets of multiples of 30 degrees only."); } rollover = false; } this.offset = checkOffset(offset); maxSpeed1=getSpeed(false,pl1); minSpeed1=getSpeed(true,pl1); maxSpeed2=getSpeed(false,pl2); minSpeed2=getSpeed(true,pl2); if (Double.isInfinite(maxSpeed1) || Double.isInfinite(minSpeed1)) { // Trying to find some reasonable min- and maxSpeed by randomly testing some speed values. // Limited to ecliptical(?) non-speed calculations so far: if (idx < 3) { double[] minmax = getTestspeed(pl1, idx, precalcCount, precalcSafetyfactor); minSpeed1 = minmax[0]; maxSpeed1 = minmax[1]; } } //System.err.println("speeds: " + minSpeed1 + " - " + maxSpeed1); if (Double.isInfinite(maxSpeed1) || Double.isInfinite(minSpeed1)) { throw new IllegalArgumentException( ((flags&SweConst.SEFLG_TOPOCTR)!=0?"Topo":((flags&SweConst.SEFLG_HELCTR)!=0?"Helio":"Geo")) + "centric transit calculations with planet number " + pl1 + " ("+ sw.swe_get_planet_name(pl1) + ") not possible: extreme " + ((flags & SweConst.SEFLG_SPEED) != 0 ? "accelerations" : "speeds") + " of the planet " + ((flags & SweConst.SEFLG_EQUATORIAL) != 0 ? "in equatorial system " : "") + "not available."); } if (Double.isInfinite(maxSpeed2) || Double.isInfinite(minSpeed2)) { // Trying to find some reasonable min- and maxSpeed by randomly testing some speed values. // Limited to ecliptical(?) non-speed calculations so far: if (idx < 3) { double[] minmax = getTestspeed(pl2, idx, precalcCount, precalcSafetyfactor); minSpeed2 = minmax[0]; maxSpeed2 = minmax[1]; } } //System.err.println("speeds: " + minSpeed2 + " - " + maxSpeed2); if (Double.isInfinite(maxSpeed2) || Double.isInfinite(minSpeed2)) { throw new IllegalArgumentException( ((flags&SweConst.SEFLG_TOPOCTR)!=0?"Topo":((flags&SweConst.SEFLG_HELCTR)!=0?"Helio":"Geo")) + "centric transit calculations with planet number " + pl2 + " ("+ sw.swe_get_planet_name(pl2) + ") not possible: extreme " + ((flags & SweConst.SEFLG_SPEED) != 0 ? "accelerations" : "speeds") + " of the planet " + ((flags & SweConst.SEFLG_EQUATORIAL) != 0 ? "in equatorial system " : "") + "not available."); } if (calcYoga) { minSpeed = minSpeed1+minSpeed2; maxSpeed = maxSpeed1+maxSpeed2; } else { if (rollover) { minSpeed = (maxSpeed1>maxSpeed2)?minSpeed1-maxSpeed2:minSpeed2-maxSpeed1; maxSpeed = (maxSpeed1>maxSpeed2)?maxSpeed1-minSpeed2:maxSpeed2-minSpeed1; } else { minSpeed = SMath.min(minSpeed1-maxSpeed2, minSpeed2-maxSpeed1); maxSpeed = SMath.max(maxSpeed1-minSpeed2, maxSpeed2-minSpeed1); } } } // Looks for next time when the condition (partile / non-partile) is NOT met, // so we have a starting point for partile / non-partile calculation: double preprocessDate(double jdET, boolean back) { if (calcPartile || calcNonPartile) { // Check the current partile status: isPartile = hasPartileAspect(jdET, pl1, pl2, flags, offset); if (!calcPartileBoth) { if (isPartile && calcPartile) { // Set next non partile date as starting date int flgs = flags & ~SweConst.SEFLG_PARTILE_TRANSIT_START; flgs |= SweConst.SEFLG_PARTILE_TRANSIT_END | SweConst.SEFLG_TRANSIT_LONGITUDE; TransitCalculator tc = new TCPlanetPlanet( sw, pl1, pl2, flgs, offset); jdET = sw.getTransitET(tc, jdET, back); isPartile = !isPartile; } else if (!isPartile && calcNonPartile) { // Set next partile date as starting date int flgs = flags & ~SweConst.SEFLG_PARTILE_TRANSIT_END; flgs |= SweConst.SEFLG_PARTILE_TRANSIT_START | SweConst.SEFLG_TRANSIT_LONGITUDE; TransitCalculator tc = new TCPlanetPlanet( sw, pl1, pl2, flgs, offset); jdET = sw.getTransitET(tc, jdET, back); isPartile = !isPartile; } } } return jdET; } /** * @return Returns true, if one position value is identical to another * position value. E.g., 360 degree is identical to 0 degree in * circle angles. * @see #rolloverVal */ public boolean getRollover() { return rollover; } /** * This sets the transit degree or other transit value for the difference * or sum of the positions or speeds of both planets. It will be used on * the next call to getTransit(). * @param value The offset value. * @see #getOffset() */ public void setOffset(double value) { offset = checkOffset(value); } /** * This returns the transit degree or other transit value of the relative * position or speed of the two planets. * @return The current offset value. * @see #setOffset(double) */ public double getOffset() { return offset; } /** * This returns the two planet numbers involved as Strings. * @return An array of identifiers identifying the calculated objects. */ public Object[] getObjectIdentifiers() { return new Object[]{"" + pl1, "" + pl2}; } /** * Checks if the two planets have a partile aspect. */ public boolean hasPartileAspect(double jdET, int p1, int p2, int flgs, double offset) { StringBuffer serr = new StringBuffer(); double[] xx1 = new double[6], xx2 = new double[6]; offset = (int)offset; flgs &= ~(SweConst.SEFLG_TRANSIT_LONGITUDE | SweConst.SEFLG_TRANSIT_LATITUDE | SweConst.SEFLG_TRANSIT_DISTANCE | SweConst.SEFLG_PARTILE_TRANSIT | SweConst.SEFLG_PARTILE_TRANSIT_START | SweConst.SEFLG_PARTILE_TRANSIT_END | SweConst.SEFLG_YOGA_TRANSIT | SweConst.SEFLG_TRANSIT_SPEED); int ret = sw.swe_calc(jdET, p1, flgs, xx1, serr); if (ret<0) { throw new SwissephException(jdET, SwissephException.UNDEFINED_ERROR, "Calculation failed with return code " + ret + ":\n" + serr.toString()); } ret = sw.swe_calc(jdET, p2, flgs, xx2, serr); if (ret<0) { throw new SwissephException(jdET, SwissephException.UNDEFINED_ERROR, "Calculation failed with return code " + ret + ":\n" + serr.toString()); } return (int)(xx1[0]%30) == (int)(xx2[0]%30) && ((((int)(xx1[0]) + offset + rolloverVal) % rolloverVal == (int)xx2[0]) || (((int)(xx1[0]) - offset + rolloverVal) % rolloverVal == (int)xx2[0])); } /////////////////////////////////////////////////////////////////////////////// protected double getMaxSpeed() { return maxSpeed; } protected double getMinSpeed() { return minSpeed; } protected double calc(double jdET) { StringBuffer serr = new StringBuffer(); double[] xx1 = new double[6]; double[] xx2 = new double[6]; int ret = sw.swe_calc(jdET, pl1, flags, xx1, serr); if (ret<0) { int type = SwissephException.UNDEFINED_ERROR; if (serr.toString().matches("jd 2488117.1708818264 > Swiss Eph. upper limit 2487932.5;")) { type = SwissephException.BEYOND_USER_TIME_LIMIT; } System.err.println("SERR: " + serr); throw new SwissephException(jdET, type, "Calculation failed with return code " + ret + ":\n" + serr.toString()); } ret = sw.swe_calc(jdET, pl2, flags, xx2, serr); if (ret<0) { int type = SwissephException.UNDEFINED_ERROR; if (serr.toString().matches("jd 2488117.1708818264 > Swiss Eph. upper limit 2487932.5;")) { type = SwissephException.BEYOND_USER_TIME_LIMIT; } throw new SwissephException(jdET, type, "Calculation failed with return code " + ret + ":\n" + serr.toString()); } if (calcPartile || calcNonPartile) { lon1 = xx1[0]; lon2 = xx2[0]; double delta1, delta2, delta3, delta4; double target1 = ((int)(lon1) + offset + rolloverVal) % rolloverVal; double target2 = ((int)(lon1) - offset + rolloverVal) % rolloverVal; double target3 = ((int)(lon2) + offset + rolloverVal) % rolloverVal; double target4 = ((int)(lon2) - offset + rolloverVal) % rolloverVal; if (lon2 > target1) { delta1 = SMath.abs(lon2 - target1 - 1 + 1E-9); // Might be better to use a different comparison operator instead of '+ 1E-9'...? } else { delta1 = target1 - lon2; } if (lon2 > target2) { delta2 = SMath.abs(lon2 - target2 - 1 + 1E-9); } else { delta2 = target2 - lon2; } if (lon1 > target3) { delta3 = SMath.abs(lon1 - target3 - 1 + 1E-9); } else { delta3 = target3 - lon1; } if (lon1 > target4) { delta4 = SMath.abs(lon1 - target4 - 1 + 1E-9); } else { delta4 = target4 - lon1; } double diff = SMath.min(SMath.min(SMath.min(delta1, delta2), delta3), delta4) % 1; // Using '%1', as I don't get the next degree value, where these planets will be partile (on calcPartile?). if ((!isPartile && calcPartile && diff == 0) || (isPartile && calcNonPartile && diff != 0)) { return offset; } if (((int)xx1[idx] - (int)xx2[idx] + rolloverVal) %rolloverVal - offset == 0 || ((int)xx2[idx] - (int)xx1[idx] + rolloverVal) %rolloverVal - offset == 0) { return Double.POSITIVE_INFINITY; // Means: found, but don't interpolate with previous values } return ((xx1[idx] % rolloverVal) - (xx2[idx] % rolloverVal) + rolloverVal) % rolloverVal; } else if (calcYoga) { return xx1[idx] + xx2[idx]; } return xx1[idx] - xx2[idx]; } protected double getTimePrecision(double degPrec) { // Recalculate degPrec to mean the minimum time, in which the planet can // possibly move that degree: double amin = SMath.min(SMath.abs(minSpeed1),SMath.abs(minSpeed2)); double amax = SMath.min(SMath.abs(maxSpeed1),SMath.abs(maxSpeed2)); double maxVal = SMath.max(SMath.abs(amin),SMath.abs(amax)); if (maxVal != 0.) { return degPrec / maxVal; } return 1E-9; } protected double getDegreePrecision(double jd) { // Calculate the planet's minimum movement regarding the maximum available // precision. // // For all calculations, we assume the following minimum exactnesses // based on the discussions on http://www.astro.com/swisseph, even though // these values are nothing more than very crude estimations which should // leave us on the save side always, even more, when seeing that we always // consider the maximum possible speed / acceleration of a planet in the // transit calculations and not the real speed. // // Take degPrec to be the minimum exact degree in longitude double degPrec = 0.005; if (idx>2) { // Speed // "The speed precision is now better than 0.002" for all planets" degPrec = 0.002; } else { // Degrees // years 1980 to 2099: 0.005" // years before 1980: 0.08" (from sun to jupiter) // years 1900 to 1980: 0.08" (from saturn to neptune) (added: nodes) // years before 1900: 1" (from saturn to neptune) (added: nodes) // years after 2099: same as before 1900 // if (pl1>=SweConst.SE_SUN && pl1<=SweConst.SE_JUPITER) { if (jd<1980 || jd>2099) { degPrec = 0.08; } } else { if (jd>=1900 && jd<1980) { degPrec = 0.08; } else if (jd<1900 || jd>2099) { // Unclear about true nodes... degPrec = 1; } } if (pl2>=SweConst.SE_SUN && pl2<=SweConst.SE_JUPITER) { if (jd<1980 || jd>2099) { degPrec = SMath.max(0.08,degPrec); } } else { if (jd>=1900 && jd<1980) { degPrec = SMath.max(0.08,degPrec); } else if (jd<1900 || jd>2099) { // Unclear about true nodes... degPrec = SMath.max(1,degPrec); } } } degPrec/=3600.; degPrec*=0.5; // We take the precision to be BETTER THAN ... as it is stated somewhere // We recalculate these degrees to the minimum time difference that CAN // possibly give us data differing more than the above given precision. switch (idx) { case 0: // Longitude case 1: // Latitude case 3: // Speed in longitude case 4: // Speed in latitude break; case 2: // Distance case 5: // Speed in distance // We need to recalculate the precision in degrees to a distance value. // For this we need the maximum distance to the centre of calculation, // which is the barycentre for the main planets. double dp1, dp2; if (pl1 >= sw.ext.maxBaryDist.length) { dp1 = 0.05; // Rather random value??? } else { dp1 = sw.ext.maxBaryDist[pl1]; } if (pl2 >= sw.ext.maxBaryDist.length) { dp2 = 0.05; // Rather random value??? } else { dp2 = sw.ext.maxBaryDist[pl2]; } degPrec *= SMath.max(dp1, dp2); } return degPrec; // Barycentre: // 0.981683040 1.017099581 (Barycenter of the earth!) // Sun: 0.982747149 AU 1.017261973 AU // Moon: 0.980136691 AU 1.019846623 AU // Mercury: 0.307590579 AU 0.466604085 AU // Venus: 0.717960758 AU 0.728698831 AU // Mars: 1.382830768 AU 0.728698831 AU // Jupiter: 5.448547595 AU 4.955912195 AU // Saturn: 10.117683425 AU 8.968685733 AU // Uranus: 18.327870391 AU 19.893326756 AU // Neptune: 29.935653168 AU 30.326750627 AU // Pluto: 29.830132096 AU 41.499626899 AU // MeanNode: 0.002569555 AU 0.002569555 AU // TrueNode: 0.002361814 AU 0.002774851 AU // // Minimum and maximum (barycentric) distances: // Sun: 0.000095 AU 0.01034 AU // Moon: 0.972939 AU 1.02625 AU // Mercury: 0.298782 AU 0.47569 AU // Venus: 0.709190 AU 0.73723 AU // Mars: 1.370003 AU 1.67685 AU // Jupiter: 4.912031 AU 5.47705 AU // Saturn: 8.948669 AU 10.13792 AU // Uranus: 18.257511 AU 20.12033 AU // Neptune: 29.780622 AU 30.36938 AU // Pluto: 29.636944 AU 49.43648 AU // MeanNode: - AU - AU ? // TrueNode: - AU - AU ? // Maximum and minimum (geocentric) distances: // Sun: 1.016688129 AU 0.983320477 AU // Moon: 0.002710279 AU 0.002439921 AU // Mercury: 0.549188094 AU 1.448731236 AU // Saturn: 7.84 / 7.85 AU 11.25/11.26 AU // Uranus: 21.147/21.148 AU AU } ////////////////////////////////////////////////////////////////////////////// private double checkOffset(double val) { // Similar rollover considerations for the latitude will be necessary, if // swe_calc() would return latitudinal values beyond -90 and +90 degrees. if (rollover) { // Longitude from 0 to 360 degrees: while (val < 0.) { val += rolloverVal; } val %= rolloverVal; minVal = 0.; maxVal = rolloverVal; } else if (idx == 1) { // Latitude from -90 to +90 degrees: while (val < -90.) { val += 180.; } while (val > 90.) { val -= 180.; } minVal = -90.; maxVal = +90.; } return val; } private double getSpeed(boolean min, int planet) { boolean lon = ((tflags&SweConst.SEFLG_TRANSIT_LONGITUDE) != 0); boolean lat = ((tflags&SweConst.SEFLG_TRANSIT_LATITUDE) != 0); boolean dist = ((tflags&SweConst.SEFLG_TRANSIT_DISTANCE) != 0); boolean speed = ((tflags&SweConst.SEFLG_TRANSIT_SPEED) != 0); boolean topo = ((tflags&SweConst.SEFLG_TOPOCTR) != 0); boolean helio = ((tflags&SweConst.SEFLG_HELCTR) != 0); boolean rect = ((tflags&SweConst.SEFLG_EQUATORIAL) != 0 && !lat && !dist); boolean decl = ((tflags&SweConst.SEFLG_EQUATORIAL) != 0 && lat); try { // Some topocentric speeds are very different to the geocentric // speeds, so we use other values than for geocentric calculations: if (topo) { if (!sw.swed.geopos_is_set) { throw new IllegalArgumentException("Geographic position is not set for "+ "requested topocentric calculations."); } // if (sw.swed.topd.geoalt>50000.) { // throw new IllegalArgumentException("Topocentric transit calculations "+ // "are restricted to a maximum "+ // "altitude of 50km so far."); // } else if (sw.swed.topd.geoalt<-12000000) { // throw new IllegalArgumentException("Topocentric transit calculations "+ // "are restricted to a minimum "+ // "altitude of -12000km so far."); // } if (sw.swed.topd.geoalt>50000. || sw.swed.topd.geoalt<-12000000) { return 1./0.; } if (speed) { if (rect) { return (min?SwephData.minTopoRectAccel[planet]:SwephData.maxTopoRectAccel[planet]); } else if (decl) { return (min?SwephData.minTopoDeclAccel[planet]:SwephData.maxTopoDeclAccel[planet]); } else if (lat) { return (min?SwephData.minTopoLatAccel[planet]:SwephData.maxTopoLatAccel[planet]); } else if (dist) { return (min?SwephData.minTopoDistAccel[planet]:SwephData.maxTopoDistAccel[planet]); } else if (lon) { return (min?SwephData.minTopoLonAccel[planet]:SwephData.maxTopoLonAccel[planet]); } } else { if (rect) { return (min?SwephData.minTopoRectSpeed[planet]:SwephData.maxTopoRectSpeed[planet]); } else if (decl) { return (min?SwephData.minTopoDeclSpeed[planet]:SwephData.maxTopoDeclSpeed[planet]); } else if (lat) { return (min?SwephData.minTopoLatSpeed[planet]:SwephData.maxTopoLatSpeed[planet]); } else if (dist) { return (min?SwephData.minTopoDistSpeed[planet]:SwephData.maxTopoDistSpeed[planet]); } else if (lon) { return (min?SwephData.minTopoLonSpeed[planet]:SwephData.maxTopoLonSpeed[planet]); } } } // Heliocentric speeds are very different to the geocentric speeds, so // we use other values than for geocentric calculations: if (helio) { if (speed) { if (rect) { return (min?SwephData.minHelioRectAccel[planet]:SwephData.maxHelioRectAccel[planet]); } else if (decl) { return (min?SwephData.minHelioDeclAccel[planet]:SwephData.maxHelioDeclAccel[planet]); } else if (lat) { return (min?SwephData.minHelioLatAccel[planet]:SwephData.maxHelioLatAccel[planet]); } else if (dist) { return (min?SwephData.minHelioDistAccel[planet]:SwephData.maxHelioDistAccel[planet]); } else if (lon) { return (min?SwephData.minHelioLonAccel[planet]:SwephData.maxHelioLonAccel[planet]); } } else { if (rect) { return (min?SwephData.minHelioRectSpeed[planet]:SwephData.maxHelioRectSpeed[planet]); } else if (decl) { return (min?SwephData.minHelioDeclSpeed[planet]:SwephData.maxHelioDeclSpeed[planet]); } else if (lat) { return (min?SwephData.minHelioLatSpeed[planet]:SwephData.maxHelioLatSpeed[planet]); } else if (dist) { return (min?SwephData.minHelioDistSpeed[planet]:SwephData.maxHelioDistSpeed[planet]); } else if (lon) { return (min?SwephData.minHelioLonSpeed[planet]:SwephData.maxHelioLonSpeed[planet]); } } } // Geocentric: if (speed) { if (rect) { return (min?SwephData.minRectAccel[planet]:SwephData.maxRectAccel[planet]); } else if (decl) { return (min?SwephData.minDeclAccel[planet]:SwephData.maxDeclAccel[planet]); } else if (lat) { return (min?SwephData.minLatAccel[planet]:SwephData.maxLatAccel[planet]); } else if (dist) { return (min?SwephData.minDistAccel[planet]:SwephData.maxDistAccel[planet]); } else if (lon) { return (min?SwephData.minLonAccel[planet]:SwephData.maxLonAccel[planet]); } } else { if (rect) { return (min?SwephData.minRectSpeed[planet]:SwephData.maxRectSpeed[planet]); } else if (decl) { return (min?SwephData.minDeclSpeed[planet]:SwephData.maxDeclSpeed[planet]); } else if (lat) { return (min?SwephData.minLatSpeed[planet]:SwephData.maxLatSpeed[planet]); } else if (dist) { return (min?SwephData.minDistSpeed[planet]:SwephData.maxDistSpeed[planet]); } else if (lon) { return (min?SwephData.minLonSpeed[planet]:SwephData.maxLonSpeed[planet]); } } return 1./0.; } catch (Exception e) { return 1./0.; } } protected boolean checkIdenticalResult(double offset, double val) { if (calcPartile) { boolean res = (((lon1 % 1) < 1E-9 || (lon2 % 1) < 1E-9) && // leave other values to the interpolation after the checkResult() call otherwise (int)(lon1%30) == (int)(lon2%30) && ((((int)(lon1) + offset + rolloverVal) % rolloverVal == (int)lon2) || (((int)(lon1) - offset + rolloverVal) % rolloverVal == (int)lon2))); return res; } else if (calcNonPartile) { boolean res = (((lon1 % 1) < 1E-9 && (lon2 % 1) < 1E-9) || // leave other values to the interpolation after the checkResult() call otherwise (int)(lon1%30) != (int)(lon2%30) || ((((int)(lon1) + offset + rolloverVal) % rolloverVal != (int)lon2) && (((int)(lon1) - offset + rolloverVal) % rolloverVal != (int)lon2))); return res; } return val == offset; } protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) { if (calcPartile) { boolean res = ((int)(lon1%30) == (int)(lon2%30) && ((((int)(lon1) + offset + rolloverVal) % rolloverVal == (int)lon2) || (((int)(lon1) - offset + rolloverVal) % rolloverVal == (int)lon2))); return res; } else if (calcNonPartile) { boolean res = ((int)(lon1%30) != (int)(lon2%30) || ((((int)(lon1) + offset + rolloverVal) % rolloverVal != (int)lon2) && (((int)(lon1) - offset + rolloverVal) % rolloverVal != (int)lon2))); return res; } return super.checkResult(offset, lastVal, val, above, pxway); } protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) { if (calcPartile || calcNonPartile) { double delta1, delta2, delta3, delta4; double deltaET; // direct and direct motion: if (calcPartile) { // distances in degree to next possible matching (int-)degree double target1 = ((int)(lon1) + offset + rolloverVal) % rolloverVal; double target2 = ((int)(lon1) - offset + rolloverVal) % rolloverVal; double target3 = ((int)(lon2) + offset + rolloverVal) % rolloverVal; double target4 = ((int)(lon2) - offset + rolloverVal) % rolloverVal; if (lon2 > target1) { delta1 = SMath.abs(lon2 - target1 - 1 + 1E-9); } else { delta1 = target1 - lon2; } if (lon2 > target2) { delta2 = SMath.abs(lon2 - target2 - 1 + 1E-9); } else { delta2 = target2 - lon2; } if (lon1 > target3) { delta3 = SMath.abs(lon1 - target3 - 1 + 1E-9); } else { delta3 = target3 - lon1; } if (lon1 > target4) { delta4 = SMath.abs(lon1 - target4 - 1 + 1E-9); } else { delta4 = target4 - lon1; } } else { // partile end // distances in degree to next possible non-matching degrees // ----|->---|-----------------------------------------------|--->-|---------------------- delta1 = lon1 - (int)lon1; delta2 = 1 - delta1; delta3 = lon2 - (int)lon2; delta4 = 1 - delta3; delta1 += 1E-9; delta2 += 1E-9; delta3 += 1E-9; delta4 += 1E-9; } double maxSpeed = SMath.abs(maxSpeed2 - minSpeed1); maxSpeed = SMath.max(maxSpeed, SMath.abs(maxSpeed1 - minSpeed2)); double minDx = SMath.min(SMath.min(SMath.min(delta1, delta2), delta3), delta4)%1; deltaET = SMath.abs(minDx / maxSpeed); return jdET + (back ? - deltaET : deltaET); } return super.getNextJD(jdET, val, offset, min, max, back); } // This routine returns extreme speed values by randomly calculating the speed // of the planet. Doesn't work for accelerations so far. double[] getTestspeed(int planet, int idx, int precalcCount, double precalcSafetyfactor) { StringBuffer serr = new StringBuffer(); double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; double[] timerange = new double[] { SwephData.MOSHPLEPH_START, SwephData.MOSHPLEPH_END }; if (planet > SweConst.SE_AST_OFFSET) { // get filename: String fn = SwissLib.swi_gen_filename(2457264.5 /* don't care */, planet); // Unfortunately, the name from swi_gen_filename may be slightly different, // so we have to test opening the filename and change the filename if // the file does not exist or is not readable: FilePtr fptr = null; SwissephException se = null; try { fptr = sw.swi_fopen(SwephData.SEI_FILE_ANY_AST, fn, sw.swed.ephepath, serr); } catch (SwissephException se1) { se = se1; } if (fptr == null) { /* * try also for short files (..s.se1) */ if (fn.indexOf("s.") <= 0) { fn = fn.substring(0, fn.indexOf(".")) + "s." + SwephData.SE_FILE_SUFFIX; } try { fptr = sw.swi_fopen(SwephData.SEI_FILE_ANY_AST, fn, sw.swed.ephepath, serr); } catch (SwissephException se2) { se = se2; } } if (fptr == null) { throw se; } try { fptr.close(); } catch (Exception e) { } // Now finally we have a filename for which we can get the time range, // if the file can be found and is readable: try { timerange = sw.getDatafileTimerange(fn); } catch (SwissephException se3) { } } java.util.Random rd = new java.util.Random(); double[] xx = new double[6]; for(int f = 0; f < precalcCount; f++) { double jdET = rd.nextDouble(); jdET = jdET * (timerange[1] - timerange[0]) + timerange[0]; int ret = sw.swe_calc(jdET, planet, flags | SweConst.SEFLG_SPEED, xx, serr); if (ret<0) { // throw new SwissephException(jdET, SwissephException.UNDEFINED_ERROR, // "Calculation failed with return code "+ret+":\n"+serr.toString()); continue; } if (min > xx[idx+3]) { min = xx[idx+3]; } if (max < xx[idx+3]) { max = xx[idx+3]; } } if (min == max || min == Double.MAX_VALUE || max == -Double.MAX_VALUE) { min = 1./0.; // Use as flag } else { // Apply safety factor for randomly calculated extreme speeds: switch ((int)Math.signum(min)) { case -1 : min *= precalcSafetyfactor; break; case 0 : min = -0.1; break; case 1 : min /= precalcSafetyfactor; break; } switch ((int)Math.signum(max)) { case -1 : max /= precalcSafetyfactor; break; case 0 : max = 0.1; break; case 1 : max *= precalcSafetyfactor; break; } } return new double[] {min, max}; } public String toString() { return "[Planets:" + pl1 + "/" + pl2 + "];Offset:" + getOffset(); } }
Kibo/AstroAPI
src/main/java/swisseph/TCPlanetPlanet.java
248,678
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAinteger32BE. */ public interface HLAinteger64BE extends DataElement { @Override int getOctetBoundary(); @Override void encode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override void decode(ByteWrapper byteWrapper); /** * Returns the long value of this element. * * @return long value */ long getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAinteger64BE.java
248,679
import java.math.BigInteger; import java.util.Scanner; /* * Problem Submissions Leaderboard Discussions Problem Statement This problem is a programming version of Problem 16 from projecteuler.net 29=512 and the sum of its digits is 5+1+2=8. What is the sum of the digits of the number 2N ? Input Format The first line contains an integer T , i.e., number of test cases. Next T lines will contain an integer N. Output Format Print the values corresponding to each test case. Constraints 1≤T≤100 1≤N≤10^4 Sample Input 3 3 4 7 Sample Output 8 7 11 */ public class Project_Euler_Plus_Problem_16 { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int numberOfCases = Integer.parseInt(stdin.nextLine()); String input; for (int a = 0; a < numberOfCases; a++) { input = stdin.nextLine(); int inputInt = Integer.parseInt(input); BigInteger b = (new BigInteger("2")).pow(inputInt); String stringOfCharacters = b.toString(); char[] numericValues = stringOfCharacters.toCharArray(); int sum = 0; for(int c = 0; c < numericValues.length; c++){ sum += Integer.parseInt("" + numericValues[c]); } System.out.println(sum); } } }
PeterASteele/HackerRankProblems
Project_Euler_Plus_Problem_16.java
248,680
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * * Public exception class UnableToPerformSave * */ public final class UnableToPerformSave extends RTIexception { public UnableToPerformSave(String msg) { super(msg); } } //File: UnknownName.java
hla-certi/jcerti1516e
src/hla/rti1516/UnableToPerformSave.java
248,681
package com.vit.testcases; import java.util.StringTokenizer; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import vit.webportal.pagefactory.Login; import vit.webportal.pagefactory.WebPortalHomePage; import vit.webportal.pagefactory.Project; public class TestProject { WebDriver driver; Login objLogin; WebPortalHomePage objHomePage; Project objProject; @Test public void clickMeetings(){ objProject.clickMeetings(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/meetings/listmeetings.php"); } @Test public void clickDiscussions(){ objProject.clickDiscussions(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/topics/listtopics.php"); } @Test public void clickCheckpoints(){ objProject.clickCheckpoints(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/checkpoints/listcheckpoints.php"); } @Test public void clickFiles(){ objProject.clickFiles(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/linkedcontent/listfile.php"); } @Test public void clickTeam(){ objProject.clickTeam(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/users/listusers_ajax.php"); } @Test public void clickProfile(){ objProject.clickProfile(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/profile/viewProfile.php"); } @BeforeTest public void beforeTest(){ driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.navigate().to("https://dev.tiermed.com/devsite/site_contents/our_company_login.php"); //Create Login Page Object objLogin = new Login(driver); objLogin.LoginToWebPortal("[email protected]", "[email protected]"); objHomePage = new WebPortalHomePage(driver); objHomePage.setProjectName("2728"); objProject = new Project(driver); } @AfterTest public void afterTest() { objHomePage.logout(); driver.quit(); } }
rahulyhg/WebPortal
com/vit/testcases/TestProject.java
248,682
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516.jlc; /** * Interface for the HLA data type HLAunicodeString. */ public interface HLAunicodeString extends DataElement { @Override void encode(ByteWrapper byteWrapper); @Override void decode(ByteWrapper byteWrapper); @Override int getEncodedLength(); @Override int getOctetBoundary(); /** * Returns the string value of this element. * * @return string value */ String getValue(); }
hla-certi/jcerti1516e
src/hla/rti1516/jlc/HLAunicodeString.java
248,683
package pages; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.EnumMap; import java.util.Map; public class SearchPage { WebDriver driver; WebDriverWait wait; private final By searchTextFieldPath = By.id("search"); private final By searchBtnPath = By.cssSelector("[class='button button-primary search-button hide-mobile']"); private final By filteredByTextPath = By.cssSelector("[class='filtered-by-text']"); private final By filterBtnPath = By.cssSelector("[class='open-filters-button']"); private final By discussionsBtnPath = By.cssSelector("a[data-filter-id='filterDiscussions']"); private final By userTipsBtnPath = By.cssSelector("a[data-filter-id='filterUserTips']"); private final By peopleBtnPath = By.cssSelector("a[data-filter-id='filterPeople']"); private final By typeBtnPath = By.cssSelector("div[class='filters-layout-desktop-filters hide-mobile open'] button[aria-label='Type filters Choose one']"); private final By solvedQuestionsBtnPath = By.cssSelector(".filter-link[href='?type=filterAnswered']"); private final By unsolvedQuestionsBtnPath = By.cssSelector("a[data-filter-id='filterOpen']"); private final By communityBtnPath = By.cssSelector("[data-filter-group-id='community']"); private final By iPhoneBtnPath = By.cssSelector("a[data-filter-id='2043020']"); private final By iPadBtnPath = By.cssSelector("a[data-filter-id='2039020']"); private final By appleWatchBtnPath = By.cssSelector("a[data-filter-id='3061020']"); private final By authorBtnPath = By.cssSelector("[data-filter-group-id='author']"); private final By timeBtnPath = By.cssSelector("[data-filter-group-id='time']"); private final By dayBtnPath = By.cssSelector("a[data-filter-id='day']"); private final By topicThreadHeadingPath = By.cssSelector("[class='topics-heading']"); private final By peopleAvatarPath = By.cssSelector("[class='post-author-profile author-user']"); private final By searchByAuthorTextFieldPath = By.cssSelector("[aria-label='Search by author']"); private final By nextBtnPath = By.cssSelector("[class='next-page icon icon-standalone icon-chevronright']"); private final By previousBtnPath = By.cssSelector("[class='previous-page icon icon-standalone icon-chevronleft']"); private final By pageNumberPath = By.cssSelector("[class='page-number']"); private final By nameReplyToBtnPath = By.cssSelector("[class='topics-table-row thread']:nth-child(2) > .topics-table-row-details > article > a"); private final By authorNameBtn2Path = By.cssSelector("tr:nth-child(2) > td.topics-table-row-latest-activity > div > a.author"); private final By subCommunityBtnPath = By.cssSelector("tr:nth-child(2) > th > article > div.topic-meta > a.community-link"); private final By authorNameBtn1Path = By.cssSelector("tr:nth-child(2) > th > article > div.topic-meta > [data-action='topic-author']"); private final By popupUserNamePath = By.id("user-profile-popup-title"); private final By popupClosePath = By.cssSelector("[class='modal-close-button']"); private final By askTheCommunityBtnPath = By.cssSelector("[data-action='search-ask-community']"); public enum Button { SubCommunityButton, AuthorNameButton2, AuthorNameButton1, PopupUserName, NameReplyToButton, FilteredByText, UserTipsButton, DiscussionsButton, TimeButton, DayButton, IPhoneButton, IPadButton, CommunityButton, FilterButton, PeopleButton, AuthorButton, SearchButton, Next, Previous, PopupClose, ThreadHeadingText, AskTheCommunityButton } private final Map<SearchPage.Button, By> paths = new EnumMap<>(SearchPage.Button.class); { paths.put(SearchPage.Button.SubCommunityButton, subCommunityBtnPath); paths.put(SearchPage.Button.AuthorNameButton2, authorNameBtn2Path); paths.put(SearchPage.Button.AuthorNameButton1, authorNameBtn1Path); paths.put(SearchPage.Button.PopupUserName, popupUserNamePath); paths.put(SearchPage.Button.NameReplyToButton, nameReplyToBtnPath); paths.put(SearchPage.Button.FilteredByText, filteredByTextPath); paths.put(SearchPage.Button.UserTipsButton, userTipsBtnPath); paths.put(SearchPage.Button.DiscussionsButton, discussionsBtnPath); paths.put(SearchPage.Button.TimeButton, timeBtnPath); paths.put(SearchPage.Button.DayButton, dayBtnPath); paths.put(SearchPage.Button.IPhoneButton, iPhoneBtnPath); paths.put(SearchPage.Button.IPadButton, iPadBtnPath); paths.put(SearchPage.Button.CommunityButton, communityBtnPath); paths.put(SearchPage.Button.FilterButton, filterBtnPath); paths.put(SearchPage.Button.PeopleButton, peopleBtnPath); paths.put(SearchPage.Button.AuthorButton, authorBtnPath); paths.put(SearchPage.Button.SearchButton, searchBtnPath); paths.put(SearchPage.Button.Next, nextBtnPath); paths.put(SearchPage.Button.Previous, previousBtnPath); paths.put(SearchPage.Button.PopupClose, popupClosePath); paths.put(SearchPage.Button.AskTheCommunityButton, askTheCommunityBtnPath); paths.put(SearchPage.Button.ThreadHeadingText, topicThreadHeadingPath); } public SearchPage(WebDriver driver) { this.driver = driver; wait = new WebDriverWait(driver, Duration.ofSeconds(10)); } public void clickButton(Button button) { wait.until(ExpectedConditions.elementToBeClickable(paths.get(button))).click(); } public String getButtonText(Button button) { return wait.until(ExpectedConditions.elementToBeClickable(paths.get(button))).getText(); } public void setSearchText(String searchText) { wait.until(ExpectedConditions.visibilityOfElementLocated(searchTextFieldPath)).sendKeys(searchText); } public boolean buttonIsDisplayed(SearchPage.Button button) { try { return wait.until(ExpectedConditions.visibilityOfElementLocated(paths.get(button))).isDisplayed(); } catch (Exception e) { return false; } } public void clickSolvedBtn() throws InterruptedException { wait.until(ExpectedConditions.elementToBeClickable(typeBtnPath)).click(); Thread.sleep(4000); wait.until(ExpectedConditions.elementToBeClickable(solvedQuestionsBtnPath)).click(); } public void clickUnSolvedBtn() throws InterruptedException { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollTo(0, document.body.scrollHeight/8)"); Thread.sleep(4000); wait.until(ExpectedConditions.elementToBeClickable(unsolvedQuestionsBtnPath)).click(); } public void clickAppleWatchBtn() throws InterruptedException { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.scrollTo(0, document.body.scrollHeight/8)"); Thread.sleep(4000); wait.until(ExpectedConditions.elementToBeClickable(appleWatchBtnPath)).click(); wait.until(ExpectedConditions.elementToBeClickable(topicThreadHeadingPath)); Thread.sleep(4000); } public boolean searchByAuthorBtnIsVisible() { return wait.until(ExpectedConditions.visibilityOfElementLocated(searchByAuthorTextFieldPath)).isDisplayed(); } public void peopleAvatar() { try { wait.until(ExpectedConditions.elementToBeClickable(peopleAvatarPath)); } catch (Exception ignored) { } } public String getPageNumberName() throws InterruptedException { Thread.sleep(4000); return wait.until(ExpectedConditions.visibilityOfElementLocated(pageNumberPath)).getText(); } public void waitButtonVisibility() { wait.until(ExpectedConditions.visibilityOfElementLocated(topicThreadHeadingPath)); } }
santriarustamyan/AppleWebApp
src/main/java/pages/SearchPage.java
248,684
package com.vit.testcases; import java.util.StringTokenizer; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import vit.webportal.pagefactory.Login; import vit.webportal.pagefactory.WebPortalHomePage; public class TestHomePage { WebDriver driver; Login objLogin; WebPortalHomePage objHomePage; @Test public void clickMeetings(){ objHomePage.clickMeeting(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/general/homeMeeting.php"); } @Test public void clickDiscussions() { objHomePage.clickDiscussions(); StringTokenizer url = new StringTokenizer(driver.getCurrentUrl(),"?"); Assert.assertEquals(url.nextToken(), "https://dev.tiermed.com/projectsite/general/homeDiscussion.php"); } @BeforeTest public void beforeMethod() { driver = new FirefoxDriver(); driver.get("https://dev.tiermed.com/devsite/site_contents/our_company_login.php"); //driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS); //Create Login Page Object objLogin = new Login(driver); objLogin.LoginToWebPortal("[email protected]", "[email protected]"); objHomePage = new WebPortalHomePage(driver); } @AfterTest public void afterTest() { objHomePage.logout(); driver.quit(); } }
rahulyhg/WebPortal
com/vit/testcases/TestHomePage.java
248,685
//Program to find out if two strings are anagrams from the Discussions page of the Anagrams challenge for Java - the editorial for the Java HackerRank challenge has more solutions, one of which is exactly like mine //Why this solution is notable is because of the HashSet it uses, and the fact that it is O(n), whereas sorting arrays is n log(n) - https://www.hackerrank.com/challenges/java-anagrams/forum/comments/158850 static boolean isAnagram(String a, String b) { // test for invalid input if( a == null || b == null || a.equals("") || b.equals("") ) throw new IllegalArgumentException(); // initial quick test for non-anagrams if ( a.length() != b.length() ) return false; a = a.toLowerCase(); b = b.toLowerCase(); // populate a map with letters and frequencies of String b Map<Character, Integer> map = new HashMap<>(); for (int k = 0; k < b.length(); k++){ char letter = b.charAt(k); if( ! map.containsKey(letter)){ map.put( letter, 1 ); } else { Integer frequency = map.get( letter ); map.put( letter, ++frequency ); } } // test each letter in String a against data in the map // return if letter is absent in the map or its frequency is 0 // otherwise decrease the frequency by 1 for (int k = 0; k < a.length(); k++){ char letter = a.charAt(k); if( ! map.containsKey( letter ) ) return false; Integer frequency = map.get( letter ); if( frequency == 0 ) return false; else map.put( letter, --frequency); } // if the code got that far it is an anagram return true;
parth-io/Learn-CS-and-Coding
HackerRank/Java/Anagrams.java
248,686
/* * This file comes from SISO STD-004.1-2004 for HLA1516 * from http://www.sisostds.org/ProductsPublications/Standards/SISOStandards.aspx. * see also updated version from 2006: * http://discussions.sisostds.org/threadview.aspx?threadid=40014 * * It is provided as-is by CERTI project. */ package hla.rti1516; /** * An enumerated type (not a Java Enumeration!) * * @see hla.rti1516.RTIambassador#resignFederationExecution */ public final class ResignAction implements java.io.Serializable { private int _value; // each instance's value private static final int _lowestValue = 1; private static int _nextToAssign = _lowestValue; // begins at lowest /** * This is the only public constructor. Each user-defined instance of a * ResignAction must be initialized with one of the defined static values. * * @param otherResignActionValue must be a defined static value or another * instance. */ public ResignAction(ResignAction otherResignActionValue) { _value = otherResignActionValue._value; } /** * Private to class */ private ResignAction() { _value = _nextToAssign++; } ResignAction(int value) throws RTIinternalError { _value = value; if (value < _lowestValue || value >= _nextToAssign) throw new RTIinternalError("ResignAction: illegal value " + value); } /** * @return String with value "ResignAction(n)" where n is value */ @Override public String toString() { return "ResignAction(" + _value + ")"; } /** * Allows comparison with other instance of same type. * * @return true if supplied object is of type ResignAction and has same value; * false otherwise */ @Override public boolean equals(Object otherResignActionValue) { if (otherResignActionValue instanceof ResignAction) return _value == ((ResignAction) otherResignActionValue)._value; else return false; } @Override public int hashCode() { return _value; } static public final ResignAction UNCONDITIONALLY_DIVEST_ATTRIBUTES = new ResignAction(); static public final ResignAction DELETE_OBJECTS = new ResignAction(); static public final ResignAction CANCEL_PENDING_OWNERSHIP_ACQUISITIONS = new ResignAction(); static public final ResignAction DELETE_OBJECTS_THEN_DIVEST = new ResignAction(); static public final ResignAction CANCEL_THEN_DELETE_THEN_DIVEST = new ResignAction(); static public final ResignAction NO_ACTION = new ResignAction(); }
hla-certi/jcerti1516e
src/hla/rti1516/ResignAction.java
248,688
import java.util.*; public class bear { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int limak = sc.nextInt(); int bob = sc.nextInt(); sc.close(); int count = 0; while (limak <= bob) { limak = limak * 3; bob *= 2; count++; } System.out.println(count); } }
Paulie-Aditya/codeforces-grind
bear.java
248,690
public class bear extends Animal implements Printable{ private String race; public bear(String race){ this.race = race; } @Override public void print() { System.out.println("Раса медведя:" + race); } }
BolotbekovvB/HM-2
src/bear.java
248,694
class Bees { Honey [] beeHA; } class Raccoon { Kit k; Honey rh; } class Kit { Honey kh; } class Bear { Honey hunny; } public class Honey { public static void main(String [] args) { Honey honeyPot = new Honey(); Honey [] ha = {honeyPot, honeyPot, honeyPot, honeyPot}; Bees b1 = new Bees(); b1.beeHA = ha; Bear [] ba = new Bear[5]; for (int x=0; x < 5; x++) { ba[x] = new Bear(); ba[x].hunny = honeyPot; } Kit k = new Kit(); k.kh = honeyPot; Raccoon r = new Raccoon(); r.rh = honeyPot; r.k = k; k = null; }// end of main }
Abhishek1923/Java-Codes
Honey.java
248,701
import java.util.Scanner; public class bear { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); int b=sc.nextInt(); int c=0; while(a<=b) { a=a*3; b=b*2; c++; } System.out.println(c); sc.close(); } }
VedanshKamdar/Codeforces-Solutions
bear.java
248,702
import java.awt.*; public class Bear extends Critter { private boolean polar; private int moves; public Bear(boolean polar){ this.polar=polar; getColor(); } public Color getColor() { //Color.WHITE for a polar bear (when polar is true), // Color.BLACK otherwise (when polar is false) if (this.polar){ return Color.WHITE; } else { return Color.BLACK; } } public String toString(){ //Should alternate on each different move between a slash character (/) // and a backslash character () starting with a slash. if (moves%2==0){ return "/"; } else { return "\\"; } } public Action getMove(CritterInfo info){ //always infect if an enemy is in front, otherwise hop if possible, otherwise turn left. moves++; if(info.getFront()==Neighbor.OTHER){ return Action.INFECT; } else if (info.getFront()==Neighbor.EMPTY){ return Action.HOP; } else { return super.getMove(info); } } }
JessSanchezC/AnimalKingdom
Bear.java
248,704
public class Bear extends Obstacle{ public Bear() { super("Bear", 7, 20, 12, 2); } }
ozgucdlg/AdventureGame
src/Bear.java
248,705
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.*; public class BearTest { Bear bear; Salmon salmon; Human human; Chicken chicken; @Before public void before() { bear = new Bear("Baloo"); human = new Human(); salmon = new Salmon(); chicken = new Chicken(); } @Test public void hasName(){ assertEquals("Baloo", bear.getName()); } @Test public void bellyStartsEmpty(){ assertEquals(0, bear.foodCount()); } @Test public void canEatSalmon(){ bear.eat(salmon); assertEquals(bear.foodCount(), 1); } @Test public void shouldEmptyBellyAfterSleeping(){ bear.eat(salmon); bear.sleep(); assertEquals(bear.foodCount(), 0); } @Test public void canEatHuman(){ bear.eat(human); assertEquals(1, bear.foodCount()); } @Test public void canThrowUp(){ bear.eat(salmon); Edible food = bear.throwUp(); assertNotNull(food); Salmon original = (Salmon)food; assertEquals("swimming", original.swim()); } @Test public void chickenCanCluck(){ assertEquals("Bok bok bok", chicken.cluck()); } @Test public void chickenCanBeThrownUp(){ bear.eat(chicken); Edible food = bear.throwUp(); assertNotNull(food); Chicken supreme = (Chicken)food; assertEquals("Bok bok bok", supreme.cluck()); } @Test public void chickenIsNutritious(){ assertEquals(1400, chicken.getNutritionValue()); } @Test public void salmonIsNutritious(){ assertEquals(800, salmon.getNutritionValue()); } @Test public void peopleAreNutritious(){ assertEquals(110000, human.getNutritionValue()); } @Test public void canSumNutritionOfBellyContents(){ bear.eat(chicken); bear.eat(salmon); assertEquals(2200, bear.totalNutrition()); } }
dalzinho/The-Polymorph
BearTest.java