answer
stringlengths
17
10.2M
/* vim: set et ts=4 sts=4 sw=4 tw=72 : */ package uk.ac.cam.cl.git; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.LinkedList; import javax.ws.rs.GET; import javax.ws.rs.PathParam; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Path("/") public class GitService { @GET @Path("/git") @Produces("application/json") public Response listRepositories() { List<Repository> repos = ConfigDatabase.getRepos(); List<String> toReturn = new LinkedList<String>(); for (Repository repo : repos) { toReturn.add(repo.getName()); } return Response.status(200).entity(toReturn).build(); } @GET @Path("/git/{repoName}") @Produces("application/json") public Response listFiles(@PathParam("repoName") String repoName) throws IOException { Repository repo = ConfigDatabase.getRepoByName(repoName); Collection<String> files = repo.getSources(); List<String> toReturn = new LinkedList<String>(); for (String file : files) { toReturn.add(file); } return Response.status(200).entity(toReturn).build(); } @GET @Path("/git/{repoName}/{fileName:.*}") public Response getFile(@PathParam("fileName") String fileName , @PathParam("repoName") String repoName) { /* TODO * 1. Open the file given by filePath in the Git repository * repoName. This can be done with GitDb and TreeWalker * somehow, to prevent the need of cloning the repository. * 2. Give the contents of the file as the entity */ return Response.status(200).entity(fileName).build(); } }
package util.game; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.Set; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import external.JSON.*; /** * Local game repositories provide access to game resources stored on the * local disk, bundled with the GGP Base project. For consistency with the * web-based GGP.org infrastructure, this starts a simple HTTP server that * provides access to the local game resources, and then uses the standard * RemoteGameRepository interface to read from that server. * * @author Sam */ public final class LocalGameRepository extends GameRepository { private static final int REPO_SERVER_PORT = 9140; private static HttpServer theLocalRepoServer = null; private static String theLocalRepoURL = "http://127.0.0.1:" + REPO_SERVER_PORT; private static RemoteGameRepository theRealRepo; public LocalGameRepository() { if (theLocalRepoServer == null) { try { theLocalRepoServer = HttpServer.create(new InetSocketAddress(REPO_SERVER_PORT), 0); theLocalRepoServer.createContext("/", new LocalRepoServer()); theLocalRepoServer.setExecutor(null); // creates a default executor theLocalRepoServer.start(); } catch (IOException e) { throw new RuntimeException(e); } } theRealRepo = new RemoteGameRepository(theLocalRepoURL); } @Override protected Game getUncachedGame(String theKey) { return theRealRepo.getGame(theKey); } @Override protected Set<String> getUncachedGameKeys() { return theRealRepo.getGameKeys(); } class LocalRepoServer implements HttpHandler { public void handle(HttpExchange t) throws IOException { String theURI = t.getRequestURI().toString(); byte[] response = BaseRepository.getResponseBytesForURI(theURI); if (response == null) { t.sendResponseHeaders(404, 0); OutputStream os = t.getResponseBody(); os.close(); } else { t.sendResponseHeaders(200, response.length); OutputStream os = t.getResponseBody(); os.write(response); os.close(); } } } static class BaseRepository { public static final String repositoryRootDirectory = theLocalRepoURL; public static byte[] getResponseBytesForURI(String reqURI) throws IOException { // Files not under /games/games/ aren't versioned, // and can just be accessed directly. if (!reqURI.startsWith("/games/")) { return getBytesForFile(new File("games" + reqURI)); } // Provide a listing of all of the metadata files for all of // the games, on request. if (reqURI.equals("/games/metadata")) { JSONObject theGameMetaMap = new JSONObject(); for (String gameName : new File("games", "games").list()) { if (gameName.equals(".svn")) continue; try { theGameMetaMap.put(gameName, new JSONObject(new String(getResponseBytesForURI("/games/" + gameName + "/")))); } catch (JSONException e) { e.printStackTrace(); } } return theGameMetaMap.toString().getBytes(); } // Accessing the folder containing a game should show the game's // associated metadata (which includes the contents of the folder). if(reqURI.endsWith("/") && reqURI.length() > 9) { reqURI += "METADATA"; } // Extract out the version number String thePrefix = reqURI.substring(0, reqURI.lastIndexOf("/")); String theSuffix = reqURI.substring(reqURI.lastIndexOf("/")+1); Integer theExplicitVersion = null; try { String vPart = thePrefix.substring(thePrefix.lastIndexOf("/v")+2); theExplicitVersion = Integer.parseInt(vPart); thePrefix = thePrefix.substring(0, thePrefix.lastIndexOf("/v")); } catch (Exception e) { ; } // Sanity check: raise an exception if the parsing didn't work. if (theExplicitVersion == null) { if (!reqURI.equals(thePrefix + "/" + theSuffix)) { throw new RuntimeException(reqURI + " != [~v] " + (thePrefix + "/" + theSuffix)); } } else { if (!reqURI.equals(thePrefix + "/v" + theExplicitVersion + "/" + theSuffix)) { throw new RuntimeException(reqURI + " != [v] " + (thePrefix + "/v" + theExplicitVersion + "/" + theSuffix)); } } // When no version number is explicitly specified, assume that we want the // latest version, whatever that is. Also, make sure the game version being // requested actually exists (i.e. is between 0 and the max version). int nMaxVersion = getMaxVersionForDirectory(new File("games", thePrefix)); Integer theFetchedVersion = theExplicitVersion; if (theFetchedVersion == null) theFetchedVersion = nMaxVersion; if (theFetchedVersion < 0 || theFetchedVersion > nMaxVersion) return null; while (theFetchedVersion >= 0) { byte[] theBytes = getBytesForVersionedFile(thePrefix, theFetchedVersion, theSuffix); if (theBytes != null) { if (theSuffix.equals("METADATA")) { theBytes = adjustMetadataJSON(theBytes, theExplicitVersion, nMaxVersion); } return theBytes; } theFetchedVersion } return null; } // When the user requests a particular version, the metadata should always be for that version. // When the user requests the latest version, the metadata should always indicate the most recent version. // TODO(schreib): Clean this up later: perhaps generate the metadata entirely? public static byte[] adjustMetadataJSON(byte[] theMetaBytes, Integer nExplicitVersion, int nMaxVersion) throws IOException { try { JSONObject theMetaJSON = new JSONObject(new String(theMetaBytes)); if (nExplicitVersion == null) { theMetaJSON.put("version", nMaxVersion); } else { theMetaJSON.put("version", nExplicitVersion); } return theMetaJSON.toString().getBytes(); } catch (JSONException je) { throw new IOException(je); } } private static int getMaxVersionForDirectory(File theDir) { if (!theDir.exists() || !theDir.isDirectory()) { return -1; } int maxVersion = 0; String[] children = theDir.list(); for (String s : children) { if (s.equals(".svn")) continue; if (s.startsWith("v")) { int nVersion = Integer.parseInt(s.substring(1)); if (nVersion > maxVersion) { maxVersion = nVersion; } } } return maxVersion; } private static byte[] getBytesForVersionedFile(String thePrefix, int theVersion, String theSuffix) { if (theVersion == 0) { return getBytesForFile(new File("games", thePrefix + "/" + theSuffix)); } else { return getBytesForFile(new File("games", thePrefix + "/v" + theVersion + "/" + theSuffix)); } } private static byte[] getBytesForFile(File theFile) { try { if (!theFile.exists()) { return null; } else if (theFile.isDirectory()) { return readDirectory(theFile).getBytes(); } else if (theFile.getName().endsWith(".png")) { // TODO: Handle other binary formats? return readBinaryFile(theFile); } else if (theFile.getName().endsWith(".xsl")) { return transformXSL(readFile(theFile)).getBytes(); } else if (theFile.getName().endsWith(".js")) { return transformJS(readFile(theFile)).getBytes(); } else { return readFile(theFile).getBytes(); } } catch (IOException e) { return null; } } private static String transformXSL(String theContent) { // Special case override for XSLT return "<!DOCTYPE stylesheet [<!ENTITY ROOT \""+repositoryRootDirectory+"\">]>\n\n" + theContent; } private static String transformJS(String theContent) throws IOException { // Horrible hack; fix this later. Right now this is used to // let games share a common board user interface, but this should // really be handled in a cleaner, more general way with javascript // libraries and imports. if (theContent.contains("[BOARD_INTERFACE_JS]")) { String theCommonBoardJS = readFile(new File("games/resources/scripts/BoardInterface.js")); theContent = theContent.replaceFirst("\\[BOARD_INTERFACE_JS\\]", theCommonBoardJS); } return theContent; } private static String readDirectory(File theDirectory) throws IOException { StringBuilder response = new StringBuilder(); // Show contents of the directory, using JSON notation. response.append("["); String[] children = theDirectory.list(); for (int i=0; i<children.length; i++) { if (children[i].equals(".svn")) continue; // Get filename of file or directory response.append("\""); response.append(children[i]); response.append("\",\n "); } response.delete(response.length()-3, response.length()); response.append("]"); return response.toString(); } public static String readFile(File rootFile) throws IOException { // Show contents of the file. FileReader fr = new FileReader(rootFile); BufferedReader br = new BufferedReader(fr); String response = ""; String line; while( (line = br.readLine()) != null ) { response += line + "\n"; } return response; } private static byte[] readBinaryFile(File rootFile) throws IOException { InputStream in = new FileInputStream(rootFile); ByteArrayOutputStream out = new ByteArrayOutputStream(); // Transfer bytes from in to out byte[] buf = new byte[1024]; while (in.read(buf) > 0) { out.write(buf); } in.close(); return out.toByteArray(); } } }
package dmh.kuebiko.util; import java.io.Serializable; public final class Pair<E1, E2> implements Serializable { private static final long serialVersionUID = 1L; public static <E1, E2> Pair<E1, E2> of (E1 first, E2 second) { return new Pair<E1, E2>(first, second); } public final E1 first; public final E2 second; private Pair (E1 first, E2 second) { this.first = first; this.second = second; } @Override public String toString() { return "Pair [first=" + first + ", second=" + second + "]"; } }
package com.worldly.activities; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import org.json.JSONException; import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ConfigurationInfo; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.worldly.R; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.worldly.controller.WorldlyController; import com.worldly.data_models.Country; public class MapActivity extends FragmentActivity { private Activity self; private ArrayList<Country> availableCountries = new ArrayList<Country>(); private List<Country> selectedCountries = new ArrayList<Country>(); private HashMap<Marker, Country> markerToCountry; private EditText countrySearchField; private Button goCompareButton; private Button clearSelectionButton; private Button allSelectedCountriesButton; //private Spinner allSelectedCountrySpinner; private ArrayAdapter<Country> arrayAdapter; private GoogleMap map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); //getActionBar().setDisplayHomeAsUpEnabled(true); //removed to support lower API - version 8 self = this; WorldlyController appController = WorldlyController.getInstance(); if (appController.getCurrentSelectedCountries() != null) { this.selectedCountries = appController.getCurrentSelectedCountries(); } if (hasGLES20()) { map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { Country aCountry = markerToCountry.get(marker); boolean alreadySelected = false; for (Country existingCountry : selectedCountries) { if (existingCountry.getIso2Code().equals(aCountry.getIso2Code())) { alreadySelected = true; break; } } if (alreadySelected) { selectedCountries.remove(aCountry); Toast.makeText(self, aCountry+" removed!", Toast.LENGTH_SHORT).show(); } else { selectedCountries.add(aCountry); Toast.makeText(self, aCountry+" added!", Toast.LENGTH_SHORT).show(); } arrayAdapter.notifyDataSetChanged(); marker.hideInfoWindow(); } }); } //allSelectedCountrySpinner = (Spinner) findViewById(R.id.countries_selected_spinner); countrySearchField = (EditText) findViewById(R.id.country_search_field); goCompareButton = (Button) findViewById(R.id.compare_button); allSelectedCountriesButton = (Button) findViewById(R.id.countries_selected_button); clearSelectionButton = (Button) findViewById(R.id.clear_country_selection_button); this.arrayAdapter = new ArrayAdapter<Country>(self, android.R.layout.simple_spinner_dropdown_item, selectedCountries); allSelectedCountriesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(self) .setTitle(selectedCountries.size() + " " + getResources().getString(R.string.countries_spinner_prompt)) .setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); countrySearchField.setText(""); Country aCountry = selectedCountries.get(which); LatLng aMarker = new LatLng(aCountry.getLatitude(), aCountry.getLongitude()); map.moveCamera(CameraUpdateFactory.newLatLngZoom(aMarker, 4)); } }).create().show(); } }); //this.arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // allSelectedCountrySpinner.setAdapter(this.arrayAdapter); // allSelectedCountrySpinner.setOnItemSelectedListener(new OnItemSelectedListener() { // @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // //Log.v(getClass().getName(), "SELECTED"); // parent.setSelection(0); // @Override public void onNothingSelected(AdapterView<?> parent) { // //Log.v(getClass().getName(), "NOT SELECTED"); countrySearchField.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void afterTextChanged(Editable s) { String inputString = countrySearchField.getText().toString(); if (inputString.length() >= 0) { plotCountriesOnMap(); } } }); goCompareButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (selectedCountries.size() > 0) { WorldlyController appController = WorldlyController.getInstance(); appController.setCurrentSelectedCountries(selectedCountries); startActivity(new Intent(self, CompareCategoriesActivity.class)); } else Toast.makeText(self, getString(R.string.empty_list_countries), Toast.LENGTH_LONG).show(); } }); clearSelectionButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case DialogInterface.BUTTON_POSITIVE: selectedCountries.clear(); break; case DialogInterface.BUTTON_NEGATIVE: // No Action break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(self); builder.setTitle(selectedCountries.size() + " " + getResources().getString(R.string.countries_spinner_prompt)) .setAdapter(arrayAdapter, dialogClickListener) .setMessage("Are you sure you wish to clear your selection of countries?") .setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener) .create().show(); } }); Thread aThread = new Thread(new Runnable() { @Override public void run() { try { availableCountries = Country.getAllCountries(); plotCountriesOnMap(); } catch (JSONException e) { e.printStackTrace(); } } }); aThread.start(); } public boolean hasGLES20() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo info = am.getDeviceConfigurationInfo(); Log.d(getClass().getName(), (info.reqGlEsVersion >= 0x20000) ? "Has Open GL 2.0" : "Has not got Open GL 2.0"); return info.reqGlEsVersion >= 0x20000; } public void plotCountriesOnMap() { self.runOnUiThread(new Runnable() { @Override public void run() { plotSpecificCountriesOnMap(); } }); } public void plotSpecificCountriesOnMap() { map.clear(); markerToCountry = new HashMap<Marker, Country>(); if (availableCountries.size() > 0) { int markerCount = 0; Marker lastMarker = null; for (Country aCountry : availableCountries) { Locale current = getResources().getConfiguration().locale; String inputString = countrySearchField.getText().toString().toLowerCase(current); String countryName = aCountry.getName().toLowerCase(current); String iso2Code = aCountry.getIso2Code().toLowerCase(current); if (aCountry.getLatitude() != null && aCountry.getLongitude() != null && (countryName.startsWith(inputString) || iso2Code.startsWith(inputString))) { LatLng aLocation = new LatLng(aCountry.getLatitude(), aCountry.getLongitude()); if (map != null) { String title = aCountry.getName() + " - " + aCountry.getCapitalCity(); MarkerOptions aMarkerOption = new MarkerOptions().title(title).snippet(getString(R.string.tap_to_add_or_remove)).position(aLocation); Marker aMarker = map.addMarker(aMarkerOption); markerToCountry.put(aMarker, aCountry); lastMarker = aMarker; markerCount++; } } } if (markerCount == 1) { map.moveCamera(CameraUpdateFactory.newLatLngZoom(lastMarker.getPosition(), 4)); lastMarker = null; } else { map.moveCamera(CameraUpdateFactory.zoomTo(1)); } } } /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_about: // Take user to secret classified About Page startActivity(new Intent(this, AboutActivity.class)); break; case android.R.id.home: // Respond to the action bar's Up/Home button NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /* (non-Javadoc) * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu) */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.selection, menu); return true; } }
package org.ektorp; import java.util.LinkedHashMap; import java.util.Map; /** * * @author henrik * */ public class Options { private Map<String, String> options = new LinkedHashMap<String, String>(); /** * The loaded doc will include the special field '_conflicts' that contains all the conflicting revisions of the document. * @return */ public Options includeConflicts() { options.put("conflicts", "true"); return this; } /** * The loaded doc will include the special field '_revisions' that describes all document revisions that exists in the database. * @return */ public Options includeRevisions() { options.put("revs", "true"); return this; } /** * Retrieve a specific revision of the document. * @return */ public Options revision(String rev) { options.put("rev", rev); return this; } /** * Adds a parameter to the GET request sent to the database. * @param name * @param value * @return */ public Options param(String name, String value) { options.put(name, value); return this; } public Map<String, String> getOptions() { return options; } public boolean isEmpty() { return options.isEmpty(); } }
package analysis.dynamicsim; import gnu.trove.map.hash.TIntDoubleHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.set.hash.TIntHashSet; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import javax.xml.stream.XMLStreamException; import org.sbml.jsbml.AssignmentRule; import org.sbml.jsbml.Rule; import main.Gui; import main.util.MutableBoolean; import odk.lang.FastMath; public class SimulatorSSACR extends Simulator { //allows for access to a group number from a reaction ID private TObjectIntHashMap<String> reactionToGroupMap = null; //allows for access to a group's min/max propensity from a group ID private TIntDoubleHashMap groupToMaxValueMap = null; //allows for access to the minimum/maximum possible propensity in the group from a group ID private TIntDoubleHashMap groupToPropensityFloorMap = null; private TIntDoubleHashMap groupToPropensityCeilingMap = null; //allows for access to the reactionIDs in a group from a group ID private ArrayList<HashSet<String> > groupToReactionSetList = null; //allows for access to the group's total propensity from a group ID private TIntDoubleHashMap groupToTotalGroupPropensityMap = null; //stores group numbers that are nonempty private TIntHashSet nonemptyGroupSet = null; //number of groups including the empty groups and zero-propensity group private int numGroups = 0; private static Long initializationTime = new Long(0); MutableBoolean eventsFlag = new MutableBoolean(false); MutableBoolean rulesFlag = new MutableBoolean(false); MutableBoolean constraintsFlag = new MutableBoolean(false); public SimulatorSSACR(String SBMLFileName, String outputDirectory, double timeLimit, double maxTimeStep, double minTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running, String[] interestingSpecies, String quantityType) throws IOException, XMLStreamException { super(SBMLFileName, outputDirectory, timeLimit, maxTimeStep, minTimeStep, randomSeed, progress, printInterval, initializationTime, stoichAmpValue, running, interestingSpecies, quantityType); try { initialize(randomSeed, 1); } catch (IOException e2) { e2.printStackTrace(); } catch (XMLStreamException e2) { e2.printStackTrace(); } } /** * runs the composition and rejection simulation */ public void simulate() { if (sbmlHasErrorsFlag == true) return; long initTime2 = System.nanoTime(); final boolean noEventsFlag = (Boolean) eventsFlag.getValue(); final boolean noAssignmentRulesFlag = (Boolean) rulesFlag.getValue(); final boolean noConstraintsFlag = (Boolean) constraintsFlag.getValue(); initializationTime += System.nanoTime() - initTime2; long initTime3 = System.nanoTime() - initTime2; //System.err.println("initialization time: " + initializationTime / 1e9f); //SIMULATION LOOP //simulate until the time limit is reached long step1Time = 0; long step2Time = 0; long step3aTime = 0; long step3bTime = 0; long step4Time = 0; long step5Time = 0; long step6Time = 0; TObjectIntHashMap<String> reactionToTimesFired = new TObjectIntHashMap<String>(); currentTime = 0.0; double printTime = -0.00001; //add events to queue if they trigger if (noEventsFlag == false) handleEvents(noAssignmentRulesFlag, noConstraintsFlag); //System.err.println(reactionToPropensityMap.size()); while (currentTime < timeLimit && cancelFlag == false) { //if a constraint fails if (constraintFailureFlag == true) { JOptionPane.showMessageDialog(Gui.frame, "Simulation Canceled Due To Constraint Failure", "Constraint Failure", JOptionPane.ERROR_MESSAGE); return; } //EVENT HANDLING //trigger and/or fire events, etc. if (noEventsFlag == false) { HashSet<String> affectedReactionSet = fireEvents(noAssignmentRulesFlag, noConstraintsFlag); //recalculate propensties/groups for affected reactions if (affectedReactionSet.size() > 0) { boolean newMinPropensityFlag = updatePropensities(affectedReactionSet); if (newMinPropensityFlag == true) reassignAllReactionsToGroups(); else updateGroups(affectedReactionSet); } } //prints the initial (time == 0) data if (currentTime >= printTime) { if (printTime < 0) printTime = 0.0; try { printToTSD(printTime); bufferedTSDWriter.write(",\n"); } catch (IOException e) { e.printStackTrace(); } printTime += printInterval; } //update progress bar progress.setValue((int)((currentTime / timeLimit) * 100.0)); //STEP 1: generate random numbers //long step1Initial = System.nanoTime(); double r1 = randomNumberGenerator.nextDouble(); double r2 = randomNumberGenerator.nextDouble(); double r3 = randomNumberGenerator.nextDouble(); double r4 = randomNumberGenerator.nextDouble(); //step1Time += System.nanoTime() - step1Initial; //STEP 2A: calculate delta_t, the time till the next reaction execution //long step2Initial = System.nanoTime(); double delta_t = FastMath.log(1 / r1) / totalPropensity; if (delta_t > maxTimeStep) delta_t = maxTimeStep; if (delta_t < minTimeStep) delta_t = minTimeStep; //step2Time += System.nanoTime() - step2Initial; //STEP 2B: calculate rate rules using this time step HashSet<String> affectedVariables = performRateRules(delta_t); //update stuff based on the rate rules altering values for (String affectedVariable : affectedVariables) { if (speciesToAffectedReactionSetMap != null && speciesToAffectedReactionSetMap.containsKey(affectedVariable)) updatePropensities(speciesToAffectedReactionSetMap.get(affectedVariable)); if (variableToAffectedAssignmentRuleSetMap != null && variableToAffectedAssignmentRuleSetMap.containsKey(affectedVariable)) performAssignmentRules(variableToAffectedAssignmentRuleSetMap.get(affectedVariable)); if (variableToAffectedConstraintSetMap != null && variableToAffectedConstraintSetMap.containsKey(affectedVariable)) testConstraints(variableToAffectedConstraintSetMap.get(affectedVariable)); } //STEP 3A: select a group //long step3aInitial = System.nanoTime(); int selectedGroup = selectGroup(r2); //step3aTime += System.nanoTime() - step3aInitial; //if it's zero that means there aren't any reactions to fire if (selectedGroup != 0) { //STEP 3B: select a reaction within the group //long step3bInitial = System.nanoTime(); String selectedReactionID = selectReaction(selectedGroup, r3, r4); //step3bTime += System.nanoTime() - step3bInitial; //System.err.println(selectedReactionID + " " + reactionToPropensityMap.get(selectedReactionID)); //STEP 4: perform selected reaction and update species counts //long step4Initial = System.nanoTime(); performReaction(selectedReactionID, noAssignmentRulesFlag, noConstraintsFlag); //step4Time += System.nanoTime() - step4Initial; //STEP 5: compute affected reactions' new propensities and update total propensity //long step5Initial = System.nanoTime(); //create a set (precludes duplicates) of reactions that the selected reaction's species affect HashSet<String> affectedReactionSet = getAffectedReactionSet(selectedReactionID, noAssignmentRulesFlag); boolean newMinPropensityFlag = updatePropensities(affectedReactionSet); //step5Time += System.nanoTime() - step5Initial; //STEP 6: re-assign affected reactions to appropriate groups //long step6Initial = System.nanoTime(); //if there's a new minPropensity, then the group boundaries change //so re-calculate all groups if (newMinPropensityFlag == true) reassignAllReactionsToGroups(); else updateGroups(affectedReactionSet); //step6Time += System.nanoTime() - step6Initial; } //update time for next iteration currentTime += delta_t; if (variableToIsInAssignmentRuleMap != null && variableToIsInAssignmentRuleMap.containsKey("time")) performAssignmentRules(variableToAffectedAssignmentRuleSetMap.get("time")); //add events to queue if they trigger if (noEventsFlag == false) { handleEvents(noAssignmentRulesFlag, noConstraintsFlag); if (!triggeredEventQueue.isEmpty() && (triggeredEventQueue.peek().fireTime <= currentTime)) currentTime = triggeredEventQueue.peek().fireTime; } while ((currentTime > printTime) && (printTime < timeLimit)) { try { printToTSD(printTime); bufferedTSDWriter.write(",\n"); } catch (IOException e) { e.printStackTrace(); } // for (String speciesID : speciesIDSet) // if (speciesID.contains("ROW")) // System.err.println(speciesID + " " + variableToValueMap.get(speciesID)); // System.err.println(); // System.err.println(); printTime += printInterval; running.setTitle("Progress (" + (int)((currentTime / timeLimit) * 100.0) + "%)"); } } //end simulation loop // System.err.println("total time: " + String.valueOf((initializationTime + System.nanoTime() - // initTime2 - initTime3) / 1e9f)); // System.err.println("total step 1 time: " + String.valueOf(step1Time / 1e9f)); // System.err.println("total step 2 time: " + String.valueOf(step2Time / 1e9f)); // System.err.println("total step 3a time: " + String.valueOf(step3aTime / 1e9f)); // System.err.println("total step 3b time: " + String.valueOf(step3bTime / 1e9f)); // System.err.println("total step 4 time: " + String.valueOf(step4Time / 1e9f)); // System.err.println("total step 5 time: " + String.valueOf(step5Time / 1e9f)); // System.err.println("total step 6 time: " + String.valueOf(step6Time / 1e9f)); if (cancelFlag == false) { //print the final species counts try { printToTSD(printTime); } catch (IOException e) { e.printStackTrace(); } try { bufferedTSDWriter.write(')'); bufferedTSDWriter.flush(); } catch (IOException e1) { e1.printStackTrace(); } } // System.err.println("grid " + diffCount); // System.err.println((double) diffCount / (double) totalCount); // System.err.println("membrane " + memCount); // System.err.println((double) memCount / (double) totalCount); // System.err.println("total " + totalCount); } /** * initializes data structures local to the SSA-CR method * calculates initial propensities and assigns reactions to groups * * @param noEventsFlag * @param noAssignmentRulesFlag * @param noConstraintsFlag * * @throws IOException * @throws XMLStreamException */ private void initialize(long randomSeed, int runNumber) throws IOException, XMLStreamException { reactionToGroupMap = new TObjectIntHashMap<String>((int) (numReactions * 1.5)); groupToMaxValueMap = new TIntDoubleHashMap(); groupToPropensityFloorMap = new TIntDoubleHashMap(); groupToPropensityCeilingMap = new TIntDoubleHashMap(); groupToReactionSetList = new ArrayList<HashSet<String> >(); groupToTotalGroupPropensityMap = new TIntDoubleHashMap(); nonemptyGroupSet = new TIntHashSet(); eventsFlag = new MutableBoolean(false); rulesFlag = new MutableBoolean(false); constraintsFlag = new MutableBoolean(false); setupArrays(); setupSpecies(); setupParameters(); setupRules(); setupInitialAssignments(); setupConstraints(); if (numEvents == 0) eventsFlag.setValue(true); else eventsFlag.setValue(false); if (numAssignmentRules == 0 && numRateRules == 0) rulesFlag.setValue(true); else rulesFlag.setValue(false); if (numConstraints == 0) constraintsFlag.setValue(true); else constraintsFlag.setValue(false); //STEP 0A: calculate initial propensities (including the total) setupReactions(); //STEP OB: create and populate initial groups createAndPopulateInitialGroups(); setupEvents(); setupForOutput(randomSeed, runNumber); if (dynamicBoolean == true) { setupGrid(); createModelCopy(); } HashSet<String> comps = new HashSet<String>(); comps.addAll(componentToLocationMap.keySet()); if (dynamicBoolean == false) { bufferedTSDWriter.write("(" + "\"" + "time" + "\""); //if there's an interesting species, only those get printed if (interestingSpecies.size() > 0) { for (String speciesID : interestingSpecies) bufferedTSDWriter.write(", \"" + speciesID + "\""); } else { for (String speciesID : speciesIDSet) { bufferedTSDWriter.write(", \"" + speciesID + "\""); } //print compartment IDs (for sizes) for (String componentID : compartmentIDSet) { bufferedTSDWriter.write(", \"" + componentID + "\""); } //print nonconstant parameter IDs for (String parameterID : nonconstantParameterIDSet) { try { bufferedTSDWriter.write(", \"" + parameterID + "\""); } catch (IOException e) { e.printStackTrace(); } } } bufferedTSDWriter.write("),\n"); } } /** * creates the appropriate number of groups and associates reactions with groups */ private void createAndPopulateInitialGroups() { //create groups int currentGroup = 1; double groupPropensityCeiling = 2 * minPropensity; groupToPropensityFloorMap.put(1, minPropensity); while (groupPropensityCeiling < maxPropensity) { groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling); groupToPropensityFloorMap.put(currentGroup + 1, groupPropensityCeiling); groupToMaxValueMap.put(currentGroup, 0.0); groupPropensityCeiling *= 2; ++currentGroup; } //if there are no non-zero groups if (minPropensity == 0) { numGroups = 1; groupToReactionSetList.add(new HashSet<String>(500)); } else { numGroups = currentGroup + 1; groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling); groupToMaxValueMap.put(currentGroup, 0.0); //start at 0 to make a group for zero propensities for (int groupNum = 0; groupNum < numGroups; ++groupNum) { groupToReactionSetList.add(new HashSet<String>(500)); groupToTotalGroupPropensityMap.put(groupNum, 0.0); } } //assign reactions to groups for (String reaction : reactionToPropensityMap.keySet()) { double propensity = reactionToPropensityMap.get(reaction); org.openmali.FastMath.FRExpResultf frexpResult = org.openmali.FastMath.frexp((float) (propensity / minPropensity)); int group = frexpResult.exponent; groupToTotalGroupPropensityMap.adjustValue(group, propensity); groupToReactionSetList.get(group).add(reaction); reactionToGroupMap.put(reaction, group); if (propensity > groupToMaxValueMap.get(group)) groupToMaxValueMap.put(group, propensity); } //find out which (if any) groups are empty //this is done so that empty groups are never chosen during simulation for (int groupNum = 1; groupNum < numGroups; ++groupNum) { if (groupToReactionSetList.get(groupNum).isEmpty()) continue; nonemptyGroupSet.add(groupNum); } } /** * cancels the current run */ protected void cancel() { cancelFlag = true; } /** * clears data structures for new run */ protected void clear() { variableToValueMap.clear(); reactionToPropensityMap.clear(); if (numEvents > 0) { triggeredEventQueue.clear(); untriggeredEventSet.clear(); eventToPriorityMap.clear(); eventToDelayMap.clear(); } reactionToGroupMap.clear(); reactionToFormulaMap.clear(); groupToMaxValueMap.clear(); groupToPropensityFloorMap.clear(); groupToPropensityCeilingMap.clear(); groupToReactionSetList.clear(); groupToTotalGroupPropensityMap.clear(); nonemptyGroupSet.clear(); speciesIDSet.clear(); componentToLocationMap.clear(); componentToReactionSetMap.clear(); componentToVariableSetMap.clear(); componentToEventSetMap.clear(); compartmentIDSet.clear(); nonconstantParameterIDSet.clear(); minRow = Integer.MAX_VALUE; minCol = Integer.MAX_VALUE; maxRow = Integer.MIN_VALUE; maxCol = Integer.MIN_VALUE; //get rid of things that were created dynamically this run //or else dynamically created stuff will still be in the model next run if (dynamicBoolean == true) { resetModel(); } } /** * removes a component's reactions from reactionToGroupMap and groupToReactionSetList */ protected void eraseComponentFurther(HashSet<String> reactionIDs) { for (String reactionID : reactionIDs) { int group = reactionToGroupMap.get(reactionID); reactionToGroupMap.remove(reactionID); groupToReactionSetList.get(group).remove(reactionID); } } /** * assigns all reactions to (possibly new) groups * this is called when the minPropensity changes, which * changes the groups' floor/ceiling propensity values */ private void reassignAllReactionsToGroups() { int currentGroup = 1; double groupPropensityCeiling = 2 * minPropensity; //re-calulate and store group propensity floors/ceilings groupToPropensityCeilingMap.clear(); groupToPropensityFloorMap.clear(); groupToPropensityFloorMap.put(1, minPropensity); while (groupPropensityCeiling <= maxPropensity) { groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling); groupToPropensityFloorMap.put(currentGroup + 1, groupPropensityCeiling); groupPropensityCeiling *= 2; ++currentGroup; } groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling); int newNumGroups = currentGroup + 1; //allocate memory if the number of groups expands if (newNumGroups > numGroups) { for (int groupNum = numGroups; groupNum < newNumGroups; ++groupNum) groupToReactionSetList.add(new HashSet<String>(500)); } //clear the reaction set for each group //start at 1, as the zero propensity group isn't going to change for (int groupNum = 1; groupNum < newNumGroups; ++groupNum) { groupToReactionSetList.get(groupNum).clear(); groupToMaxValueMap.put(groupNum, 0.0); groupToTotalGroupPropensityMap.put(groupNum, 0.0); } numGroups = newNumGroups; totalPropensity = 0; //assign reactions to groups for (String reaction : reactionToPropensityMap.keySet()) { double propensity = reactionToPropensityMap.get(reaction); totalPropensity += propensity; //the zero-propensity group doesn't need altering if (propensity == 0.0) { reactionToGroupMap.put(reaction, 0); groupToReactionSetList.get(0).add(reaction); } org.openmali.FastMath.FRExpResultf frexpResult = org.openmali.FastMath.frexp((float) (propensity / minPropensity)); int group = frexpResult.exponent; groupToReactionSetList.get(group).add(reaction); reactionToGroupMap.put(reaction, group); groupToTotalGroupPropensityMap.adjustValue(group, propensity); if (propensity > groupToMaxValueMap.get(group)) groupToMaxValueMap.put(group, propensity); } //find out which (if any) groups are empty //this is done so that empty groups are never chosen during simulation nonemptyGroupSet.clear(); for (int groupNum = 1; groupNum < numGroups; ++groupNum) { if (groupToReactionSetList.get(groupNum).isEmpty()) continue; nonemptyGroupSet.add(groupNum); } } /** * chooses a random number between 0 and the total propensity * then it finds which nonempty group this number belongs to * * @param r2 random number * @return the group selected */ private int selectGroup(double r2) { if (nonemptyGroupSet.size() == 0) return 0; double randomPropensity = r2 * (totalPropensity); double runningTotalGroupsPropensity = 0.0; int selectedGroup = 1; // System.err.println(reactionToGroupMap); // System.err.println(randomPropensity); // System.err.println(totalPropensity); // System.err.println(); //finds the group that the random propensity lies in //it keeps adding the next group's total propensity to a running total //until the running total is greater than the random propensity for (; selectedGroup < numGroups; ++selectedGroup) { runningTotalGroupsPropensity += groupToTotalGroupPropensityMap.get(selectedGroup); // System.err.println(selectedGroup + " " + nonemptyGroupSet.contains(selectedGroup) // + " " + groupToTotalGroupPropensityMap.get(selectedGroup)); // System.err.println(runningTotalGroupsPropensity); if (randomPropensity < runningTotalGroupsPropensity && nonemptyGroupSet.contains(selectedGroup)) break; } // System.err.println(selectedGroup); // System.err.println(); // if (selectedGroup == 17) // System.err.println(nonemptyGroupSet); return selectedGroup; } /** * from the selected group, a reaction is chosen randomly/uniformly * a random number between 0 and the group's max propensity is then chosen * if this number is not less than the chosen reaction's propensity, * the reaction is rejected and the process is repeated until success occurs * * @param selectedGroup the group to choose a reaction from * @param r3 * @param r4 * @return the chosen reaction's ID */ private String selectReaction(int selectedGroup, double r3, double r4) { HashSet<String> reactionSet = groupToReactionSetList.get(selectedGroup); double randomIndex = FastMath.floor(r3 * reactionSet.size()); int indexIter = 0; Iterator<String> reactionSetIterator = reactionSet.iterator(); while (reactionSetIterator.hasNext() && indexIter < randomIndex) { reactionSetIterator.next(); ++indexIter; } String selectedReactionID = reactionSetIterator.next(); double reactionPropensity = reactionToPropensityMap.get(selectedReactionID); //this is choosing a value between 0 and the max propensity in the group double randomPropensity = r4 * groupToMaxValueMap.get(selectedGroup); //loop until there's no reaction rejection //if the random propensity is higher than the selected reaction's propensity, another random reaction is chosen while (randomPropensity > reactionPropensity) { r3 = randomNumberGenerator.nextDouble(); r4 = randomNumberGenerator.nextDouble(); randomIndex = (int) FastMath.floor(r3 * reactionSet.size()); indexIter = 0; reactionSetIterator = reactionSet.iterator(); while (reactionSetIterator.hasNext() && (indexIter < randomIndex)) { reactionSetIterator.next(); ++indexIter; } selectedReactionID = reactionSetIterator.next(); reactionPropensity = reactionToPropensityMap.get(selectedReactionID); randomPropensity = r4 * groupToMaxValueMap.get(selectedGroup); } return selectedReactionID; } /** * does a minimized initialization process to prepare for a new run */ protected void setupForNewRun(int newRun) { try { setupSpecies(); } catch (IOException e) { e.printStackTrace(); } setupParameters(); setupInitialAssignments(); setupRules(); setupConstraints(); totalPropensity = 0.0; numGroups = 0; minPropensity = Double.MAX_VALUE; maxPropensity = Double.MIN_VALUE; if (numEvents == 0) eventsFlag.setValue(true); else eventsFlag.setValue(false); if (numAssignmentRules == 0 && numRateRules == 0) rulesFlag.setValue(true); else rulesFlag.setValue(false); if (numConstraints == 0) constraintsFlag.setValue(true); else constraintsFlag.setValue(false); //STEP 0A: calculate initial propensities (including the total) setupReactions(); //STEP OB: create and populate initial groups createAndPopulateInitialGroups(); setupEvents(); setupForOutput(0, newRun); if (dynamicBoolean == true) { setupGrid(); } } /** * updates the groups */ protected void updateAfterDynamicChanges() { reassignAllReactionsToGroups(); } /** * updates the groups of the reactions affected by the recently performed reaction * ReassignAllReactionsToGroups() is called instead when all reactions need changing * * @param affectedReactionSet the set of reactions affected by the recently performed reaction */ private void updateGroups(HashSet<String> affectedReactionSet) { //update the groups for all of the affected reactions //their propensities have changed and they may need to go into a different group for (String affectedReactionID : affectedReactionSet) { double newPropensity = reactionToPropensityMap.get(affectedReactionID); int oldGroup = reactionToGroupMap.get(affectedReactionID); if (newPropensity == 0.0) { HashSet<String> oldReactionSet = groupToReactionSetList.get(oldGroup); //update group collections //zero propensities go into group 0 oldReactionSet.remove(affectedReactionID); reactionToGroupMap.put(affectedReactionID, 0); groupToReactionSetList.get(0).add(affectedReactionID); if (oldReactionSet.size() == 0) { nonemptyGroupSet.remove(oldGroup); } } //if the new propensity != 0.0 (ie, new group != 0) else { //if it's outside of the old group's boundaries if (newPropensity > groupToPropensityCeilingMap.get(oldGroup) || newPropensity < groupToPropensityFloorMap.get(oldGroup)) { org.openmali.FastMath.FRExpResultf frexpResult = org.openmali.FastMath.frexp((float) (newPropensity / minPropensity)); int group = frexpResult.exponent; //if the group is one that currently exists if (group < numGroups) { HashSet<String> newGroupReactionSet = groupToReactionSetList.get(group); HashSet<String> oldGroupReactionSet = groupToReactionSetList.get(oldGroup); //update group collections oldGroupReactionSet.remove(affectedReactionID); reactionToGroupMap.put(affectedReactionID, group); newGroupReactionSet.add(affectedReactionID); groupToTotalGroupPropensityMap.adjustValue(group, newPropensity); //if the group that the reaction was just added to is now nonempty if (newGroupReactionSet.size() == 1) nonemptyGroupSet.add(group); if (oldGroupReactionSet.size() == 0) { nonemptyGroupSet.remove(oldGroup); } if (newPropensity > groupToMaxValueMap.get(group)) groupToMaxValueMap.put(group, newPropensity); } //this means the propensity goes into a group that doesn't currently exist else { //groupToReactionSetList is a list, so the group needs to be the index for (int iter = numGroups; iter <= group; ++iter) { if (iter >= groupToReactionSetList.size()) groupToReactionSetList.add(new HashSet<String>(500)); groupToTotalGroupPropensityMap.put(iter, 0.0); } numGroups = group + 1; HashSet<String> oldReactionSet = groupToReactionSetList.get(oldGroup); //update group collections groupToTotalGroupPropensityMap.adjustValue(group, newPropensity); groupToReactionSetList.get(oldGroup).remove(affectedReactionID); reactionToGroupMap.put(affectedReactionID, group); groupToReactionSetList.get(group).add(affectedReactionID); nonemptyGroupSet.add(group); groupToMaxValueMap.put(group, newPropensity); if (oldReactionSet.size() == 0) nonemptyGroupSet.remove(oldGroup); } } //if it's within the old group's boundaries (ie, group isn't changing) else { //maintain current group if (newPropensity > groupToMaxValueMap.get(oldGroup)) groupToMaxValueMap.put(oldGroup, newPropensity); groupToTotalGroupPropensityMap.adjustValue(oldGroup, newPropensity); } } } } /** * updates the propensities of the reactions affected by the recently performed reaction * @param affectedReactionSet the set of reactions affected by the recently performed reaction * @return whether or not there's a new minPropensity (if there is, all reaction's groups need to change) */ private boolean updatePropensities(HashSet<String> affectedReactionSet) { boolean newMinPropensityFlag = false; //loop through the affected reactions and update the propensities for (String affectedReactionID : affectedReactionSet) { boolean notEnoughMoleculesFlag = false; HashSet<StringDoublePair> reactantStoichiometrySet = reactionToReactantStoichiometrySetMap.get(affectedReactionID); if (reactantStoichiometrySet == null) continue; //check for enough molecules for the reaction to occur for (StringDoublePair speciesAndStoichiometry : reactantStoichiometrySet) { String speciesID = speciesAndStoichiometry.string; double stoichiometry = speciesAndStoichiometry.doub; //if there aren't enough molecules to satisfy the stoichiometry if (variableToValueMap.get(speciesID) < stoichiometry) { notEnoughMoleculesFlag = true; break; } } double newPropensity = 0.0; if (notEnoughMoleculesFlag == false) { newPropensity = evaluateExpressionRecursive(reactionToFormulaMap.get(affectedReactionID)); } //stoichiometry amplification -- alter the propensity if (affectedReactionID.contains("_Diffusion_") && stoichAmpBoolean == true) { newPropensity *= (1.0 / stoichAmpGridValue); } if (newPropensity > 0.0 && newPropensity < minPropensity) { minPropensity = newPropensity; newMinPropensityFlag = true; } if (newPropensity > maxPropensity) maxPropensity = newPropensity; double oldPropensity = reactionToPropensityMap.get(affectedReactionID); int oldGroup = reactionToGroupMap.get(affectedReactionID); // if (oldGroup == 15) { // if (newPropensity == 0) // System.err.println(affectedReactionID + " NOW IS ZERO"); // if (oldPropensity == 0) // System.err.println(affectedReactionID + " still has propensity zero"); // System.err.println("oldgroup: " + oldGroup); // System.err.println(groupToTotalGroupPropensityMap.get(oldGroup) + " - " + oldPropensity); //remove the old propensity from the group's total //later on, the new propensity is added to the (possibly new) group's total groupToTotalGroupPropensityMap.adjustValue(oldGroup, -oldPropensity); //add the difference of new v. old propensity to the total propensity totalPropensity += newPropensity - oldPropensity; reactionToPropensityMap.put(affectedReactionID, newPropensity); } return newMinPropensityFlag; } }
package org.intermine.api.bag; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.log4j.Logger; import org.intermine.api.profile.BagState; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.api.profile.TagManager; import org.intermine.api.profile.TagManager.TagNameException; import org.intermine.api.profile.TagManager.TagNamePermissionException; import org.intermine.api.profile.TagManagerFactory; import org.intermine.api.tag.TagNames; import org.intermine.api.tag.TagTypes; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.ObjectStoreBag; import org.intermine.objectstore.query.ObjectStoreBagsForObject; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.Results; /** * A BagManager provides access to all global and/or user bags and methods to fetch them by * type, etc. * @author Richard Smith * */ public class BagManager { private static final Logger LOG = Logger.getLogger(BagManager.class); private final Profile superProfile; private final TagManager tagManager; private final Model model; private final ObjectStore osProduction; /** * The BagManager references the super user profile to fetch global bags. * @param superProfile the super user profile * @param model the object model */ public BagManager(Profile superProfile, Model model) { this.superProfile = superProfile; if (superProfile == null) { String msg = "Unable to retrieve superuser profile. Check that the superuser profile " + "in the MINE.properties file matches the superuser in the userprofile database."; LOG.error(msg); throw new RuntimeException(msg); } this.model = model; this.tagManager = new TagManagerFactory(superProfile.getProfileManager()).getTagManager(); this.osProduction = superProfile.getProfileManager().getProductionObjectStore(); } /** * Fetch globally available bags - superuser public bags that are available to everyone. * @return a map from bag name to bag */ public Map<String, InterMineBag> getGlobalBags() { return getBagsWithTag(superProfile, TagNames.IM_PUBLIC); } /** * Get global bags/lists that have a specific tag * @param tag * @return */ public Map<String, InterMineBag> getGlobalBagsWithTag(String tag) { return getBagsWithTag(superProfile, tag); } public Map<String, InterMineBag> getGlobalBagsWithTags(List<String> tags) { return getBagsWithTags(superProfile, tags); } /** * Fetch bags from given protocol with a particular tag assigned to them. * @param profile the user to fetch bags from * @param tag the tag to filter * @return a map from bag name to bag */ protected Map<String, InterMineBag> getBagsWithTag(Profile profile, String tag) { Map<String, InterMineBag> bagsWithTag = new HashMap<String, InterMineBag>(); for (Map.Entry<String, InterMineBag> entry : profile.getSavedBags().entrySet()) { InterMineBag bag = entry.getValue(); List<Tag> tags = tagManager.getTags(tag, bag.getName(), TagTypes.BAG, profile.getUsername()); if (tags.size() > 0) { bagsWithTag.put(entry.getKey(), entry.getValue()); } } return bagsWithTag; } /** * Give me profile bags matching a set of tags * @param profile The profile these bags must belong to. * @param tags The tags each bag must have. * @return The bags of a profile with all of the required tags. */ protected Map<String, InterMineBag> getBagsWithTags(Profile profile, List<String> tags) { Map<String, InterMineBag> bagsWithTags = new HashMap<String, InterMineBag>(); outer: for (Map.Entry<String, InterMineBag> entry : profile.getSavedBags().entrySet()) { // gimme the bag InterMineBag bag = entry.getValue(); // bag's tags List<Tag> bagTags = getTagsForBag(bag, profile); // do we have a winner? inner: for (String requiredTag : tags) { for (Tag bagTag : bagTags) { if (bagTag.getTagName().equals(requiredTag)) { continue inner; } } continue outer; } bagsWithTags.put(entry.getKey(), entry.getValue()); } return bagsWithTags; } public void addTagsToBag(Collection<String> tags, InterMineBag bag, Profile profile) throws TagNameException, TagNamePermissionException { for (String tag: tags) { tagManager.addTag(tag, bag, profile); } } /** * Return true if the bag is public. * @param bag The bag in question. * @return True if tagged with "im:public" */ public boolean isPublic(InterMineBag bag) { return tagManager.hasTag(TagNames.IM_PUBLIC, bag); } /** * Get a list of tags for a given bag. * @param bag The bag to get tags for. * @param profile The profile whose tags we are looking for. * @return A list of Tag objects */ public List<Tag> getTagsForBag(InterMineBag bag, Profile profile) { List<Tag> tags = new ArrayList<Tag>(tagManager.getTags(TagNames.IM_PUBLIC, bag.getName(), TagTypes.BAG, null)); tags.addAll(tagManager.getObjectTags(bag, profile)); return tags; } /** * Fetch bags for the given profile. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserBags(Profile profile) { return profile.getSavedBags(); } /** * Return true if there is at least one bag for the given profile in the 'not_current' state. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public boolean isAnyBagNotCurrent(Profile profile) { Map<String, InterMineBag> savedBags = profile.getSavedBags(); for (InterMineBag bag : savedBags.values()) { if (bag.getState().equals(BagState.NOT_CURRENT.toString())) { return true; } } return false; } /** * Return true if there is at least one bag for the given profile in the 'to_upgrade' state. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public boolean isAnyBagToUpgrade(Profile profile) { Map<String, InterMineBag> savedBags = profile.getSavedBags(); for (InterMineBag bag : savedBags.values()) { if (bag.getState().equals(BagState.TO_UPGRADE.toString())) { return true; } } return false; } /** * Fetch all global bags and user bags combined in the same map. If user has a bag with the * same name as a global bag the user's bag takes precedence. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserAndGlobalBags(Profile profile) { // add global bags first, any user bags with same name take precedence Map<String, InterMineBag> allBags = new HashMap<String, InterMineBag>(); allBags.putAll(getGlobalBags()); if (profile != null) { Map<String, InterMineBag> savedBags = profile.getSavedBags(); synchronized (savedBags) { allBags.putAll(savedBags); } } return allBags; } /** * Order a map of bags by im:order:n tag * @param bags unordered * @return an ordered Map of InterMineBags */ public Map<String, InterMineBag> orderBags(Map<String, InterMineBag> bags) { Map<String, InterMineBag> bagsOrdered = new TreeMap<String, InterMineBag>(new ByTagOrder()); bagsOrdered.putAll(bags); return bagsOrdered; } /** * Fetch a global bag by name. * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getGlobalBag(String bagName) { return getGlobalBags().get(bagName); } /** * Fetch a user bag by name. * @param profile the user to fetch bags for * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getUserBag(Profile profile, String bagName) { return getUserBags(profile).get(bagName); } /** * Fetch a global or user bag by name. If user has a bag with the same name as a global bag * the user's bag takes precedence. * @param profile the user to fetch bags for * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getUserOrGlobalBag(Profile profile, String bagName) { return getUserAndGlobalBags(profile).get(bagName); } /** * Fetch global and user bags of the specified type or a subclass of the specified type. * @param profile the user to fetch bags for * @param type an unqualified class name * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserOrGlobalBagsOfType(Profile profile, String type) { return getUserOrGlobalBagsOfType(profile, type, false); } /** * Fetch global and user bags current of the specified type or a subclass of the specified type. * @param profile the user to fetch bags for * @param type an unqualified class name * @return a map from bag name to bag */ public Map<String, InterMineBag> getCurrentUserOrGlobalBagsOfType(Profile profile, String type) { return getUserOrGlobalBagsOfType(profile, type, true); } /** * Fetch global and user bags of the specified type or a subclass of the specified type. * @param profile the user to fetch bags for * @param type an unqualified class name * @param onlyCurrent if true return only the current bags * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserOrGlobalBagsOfType(Profile profile, String type, boolean onlyCurrent) { return filterBagsByType(getUserAndGlobalBags(profile), type, onlyCurrent); } /** * Fetch user bags curent of the specified type or a subclass of the specified type. * @param profile the user to fetch bags for * @param type an unqualified class name * @return a map from bag name to bag */ public Map<String, InterMineBag> getCurrentUserBagsOfType(Profile profile, String type) { return filterBagsByType(getUserBags(profile), type, true); } private Map<String, InterMineBag> filterBagsByType(Map<String, InterMineBag> bags, String type, boolean onlyCurrent) { Set<String> classAndSubs = new HashSet<String>(); classAndSubs.add(type); ClassDescriptor bagTypeCld = model.getClassDescriptorByName(type); if (bagTypeCld == null) { throw new NullPointerException("Could not find ClassDescriptor for name " + type); } for (ClassDescriptor cld : model.getAllSubs(bagTypeCld)) { classAndSubs.add(cld.getUnqualifiedName()); } Map<String, InterMineBag> bagsOfType = new HashMap<String, InterMineBag>(); for (Map.Entry<String, InterMineBag> entry : bags.entrySet()) { InterMineBag bag = entry.getValue(); if (classAndSubs.contains(bag.getType())) { if ((onlyCurrent && bag.isCurrent()) || !onlyCurrent) { bagsOfType.put(entry.getKey(), bag); } } } return bagsOfType; } /** * Fetch global bags that contain the given id. * @param id the id to search bags for * @return bags containing the given id */ public Collection<InterMineBag> getGlobalBagsContainingId(Integer id) { return getBagsContainingId(getGlobalBags(), id); } /** * Fetch user bags that contain the given id. * @param id the id to search bags for * @param profile the user to fetch bags from * @return bags containing the given id */ public Collection<InterMineBag> getUserBagsContainingId(Profile profile, Integer id) { return getBagsContainingId(getUserBags(profile), id); } /** * Fetch the current user or global bags that contain the given id. If user has a bag * with the same name as a global bag the user's bag takes precedence. * Only current bags are included. * @param id the id to search bags for * @param profile the user to fetch bags from * @return bags containing the given id */ public Collection<InterMineBag> getCurrentUserOrGlobalBagsContainingId(Profile profile, Integer id) { HashSet<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); for (InterMineBag bag: getGlobalBagsContainingId(id)) { if (bag.isCurrent()) { bagsContainingId.add(bag); } } for (InterMineBag bag: getUserBagsContainingId(profile, id)) { if (bag.isCurrent()) { bagsContainingId.add(bag); } } return bagsContainingId; } private Collection<InterMineBag> getBagsContainingId(Map<String, InterMineBag> imBags, Integer id) { Collection<ObjectStoreBag> objectStoreBags = getObjectStoreBags(imBags.values()); Map<Integer, InterMineBag> osBagIdToInterMineBag = getOsBagIdToInterMineBag(imBags.values()); // this searches bags for an object ObjectStoreBagsForObject osbo = new ObjectStoreBagsForObject(id, objectStoreBags); // run query Query q = new Query(); q.addToSelect(osbo); Collection<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); // this should return all bags with that object Results res = osProduction.executeSingleton(q); Iterator<Object> resIter = res.iterator(); while (resIter.hasNext()) { Integer osBagId = (Integer) resIter.next(); if (osBagIdToInterMineBag.containsKey(osBagId)) { bagsContainingId.add(osBagIdToInterMineBag.get(osBagId)); } } return bagsContainingId; } private Map<Integer, InterMineBag> getOsBagIdToInterMineBag(Collection<InterMineBag> imBags) { Map<Integer, InterMineBag> osBagIdToInterMineBag = new HashMap<Integer, InterMineBag>(); for (InterMineBag imBag : imBags) { osBagIdToInterMineBag.put(new Integer(imBag.getOsb().getBagId()), imBag); } return osBagIdToInterMineBag; } private Collection<ObjectStoreBag> getObjectStoreBags(Collection<InterMineBag> imBags) { Set<ObjectStoreBag> objectStoreBags = new HashSet<ObjectStoreBag>(); for (InterMineBag imBag : imBags) { objectStoreBags.add(imBag.getOsb()); } return objectStoreBags; } /** * Compare lists based on their im:order:n tag * @author radek * */ public class ByTagOrder implements Comparator<String> { /** * For a list of tags corresponding to a bag, give us the order set in im:order:n * @param tags * @return */ private Integer resolveOrderFromTagsList(List<Tag> tags) { for (Tag t : tags) { String name = t.getTagName(); if (name.startsWith("im:order:")) { return Integer.parseInt(name.replaceAll("[^0-9]", "")); } } return Integer.MAX_VALUE; } @Override public int compare(String aK, String bK) { // get the order from the tags for the bags for the superduper profile Integer aO = resolveOrderFromTagsList(tagManager.getTags(null, aK, TagTypes.BAG, null)); Integer bO = resolveOrderFromTagsList(tagManager.getTags(null, bK, TagTypes.BAG, null)); if (aO < bO) { return -1; } else { if (aO > bO) { return 1; } else { CaseInsensitiveComparator cic = new CaseInsensitiveComparator(); return cic.compare(aK, bK); } } } } /** * Lower-case key comparator * @author radek * */ public class CaseInsensitiveComparator implements Comparator<String> { @Override public int compare(String aK, String bK) { return aK.toLowerCase().compareTo(bK.toLowerCase()); } } }
package bisq.inventory; import bisq.core.network.p2p.inventory.GetInventoryRequestManager; import bisq.core.network.p2p.seed.DefaultSeedNodeRepository; import bisq.core.proto.network.CoreNetworkProtoResolver; import bisq.network.p2p.NetworkNodeProvider; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.network.NetworkNode; import bisq.network.p2p.network.SetupListener; import bisq.common.UserThread; import bisq.common.app.Capabilities; import bisq.common.app.Capability; import bisq.common.config.BaseCurrencyNetwork; import bisq.common.file.JsonFileManager; import bisq.common.util.Utilities; import java.time.Clock; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Slf4j public class InventoryMonitor { private final Map<NodeAddress, JsonFileManager> jsonFileManagerByNodeAddress = new HashMap<>(); private final boolean useLocalhostForP2P; private final int intervalSec; public InventoryMonitor(File appDir, boolean useLocalhostForP2P, BaseCurrencyNetwork network, int intervalSec, int port) { this.useLocalhostForP2P = useLocalhostForP2P; this.intervalSec = intervalSec; setupCapabilities(); DefaultSeedNodeRepository.readSeedNodePropertyFile(network) .ifPresent(seedNodeFile -> { List<NodeAddress> seedNodes = new ArrayList<>(DefaultSeedNodeRepository.getSeedNodeAddressesFromPropertyFile(network)); File jsonDir = new File(appDir, "json"); if (!jsonDir.exists() && !jsonDir.mkdir()) { log.warn("make jsonDir failed"); } seedNodes.forEach(nodeAddress -> { JsonFileManager jsonFileManager = new JsonFileManager(new File(jsonDir, getShortAddress(nodeAddress, useLocalhostForP2P))); jsonFileManagerByNodeAddress.put(nodeAddress, jsonFileManager); }); NetworkNode networkNode = getNetworkNode(appDir); GetInventoryRequestManager getInventoryRequestManager = new GetInventoryRequestManager(networkNode); InventoryWebServer inventoryWebServer = new InventoryWebServer(port, seedNodes, seedNodeFile); networkNode.start(new SetupListener() { @Override public void onTorNodeReady() { startRequests(inventoryWebServer, getInventoryRequestManager, seedNodes); } @Override public void onHiddenServicePublished() { } @Override public void onSetupFailed(Throwable throwable) { } @Override public void onRequestCustomBridges() { } }); }); } private NetworkNode getNetworkNode(File appDir) { File torDir = new File(appDir, "tor"); CoreNetworkProtoResolver networkProtoResolver = new CoreNetworkProtoResolver(Clock.systemDefaultZone()); return new NetworkNodeProvider(networkProtoResolver, ArrayList::new, useLocalhostForP2P, 9999, torDir, null, "", -1, "", null, false, false).get(); } protected void setupCapabilities() { Capabilities.app.addAll( Capability.TRADE_STATISTICS, Capability.TRADE_STATISTICS_2, Capability.ACCOUNT_AGE_WITNESS, Capability.ACK_MSG, Capability.PROPOSAL, Capability.BLIND_VOTE, Capability.DAO_STATE, Capability.BUNDLE_OF_ENVELOPES, Capability.MEDIATION, Capability.SIGNED_ACCOUNT_AGE_WITNESS, Capability.REFUND_AGENT, Capability.TRADE_STATISTICS_HASH_UPDATE, Capability.NO_ADDRESS_PRE_FIX, Capability.TRADE_STATISTICS_3, Capability.RECEIVE_BSQ_BLOCK ); } private String getShortAddress(NodeAddress nodeAddress, boolean useLocalhostForP2P) { return useLocalhostForP2P ? nodeAddress.getFullAddress().replace(":", "_") : nodeAddress.getFullAddress().substring(0, 10); } private void startRequests(InventoryWebServer inventoryWebServer, GetInventoryRequestManager getInventoryRequestManager, List<NodeAddress> seedNodes) { UserThread.runPeriodically(() -> requestAllSeeds(inventoryWebServer, getInventoryRequestManager, seedNodes), intervalSec); requestAllSeeds(inventoryWebServer, getInventoryRequestManager, seedNodes); } private void requestAllSeeds(InventoryWebServer inventoryWebServer, GetInventoryRequestManager getInventoryRequestManager, List<NodeAddress> seedNodes) { seedNodes.forEach(nodeAddress -> { RequestInfo requestInfo = new RequestInfo(System.currentTimeMillis()); new Thread(() -> { Thread.currentThread().setName("request @ " + getShortAddress(nodeAddress, useLocalhostForP2P)); getInventoryRequestManager.request(nodeAddress, result -> { log.info("nodeAddress={}, result={}", nodeAddress, result.toString()); long responseTime = System.currentTimeMillis(); requestInfo.setResponseTime(responseTime); requestInfo.setInventory(result); inventoryWebServer.onNewRequestInfo(requestInfo, nodeAddress); String json = Utilities.objectToJson(requestInfo); jsonFileManagerByNodeAddress.get(nodeAddress).writeToDisc(json, String.valueOf(responseTime)); }, errorMessage -> { log.warn(errorMessage); requestInfo.setErrorMessage(errorMessage); }); }).start(); }); } public void shutDown() { jsonFileManagerByNodeAddress.values().forEach(JsonFileManager::shutDown); } @Getter public static class RequestInfo { private final long requestStartTime; @Setter private long responseTime; @Setter private Map<String, String> inventory; @Setter private String errorMessage; public RequestInfo(long requestStartTime) { this.requestStartTime = requestStartTime; } } }
package org.mwg; import io.undertow.connector.ByteBufferPool; import io.undertow.server.DefaultByteBufferPool; import io.undertow.websockets.client.WebSocketClient; import io.undertow.websockets.core.*; import org.mwg.utility.Base64; import org.mwg.chunk.Chunk; import org.mwg.plugin.Storage; import org.mwg.struct.Buffer; import org.mwg.struct.BufferIterator; import org.xnio.*; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; public class WSClient implements Storage { private final String url; private WebSocketChannel channel; private XnioWorker _worker; private Graph graph; private Map<Integer, Callback> callbacks; public WSClient(String p_url) { this.url = p_url; this.callbacks = new HashMap<Integer, Callback>(); } @Override public void get(Buffer keys, Callback<Buffer> callback) { send_rpc_req(WSConstants.REQ_GET, keys, callback); } @Override public void put(Buffer stream, Callback<Boolean> callback) { send_rpc_req(WSConstants.REQ_PUT, stream, callback); } @Override public void remove(Buffer keys, Callback<Boolean> callback) { send_rpc_req(WSConstants.REQ_REMOVE, keys, callback); } @Override public void lock(Callback<Buffer> callback) { send_rpc_req(WSConstants.REQ_LOCK, null, callback); } @Override public void unlock(Buffer previousLock, Callback<Boolean> callback) { send_rpc_req(WSConstants.REQ_UNLOCK, previousLock, callback); } @Override public void connect(final Graph p_graph, final Callback<Boolean> callback) { if (channel != null) { if (callback != null) { callback.on(true);//already connected } } this.graph = p_graph; try { Xnio xnio = Xnio.getInstance(io.undertow.websockets.client.WebSocketClient.class.getClassLoader()); _worker = xnio.createWorker(OptionMap.builder() .set(Options.WORKER_IO_THREADS, 2) .set(Options.CONNECTION_HIGH_WATER, 1000000) .set(Options.CONNECTION_LOW_WATER, 1000000) .set(Options.WORKER_TASK_CORE_THREADS, 30) .set(Options.WORKER_TASK_MAX_THREADS, 30) .set(Options.TCP_NODELAY, true) .set(Options.CORK, true) .getMap()); ByteBufferPool _buffer = new DefaultByteBufferPool(true, 1024 * 1024); WebSocketClient.ConnectionBuilder builder = io.undertow.websockets.client.WebSocketClient .connectionBuilder(_worker, _buffer, new URI(url)); /* if(_sslContext != null) { UndertowXnioSsl ssl = new UndertowXnioSsl(Xnio.getInstance(), OptionMap.EMPTY, _sslContext); builder.setSsl(ssl); }*/ IoFuture<WebSocketChannel> futureChannel = builder.connect(); futureChannel.await(5, TimeUnit.SECONDS); //Todo change this magic number!!! if (futureChannel.getStatus() != IoFuture.Status.DONE) { System.err.println("Error during connexion with webSocket"); if (callback != null) { callback.on(null); } } channel = futureChannel.get(); channel.getReceiveSetter().set(new MessageReceiver()); channel.resumeReceives(); if (callback != null) { callback.on(true); } } catch (Exception e) { if (callback != null) { callback.on(false); } e.printStackTrace(); } } @Override public void disconnect(Callback<Boolean> callback) { try { System.out.println("CloseClient"); channel.sendClose(); channel.close(); _worker.shutdown(); channel = null; _worker = null; } catch (IOException e) { e.printStackTrace(); } finally { callback.on(true); } } private class MessageReceiver extends AbstractReceiveListener { @Override protected void onFullBinaryMessage(WebSocketChannel channel, BufferedBinaryMessage message) throws IOException { ByteBuffer byteBuffer = WebSockets.mergeBuffers(message.getData().getResource()); process_rpc_resp(byteBuffer.array()); super.onFullBinaryMessage(channel, message); } @Override protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) throws IOException { process_rpc_resp(message.getData().getBytes()); super.onFullTextMessage(channel, message); } } private void send_rpc_req(byte code, Buffer payload, Callback callback) { if (channel == null) { throw new RuntimeException(WSConstants.DISCONNECTED_ERROR); } Buffer buffer = graph.newBuffer(); buffer.write(code); buffer.write(Constants.BUFFER_SEP); int hash = callback.hashCode(); callbacks.put(hash, callback); Base64.encodeIntToBuffer(hash, buffer); if (payload != null) { buffer.write(Constants.BUFFER_SEP); buffer.writeAll(payload.data()); } ByteBuffer wrapped = ByteBuffer.wrap(buffer.data()); buffer.free(); WebSockets.sendBinary(wrapped, channel, new WebSocketCallback<Void>() { @Override public void complete(WebSocketChannel webSocketChannel, Void aVoid) { } @Override public void onError(WebSocketChannel webSocketChannel, Void aVoid, Throwable throwable) { throwable.printStackTrace(); } }); } private void process_rpc_resp(byte[] payload) { Buffer payloadBuf = graph.newBuffer(); payloadBuf.writeAll(payload); BufferIterator it = payloadBuf.iterator(); Buffer codeView = it.next(); if (codeView != null && codeView.length() != 0) { final byte firstCode = codeView.read(0); if (firstCode == WSConstants.REQ_UPDATE) { Buffer updateBuf = graph.newBuffer(); boolean isFirst = true; while (it.hasNext()) { Buffer view = it.next(); ChunkKey key = ChunkKey.build(view); if (key != null) { Chunk ch = graph.space().getAndMark(key.type, key.world, key.time, key.id); if (ch != null) { graph.space().unmark(ch.index()); //ok we keep it, ask for update if (isFirst) { isFirst = false; } else { updateBuf.write(Constants.BUFFER_SEP); } updateBuf.writeAll(view.data()); } } } //now ask for ta get query ... TODO //System.out.println("Notification!"); //TODO } else { Buffer callbackCodeView = it.next(); if (callbackCodeView != null) { int callbackCode = Base64.decodeToIntWithBounds(callbackCodeView, 0, callbackCodeView.length()); Callback resolvedCallback = callbacks.get(callbackCode); if (resolvedCallback != null) { if (firstCode == WSConstants.RESP_LOCK || firstCode == WSConstants.RESP_GET) { Buffer newBuf = graph.newBuffer();//will be free by the core boolean isFirst = true; while (it.hasNext()) { if (isFirst) { isFirst = false; } else { newBuf.write(Constants.BUFFER_SEP); } newBuf.writeAll(it.next().data()); } resolvedCallback.on(newBuf); } else { resolvedCallback.on(true); } } } } } payloadBuf.free(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.infobip.push.java; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mmilivojevic */ public class Header { private final String encoding = "UTF-8"; private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Header(String name, String value) { this.name = name; this.value = value; } @Override public String toString() { try { return URLEncoder.encode(this.name + ":" + this.value, encoding); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Header.class.getName()).log(Level.SEVERE, null, ex); } finally { return null; } } }
package com.sun.star.lib.uno.helper; import com.sun.star.lang.XComponent; import com.sun.star.lang.XEventListener; import com.sun.star.lang.EventObject; import java.util.List; import java.util.Collections; import java.util.LinkedList; import com.sun.star.uno.Type; /** This class can be used as the base class for UNO components. In addition to the functionality ,which * is inherited from WeakBase, it implements com.sun.star.lang.XComponent. */ public class ComponentBase extends WeakBase implements XComponent { private final boolean DEBUG= false; protected MultiTypeInterfaceContainer listenerContainer; protected boolean bInDispose= false; protected boolean bDisposed= false; static final Type EVT_LISTENER_TYPE= new Type(XEventListener.class); /** Creates a new instance of CompBase */ public ComponentBase() { super(); listenerContainer= new MultiTypeInterfaceContainer(); } /** Override to perform extra clean-up work. Provided for subclasses. It is called during dispose() */ protected void preDisposing() { } /** Override to become notified right before the disposing action is performed. */ protected void postDisposing() { } /** Method of XComponent. It is called by the owning client when the component is not needed * anymore. The registered listeners are notified that this method has been called. */ public void dispose() { // Determine in a thread-safe way if this is the first call to this method. // Only then we proceed with the notification of event listeners. // It is an error to call this method more then once. boolean bDoDispose= false; synchronized (this) { if ( ! bInDispose && ! bDisposed) { bDoDispose= true; bInDispose= true; } } // The notification occures in an unsynchronized block in order to avoid // deadlocks if one of the listeners calls back in a different thread on // a synchronized method which uses the same object. if (bDoDispose) { try { preDisposing(); listenerContainer.disposeAndClear(new EventObject(this)); //notify subclasses that disposing is in progress postDisposing(); } finally { // finally makes sure that the flags are set even if a RuntimeException is thrown. // That ensures that this function is only called once. bDisposed= true; bInDispose= false; } } else { // in a multithreaded environment, it can't be avoided, that dispose is called twice. // However this condition is traced, because it MAY indicate an error. if (DEBUG) System.out.println("OComponentHelper::dispose() - dispose called twice" ); } } /** Method of XComponent. */ public void removeEventListener(XEventListener xEventListener) { listenerContainer.removeInterface( EVT_LISTENER_TYPE, xEventListener); } public void addEventListener(XEventListener listener) { boolean bDoDispose= false; synchronized (this) { if (bDisposed || bInDispose) bDoDispose= true; else listenerContainer.addInterface(EVT_LISTENER_TYPE, listener); } if (bDoDispose ) { listener.disposing( new EventObject(this)); } } protected void finalize() throws Throwable { if ( ! bInDispose && ! bDisposed) dispose(); super.finalize(); } }
package com.jenjinstudios.net; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; /** * Listens for incoming client connections on behalf of a Server. * @author Caleb Brinkman */ class ClientListener<T extends ClientHandler> implements Runnable { /** The Logger for this class. */ private static final Logger LOGGER = Logger.getLogger(ClientListener.class.getName()); /** The port on which this object listens. */ private final int PORT; /** The list of new clients. */ private final LinkedList<T> newClientHandlers; /** Flags whether this should be listening. */ private volatile boolean listening; /** The server socket. */ private ServerSocket serverSock; /** The server. */ private final Server server; /** The constructor called to create new handlers. */ private Constructor<T> handlerConstructor; /** * Construct a new ClientListener for the given server on the given port. * @param s The server for which this listener will listen. * @param p The port on which to listen. * @param handlerClass The class of the ClientHandler to be used by this server. * @throws IOException If there is an error listening on the port. * @throws NoSuchMethodException If there is no appropriate constructor for the specified ClientHandler constructor. */ public ClientListener(Server s, int p, Class<T> handlerClass) throws IOException, NoSuchMethodException { server = s; PORT = p; try { handlerConstructor = handlerClass.getConstructor(s.getClass(), Socket.class); } catch (NoSuchMethodException e) { LOGGER.log(Level.SEVERE, "Unable to find appropriate ClientHandler constructor: " + handlerClass.getName(), e); throw e; } listening = false; newClientHandlers = new LinkedList<>(); serverSock = new ServerSocket(PORT); } /** * Get the new clients accrued since the last check. * @return A {@code LinkedList} containing the new clients. */ public LinkedList<T> getNewClients() { LinkedList<T> temp = new LinkedList<>(); synchronized (newClientHandlers) { if (newClientHandlers.isEmpty()) return temp; Server.LOGGER.log(Level.FINE, newClientHandlers.peek().toString()); temp = new LinkedList<>(newClientHandlers); newClientHandlers.removeAll(temp); } return temp; } /** * Stop listening and close the socket. * @throws IOException If there is an error closing the socket. */ public void stopListening() throws IOException { listening = false; serverSock.close(); } /** Listen for clients in a new thread. If already listening this method does nothing. */ public void listen() { if (listening) return; listening = true; new Thread(this, "Client Listener " + PORT).start(); } /** * Add a new client to the list of new clients. * @param h The handler for the new client. */ void addNewClient(T h) { synchronized (newClientHandlers) { newClientHandlers.add(h); } } /** * Add a new Client using the specified socket as a connection. * @param sock The connection to the new client. */ private void addNewClient(Socket sock) { try { T newHandler = handlerConstructor.newInstance(server, sock); addNewClient(newHandler); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { LOGGER.log(Level.SEVERE, "Unable to instantiate client handler.", e); } } @Override public void run() { while (listening) { try { Socket sock = serverSock.accept(); addNewClient(sock); } catch (IOException e) { Server.LOGGER.log(Level.WARNING, "Error connecting to client: ", e); } } } }
package processing_test; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import net.iharder.dnd.FileDrop; /** * The visual in the main view window * * @author nikla_000 */ public class DisplayFrame extends JFrame implements ActionListener { private final JButton fileChooseButton; private final JButton clearButton; private final JButton saveButton; private final JButton backButton; private final JButton forwardButton; private final JButton cloneButton; private final JButton setPoints; private final JButton blurButton; private final JButton invertButton; private final JButton newTab; private final JButton closeTab; private final JButton randomShit; private final JButton wrappingButton; private final JButton squareButton; private final JButton ellipseButton; private final JComboBox functionChooser; private final JTabbedPane sketchTabs; ToolWindow tw; private String[] functionNames = {"Original", "Dots", "Squares", "3D", "Clone"}; ColorChooserDemo ccd; private final JSlider slider; private final JSlider cloneRadiusSlider; colorPicker cp; private int tabIndex; private int tabs = 2; private ArrayList<Component> componentList; private HashMap<String, Component> toolWindowComponents; private SampleSketch currentSketch; /** * Constructor for instances of class DisplayFrame. Initializes all * components of the GUI as well as the processing sketch. */ public DisplayFrame() throws IOException { this.setSize(1340, 890); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //cp = new colorPicker(); ccd = new ColorChooserDemo(); setLocationByPlatform(true); componentList = new ArrayList<>(); sketchTabs = new JTabbedPane(); closeTab = new JButton(new ImageIcon(ImageIO.read(new File("graphics/X.gif")))); fileChooseButton = new JButton(new ImageIcon(ImageIO.read(new File("graphics/OpenButton.gif")))); saveButton = new JButton(new ImageIcon(ImageIO.read(new File("graphics/Save-icon.png")))); newTab = new JButton(new ImageIcon(ImageIO.read(new File("graphics/blank.jpg")))); backButton = new JButton("<"); forwardButton = new JButton(">"); randomShit = new JButton("Surprise motherfucker!"); cloneRadiusSlider = new JSlider(JSlider.HORIZONTAL, 1, 50, 25); arrangeLayout(); setHoverText(); tw = new ToolWindow(); sketchTabs.addTab("Sketch 1", createNewSketch()); add(fileChooseButton); add(saveButton); add(backButton); add(forwardButton); add(sketchTabs); add(newTab); add(closeTab); add(randomShit); add(ccd); toolWindowComponents = tw.getToolComponents(); componentList.add(backButton); componentList.add(forwardButton); componentList.add(fileChooseButton); componentList.add(saveButton); componentList.add(randomShit); Set<String> keys = toolWindowComponents.keySet(); for (String key : keys) { componentList.add(toolWindowComponents.get(key)); } clearButton = (JButton) toolWindowComponents.get("clearButton"); cloneButton = (JButton) toolWindowComponents.get("cloneButton"); blurButton = (JButton) toolWindowComponents.get("blurButton"); invertButton = (JButton) toolWindowComponents.get("invertButton"); wrappingButton = (JButton) toolWindowComponents.get("wrappingButton"); setPoints = (JButton) toolWindowComponents.get("setPointsButton"); slider = (JSlider) toolWindowComponents.get("sizeSlider"); squareButton = (JButton) toolWindowComponents.get("squareButton"); ellipseButton = (JButton) toolWindowComponents.get("ellipseButton"); functionChooser = (JComboBox) toolWindowComponents.get("functionComboBox"); tabIndex = sketchTabs.getSelectedIndex(); currentSketch = (SampleSketch) sketchTabs.getSelectedComponent(); setActionListeners(currentSketch); setLocalActionListeners(); sketchTabs.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (tabIndex != sketchTabs.getSelectedIndex()) { removeOldActionListeners(currentSketch); SampleSketch newSketch = (SampleSketch) sketchTabs.getSelectedComponent(); setActionListeners(newSketch); currentSketch = newSketch; tabIndex = sketchTabs.getSelectedIndex(); } } }); setVisible(true); tw.setVisible(true); } /** * Creating a new tab */ private void newTab() { sketchTabs.addTab("Sketch " + tabs, createNewSketch()); sketchTabs.setSelectedIndex(sketchTabs.getTabCount() - 1); tabs++; System.out.println(tabs); } /** * Creates and instance of the processing sketch class SampleSketch. * * @return The created sketch. */ private SampleSketch createNewSketch() { SampleSketch newSketch = new SampleSketch(); newSketch.setToolWindow(tw); newSketch.setColorPicker(ccd); newSketch.setButtons(forwardButton, backButton); new FileDrop(newSketch, new FileDrop.Listener() { @Override public void filesDropped(File[] files) { String fileName = files[0].getAbsolutePath(); if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("gif")) { newSketch.loadBgImage(files[0]); } else { JOptionPane.showMessageDialog(newSketch, "This it not a picture. Please drop an image with jpg, png or gif format."); } } }); newSketch.init(); return newSketch; } /** * Arranges the layout of the panel and buttons. */ private void arrangeLayout() { setLayout(null); //Position and size for buttons. closeTab.setBounds(1267, 10, 30, 30); newTab.setBounds(20, 10, 50, 50); fileChooseButton.setBounds(80, 10, 50, 50); saveButton.setBounds(140, 10, 50, 50); backButton.setBounds(220, 10, 50, 50); forwardButton.setBounds(280, 10, 50, 50); sketchTabs.setBounds(20, 110, 1282, 722); cloneRadiusSlider.setBounds(720, 30, 215, 20); randomShit.setBounds(340,10,200,50); ccd.setBounds(407, -173, 500, 500); ccd.setBounds(407, -163, 500, 500); } /** * Sets the hovertext for main window buttons * Gives a description of buttonfunctions */ private void setHoverText() { closeTab.setToolTipText("Close current tab"); newTab.setToolTipText("Create new tab"); fileChooseButton.setToolTipText("Open a file"); saveButton.setToolTipText("Save current work"); forwardButton.setToolTipText("Redo"); backButton.setToolTipText("Undo"); } /** * Removes action listeners for components. * * @param removeFrom A pointer to the instance of the sketch where the * listeners will be removed from */ private void removeOldActionListeners(SampleSketch removeFrom) { for (Component c : componentList) { if (c instanceof JButton) { JButton b = (JButton) c; for (ActionListener a : b.getActionListeners()) { b.removeActionListener(a); } } else if (c instanceof JSlider) { JSlider s = (JSlider) c; for (ChangeListener ch : s.getChangeListeners()) { s.removeChangeListener(ch); } } else if (c instanceof JComboBox) { JComboBox cb = (JComboBox) c; for (ItemListener il : cb.getItemListeners()) { cb.removeItemListener(il); } } } } /** * Adds actionlisteners to buttons that shall be relevant for all tabs */ private void setLocalActionListeners() { newTab.addActionListener(this); newTab.setActionCommand("newTab"); closeTab.addActionListener(this); closeTab.setActionCommand("closeTab"); } /** * Adds action listener to all relevant components, in the current tab * * @param s The processing sketch where buttons execute the listener. */ private void setActionListeners(SampleSketch s) { randomShit.addActionListener(s); randomShit.setActionCommand(""); clearButton.addActionListener(s); clearButton.setActionCommand("clear"); backButton.addActionListener(s); backButton.setActionCommand("back"); forwardButton.addActionListener(s); forwardButton.setActionCommand("forward"); cloneButton.addActionListener(s); cloneButton.setActionCommand("clone"); blurButton.addActionListener(s); blurButton.setActionCommand("blur"); setPoints.addActionListener(s); setPoints.setActionCommand("setPoints"); invertButton.addActionListener(s); invertButton.setActionCommand("invert"); wrappingButton.addActionListener(s); wrappingButton.setActionCommand("wrapping"); squareButton.addActionListener(s); squareButton.setActionCommand("square"); ellipseButton.addActionListener(s); ellipseButton.setActionCommand("ellipse"); slider.addChangeListener(s); fileChooseButton.addActionListener(( ActionEvent arg0 ) -> { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG, GIF & PNG", "jpg", "gif", "png"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(sketchTabs); if (returnVal == JFileChooser.APPROVE_OPTION) { s.loadBgImage(chooser.getSelectedFile()); } } ); saveButton.addActionListener(( ActionEvent arg0 ) -> { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG: png", "png")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG: jpg & jpeg", "jpg", "jpeg")); chooser.addChoosableFileFilter(new FileNameExtensionFilter("TIF: tif", "tif")); int returnVal = chooser.showSaveDialog(sketchTabs); if (returnVal == JFileChooser.APPROVE_OPTION) { s.saveImage(chooser.getSelectedFile()); } } ); functionChooser.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { s.selectFunction(functionNames[(int) e.getItem()]); } } } ); } /** * Creates a dialog asking the user whether or not they want to reset. * * @return dialogResult */ private boolean wantToReset() { int dialogButton = JOptionPane.YES_NO_OPTION; int dialogResult = JOptionPane.showConfirmDialog(null, "All unsaved progress will be lost, " + "are you sure you want to do this?", "Warning", dialogButton); return dialogResult == JOptionPane.YES_OPTION; } /** * Actionlistener for creating new tabs and closing. * * @param e Actionevent */ @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "newTab": System.out.println("Yoloswaggins"); newTab(); break; case "closeTab": sketchTabs.remove(sketchTabs.getSelectedIndex()); tabs System.out.println(tabs); if (sketchTabs.getTabCount() < 1) { newTab(); } } } }
package fi.jumi.core.util; import javax.annotation.concurrent.ThreadSafe; import java.util.concurrent.atomic.AtomicBoolean; @ThreadSafe public class MemoryBarrier { private final AtomicBoolean var = new AtomicBoolean(); public void storeStore() { var.lazySet(true); } public void storeLoad() { var.set(true); } public void loadLoad() { var.get(); } }
package com.intellij.util.indexing; import com.intellij.AppTopics; import com.intellij.ide.startup.CacheUpdater; import com.intellij.ide.startup.FileSystemSynchronizer; import com.intellij.lang.ASTNode; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.fileTypes.FileTypeEvent; import com.intellij.openapi.fileTypes.FileTypeListener; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.CollectingContentIterator; import com.intellij.openapi.roots.ContentIterator; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.*; import com.intellij.openapi.vfs.ex.VirtualFileManagerEx; import com.intellij.openapi.vfs.newvfs.ManagingFS; import com.intellij.openapi.vfs.newvfs.NewVirtualFile; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiLock; import com.intellij.psi.SingleRootFileViewProvider; import com.intellij.psi.impl.PsiDocumentTransactionListener; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.util.ArrayUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.Processor; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.io.IOUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.messages.MessageBusConnection; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.*; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; public class FileBasedIndex implements ApplicationComponent { private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.FileBasedIndex"); private final Map<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>> myIndices = new HashMap<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>>(); private final TObjectIntHashMap<ID<?, ?>> myIndexIdToVersionMap = new TObjectIntHashMap<ID<?, ?>>(); private final Set<ID<?, ?>> myNeedContentLoading = new HashSet<ID<?, ?>>(); private final Map<Document, AtomicLong> myLastIndexedDocStamps = new HashMap<Document, AtomicLong>(); private final Map<Document, CharSequence> myLastIndexedUnsavedContent = new HashMap<Document, CharSequence>(); private ChangedFilesUpdater myChangedFilesUpdater; private final List<IndexableFileSet> myIndexableSets = new CopyOnWriteArrayList<IndexableFileSet>(); public static final int OK = 1; public static final int REQUIRES_REBUILD = 2; public static final int REBUILD_IN_PROGRESS = 3; private final Map<ID<?, ?>, AtomicInteger> myRebuildStatus = new HashMap<ID<?,?>, AtomicInteger>(); private final VirtualFileManagerEx myVfManager; private final Semaphore myUnsavedDataIndexingSemaphore = new Semaphore(); private final Map<Document, PsiFile> myTransactionMap = new HashMap<Document, PsiFile>(); private final FileContentStorage myFileContentAttic; private final Map<ID<?, ?>, FileBasedIndexExtension<?, ?>> myExtentions = new HashMap<ID<?,?>, FileBasedIndexExtension<?,?>>(); private static final int ALREADY_PROCESSED = 0x02; public interface InputFilter { boolean acceptInput(VirtualFile file); } public FileBasedIndex(final VirtualFileManagerEx vfManager, MessageBus bus) throws IOException { myVfManager = vfManager; final MessageBusConnection connection = bus.connect(); connection.subscribe(PsiDocumentTransactionListener.TOPIC, new PsiDocumentTransactionListener() { public void transactionStarted(final Document doc, final PsiFile file) { if (file != null) { myTransactionMap.put(doc, file); } } public void transactionCompleted(final Document doc, final PsiFile file) { myTransactionMap.remove(doc); } }); connection.subscribe(AppTopics.FILE_TYPES, new FileTypeListener() { public void beforeFileTypesChanged(final FileTypeEvent event) { cleanupProcessedFlag(); } public void fileTypesChanged(final FileTypeEvent event) { } }); final File workInProgressFile = getMarkerFile(); if (workInProgressFile.exists()) { // previous IDEA session was closed incorrectly, so drop all indices FileUtil.delete(PathManager.getIndexRoot()); } try { final FileBasedIndexExtension[] extensions = Extensions.getExtensions(FileBasedIndexExtension.EXTENSION_POINT_NAME); for (FileBasedIndexExtension<?, ?> extension : extensions) { myRebuildStatus.put(extension.getName(), new AtomicInteger(OK)); } for (FileBasedIndexExtension<?, ?> extension : extensions) { registerIndexer(extension); } dropUnregisteredIndices(); // check if rebuild was requested for any index during registration for (ID<?, ?> indexId : myIndices.keySet()) { if (myRebuildStatus.get(indexId).compareAndSet(REQUIRES_REBUILD, OK)) { try { clearIndex(indexId); } catch (StorageException e) { requestRebuild(indexId); LOG.error(e); } } } myChangedFilesUpdater = new ChangedFilesUpdater(); vfManager.addVirtualFileListener(myChangedFilesUpdater); vfManager.registerRefreshUpdater(myChangedFilesUpdater); myFileContentAttic = new FileContentStorage(new File(PathManager.getIndexRoot(), "updates.tmp")); } finally { workInProgressFile.createNewFile(); saveRegisteredInices(myIndices.keySet()); } } public static FileBasedIndex getInstance() { return ApplicationManager.getApplication().getComponent(FileBasedIndex.class); } /** * @return true if registered index requires full rebuild for some reason, e.g. is just created or corrupted * @param extension */ private <K, V> void registerIndexer(final FileBasedIndexExtension<K, V> extension) throws IOException { final ID<K, V> name = extension.getName(); final int version = extension.getVersion(); if (extension.dependsOnFileContent()) { myNeedContentLoading.add(name); } myIndexIdToVersionMap.put(name, version); final File versionFile = IndexInfrastructure.getVersionFile(name); if (IndexInfrastructure.versionDiffers(versionFile, version)) { FileUtil.delete(IndexInfrastructure.getIndexRootDir(name)); IndexInfrastructure.rewriteVersion(versionFile, version); } for (int attempt = 0; attempt < 2; attempt++) { try { final MapIndexStorage<K, V> storage = new MapIndexStorage<K, V>(IndexInfrastructure.getStorageFile(name), extension.getKeyDescriptor(), extension.getValueExternalizer(), extension.getCacheSize()); final IndexStorage<K, V> memStorage = new MemoryIndexStorage<K, V>(storage); final UpdatableIndex<K, V, FileContent> index = createIndex(extension, memStorage); myIndices.put(name, new Pair<UpdatableIndex<?,?, FileContent>, InputFilter>(index, new IndexableFilesFilter(extension.getInputFilter()))); myExtentions.put(name, extension); break; } catch (IOException e) { FileUtil.delete(IndexInfrastructure.getIndexRootDir(name)); IndexInfrastructure.rewriteVersion(versionFile, version); } } } private static void saveRegisteredInices(Collection<ID<?, ?>> ids) { final File file = getRegisteredIndicesFile(); try { file.getParentFile().mkdirs(); file.createNewFile(); final DataOutputStream os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); try { os.writeInt(ids.size()); for (ID<?, ?> id : ids) { IOUtil.writeString(id.toString(), os); } } finally { os.close(); } } catch (IOException ignored) { } } private static Set<String> readRegistsredIndexNames() { final Set<String> result = new HashSet<String>(); try { final DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(getRegisteredIndicesFile()))); try { final int size = in.readInt(); for (int idx = 0; idx < size; idx++) { result.add(IOUtil.readString(in)); } } finally { in.close(); } } catch (IOException ignored) { } return result; } private static File getRegisteredIndicesFile() { return new File(PathManager.getIndexRoot(), "registered"); } private static File getMarkerFile() { return new File(PathManager.getIndexRoot(), "work_in_progress"); } private <K, V> UpdatableIndex<K, V, FileContent> createIndex(final FileBasedIndexExtension<K, V> extension, final IndexStorage<K, V> storage) { if (extension instanceof CustomImplementationFileBasedIndexExtension) { return ((CustomImplementationFileBasedIndexExtension<K, V, FileContent>)extension).createIndexImplementation(this, storage); } return new MapReduceIndex<K, V, FileContent>(extension.getIndexer(), storage); } @NonNls @NotNull public String getComponentName() { return "FileBasedIndex"; } public void initComponent() { } public void disposeComponent() { myChangedFilesUpdater.forceUpdate(); for (ID<?, ?> indexId : myIndices.keySet()) { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; index.dispose(); } myVfManager.removeVirtualFileListener(myChangedFilesUpdater); myVfManager.unregisterRefreshUpdater(myChangedFilesUpdater); FileUtil.delete(getMarkerFile()); } public void flushCaches() { ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { for (ID<?, ?> indexId : myIndices.keySet()) { //noinspection ConstantConditions getIndex(indexId).flush(); } } }); } @NotNull public <K> Collection<K> getAllKeys(final ID<K, ?> indexId) { Set<K> allKeys = new HashSet<K>(); processAllKeys(indexId, new CommonProcessors.CollectProcessor<K>(allKeys)); return allKeys; } public <K> boolean processAllKeys(final ID<K, ?> indexId, Processor<K> processor) { try { ensureUpToDate(indexId); final UpdatableIndex<K, ?, FileContent> index = getIndex(indexId); if (index == null) return true; return index.processAllKeys(processor); } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, cause); } else { throw e; } } return false; } private ThreadLocal<Integer> myUpToDateCheckState = new ThreadLocal<Integer>(); public void disableUpToDateCheckForCurrentThread() { final Integer currentValue = myUpToDateCheckState.get(); myUpToDateCheckState.set(currentValue == null? 1 : currentValue.intValue() + 1); } public void enableUpToDateCheckForCurrentThread() { final Integer currentValue = myUpToDateCheckState.get(); if (currentValue != null) { final int newValue = currentValue.intValue() - 1; if (newValue != 0) { myUpToDateCheckState.set(newValue); } else { myUpToDateCheckState.remove(); } } } private boolean isUpToDateCheckEnabled() { final Integer value = myUpToDateCheckState.get(); return value == null || value.intValue() == 0; } public <K> void ensureUpToDate(final ID<K, ?> indexId) { myChangedFilesUpdater.ensureAllInvalidateTasksCompleted(); if (isUpToDateCheckEnabled()) { try { checkRebuild(indexId); indexUnsavedDocuments(); } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, e); } else { throw e; } } } } @NotNull public <K, V> List<V> getValues(final ID<K, V> indexId, K dataKey, final VirtualFileFilter filter) { final List<V> values = new ArrayList<V>(); processValuesImpl(indexId, dataKey, true, null, new ValueProcessor<V>() { public void process(final VirtualFile file, final V value) { values.add(value); } }, filter); return values; } @NotNull public <K, V> Collection<VirtualFile> getContainingFiles(final ID<K, V> indexId, K dataKey, final VirtualFileFilter filter) { final Set<VirtualFile> files = new HashSet<VirtualFile>(); processValuesImpl(indexId, dataKey, false, null, new ValueProcessor<V>() { public void process(final VirtualFile file, final V value) { files.add(file); } }, filter); return files; } public static interface ValueProcessor<V> { void process(VirtualFile file, V value); } public <K, V> void processValues(final ID<K, V> indexId, final K dataKey, @Nullable final VirtualFile inFile, ValueProcessor<V> processor, final VirtualFileFilter filter) { processValuesImpl(indexId, dataKey, false, inFile, processor, filter); } private <K, V> void processValuesImpl(final ID<K, V> indexId, final K dataKey, boolean ensureValueProcessedOnce, @Nullable final VirtualFile restrictToFile, ValueProcessor<V> processor, final VirtualFileFilter filter) { try { ensureUpToDate(indexId); final UpdatableIndex<K, V, FileContent> index = getIndex(indexId); if (index == null) { return; } final Lock readLock = index.getReadLock(); try { readLock.lock(); final ValueContainer<V> container = index.getData(dataKey); if (restrictToFile != null) { if (!(restrictToFile instanceof VirtualFileWithId)) return; final int restrictedFileId = getFileId(restrictToFile); for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext();) { final V value = valueIt.next(); if (container.isAssociated(value, restrictedFileId)) { processor.process(restrictToFile, value); } } } else { final PersistentFS fs = (PersistentFS)ManagingFS.getInstance(); for (final Iterator<V> valueIt = container.getValueIterator(); valueIt.hasNext();) { final V value = valueIt.next(); for (final ValueContainer.IntIterator inputIdsIterator = container.getInputIdsIterator(value); inputIdsIterator.hasNext();) { final int id = inputIdsIterator.next(); VirtualFile file = IndexInfrastructure.findFileById(fs, id); if (file != null && filter.accept(file)) { processor.process(file, value); if (ensureValueProcessedOnce) { break; // continue with the next value } } } } } } finally { index.getReadLock().unlock(); } } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, cause); } else { throw e; } } } public static interface AllValuesProcessor<V> { void process(final int inputId, V value); } public <K, V> void processAllValues(final ID<K, V> indexId, AllValuesProcessor<V> processor) { try { ensureUpToDate(indexId); final UpdatableIndex<K, V, FileContent> index = getIndex(indexId); if (index == null) { return; } try { index.getReadLock().lock(); for (K dataKey : index.getAllKeys()) { final ValueContainer<V> container = index.getData(dataKey); for (final Iterator<V> it = container.getValueIterator(); it.hasNext();) { final V value = it.next(); for (final ValueContainer.IntIterator inputsIt = container.getInputIdsIterator(value); inputsIt.hasNext();) { processor.process(inputsIt.next(), value); } } } } finally { index.getReadLock().unlock(); } } catch (StorageException e) { scheduleRebuild(indexId, e); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof StorageException || cause instanceof IOException) { scheduleRebuild(indexId, e); } else { throw e; } } } private <K> void scheduleRebuild(final ID<K, ?> indexId, final Throwable e) { requestRebuild(indexId); LOG.info(e); checkRebuild(indexId); } private void checkRebuild(final ID<?, ?> indexId) { if (myRebuildStatus.get(indexId).compareAndSet(REQUIRES_REBUILD, REBUILD_IN_PROGRESS)) { cleanupProcessedFlag(); final FileSystemSynchronizer synchronizer = new FileSystemSynchronizer(); synchronizer.setCancelable(false); for (Project project : ProjectManager.getInstance().getOpenProjects()) { synchronizer.registerCacheUpdater(new UnindexedFilesUpdater(project, ProjectRootManager.getInstance(project), this)); } final Runnable rebuildRunnable = new Runnable() { public void run() { try { clearIndex(indexId); synchronizer.execute(); } catch (StorageException e) { requestRebuild(indexId); LOG.info(e); } finally { myRebuildStatus.get(indexId).compareAndSet(REBUILD_IN_PROGRESS, OK); } } }; final Application application = ApplicationManager.getApplication(); if (application.isUnitTestMode()) { rebuildRunnable.run(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { new Task.Modal(null, "Updating index", false) { public void run(@NotNull final ProgressIndicator indicator) { indicator.setIndeterminate(true); rebuildRunnable.run(); } }.queue(); } }); } } if (myRebuildStatus.get(indexId).get() == REBUILD_IN_PROGRESS) { throw new ProcessCanceledException(); } } private void clearIndex(final ID<?, ?> indexId) throws StorageException { final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; index.clear(); try { IndexInfrastructure.rewriteVersion(IndexInfrastructure.getVersionFile(indexId), myIndexIdToVersionMap.get(indexId)); } catch (IOException e) { LOG.error(e); } } private Set<Document> getUnsavedOrTransactedDocuments() { Set<Document> docs = new HashSet<Document>(Arrays.asList(FileDocumentManager.getInstance().getUnsavedDocuments())); docs.addAll(myTransactionMap.keySet()); return docs; } private void indexUnsavedDocuments() throws StorageException { myChangedFilesUpdater.forceUpdate(); final Set<Document> documents = getUnsavedOrTransactedDocuments(); if (!documents.isEmpty()) { // now index unsaved data setDataBufferingEnabled(true); myUnsavedDataIndexingSemaphore.down(); try { for (Document document : documents) { indexUnsavedDocument(document); } } catch (StorageException e) { setDataBufferingEnabled(false); // revert to original state throw e; } catch (ProcessCanceledException e) { setDataBufferingEnabled(false); // revert to original state throw e; } finally { myUnsavedDataIndexingSemaphore.up(); while (!myUnsavedDataIndexingSemaphore.waitFor(500)) { // may need to wait until another thread is done with indexing if (Thread.holdsLock(PsiLock.LOCK)) { break; // hack. Most probably that other indexing threas is waiting for PsiLock, which we're are holding. } } } } } private interface DocumentContent { String getText(); long getModificationStamp(); } private static class AuthenticContent implements DocumentContent { private final Document myDocument; public AuthenticContent(final Document document) { myDocument = document; } public String getText() { return myDocument.getText(); } public long getModificationStamp() { return myDocument.getModificationStamp(); } } private static class PsiContent implements DocumentContent { private final Document myDocument; private final PsiFile myFile; public PsiContent(final Document document, final PsiFile file) { myDocument = document; myFile = file; } public String getText() { if (myFile.getModificationStamp() != myDocument.getModificationStamp()) { final ASTNode node = myFile.getNode(); assert node != null; return node.getText(); } return myDocument.getText(); } public long getModificationStamp() { return myFile.getModificationStamp(); } } private void indexUnsavedDocument(final Document document) throws StorageException { final VirtualFile vFile = FileDocumentManager.getInstance().getFile(document); if (!(vFile instanceof VirtualFileWithId) || !vFile.isValid()) { return; } PsiFile dominantContentFile = findDominantPsiForDocument(document); DocumentContent content; if (dominantContentFile != null && dominantContentFile.getModificationStamp() != document.getModificationStamp()) { content = new PsiContent(document, dominantContentFile); } else { content = new AuthenticContent(document); } final long currentDocStamp = content.getModificationStamp(); if (currentDocStamp != getLastIndexedStamp(document).getAndSet(currentDocStamp)) { CharSequence lastIndexed = myLastIndexedUnsavedContent.get(document); if (lastIndexed == null) { lastIndexed = loadContent(vFile); } final FileContent oldFc = new FileContent(vFile, lastIndexed, vFile.getCharset()); final FileContent newFc = new FileContent(vFile, content.getText(), vFile.getCharset()); if (dominantContentFile != null) { dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, true); newFc.putUserData(PSI_FILE, dominantContentFile); } for (ID<?, ?> indexId : myIndices.keySet()) { if (getInputFilter(indexId).acceptInput(vFile)) { final int inputId = Math.abs(getFileId(vFile)); getIndex(indexId).update(inputId, newFc, oldFc); } } if (dominantContentFile != null) { dominantContentFile.putUserData(PsiFileImpl.BUILDING_STUB, null); } myLastIndexedUnsavedContent.put(document, newFc.getContentAsText()); } } public static final Key<PsiFile> PSI_FILE = new Key<PsiFile>("PSI for stubs"); public static final Key<Project> PROJECT = new Key<Project>("Context project"); @Nullable private PsiFile findDominantPsiForDocument(final Document document) { if (myTransactionMap.containsKey(document)) { return myTransactionMap.get(document); } return findLatestKnownPsiForUncomittedDocument(document); } @NotNull private AtomicLong getLastIndexedStamp(final Document document) { AtomicLong lastStamp; synchronized (myLastIndexedDocStamps) { lastStamp = myLastIndexedDocStamps.get(document); if (lastStamp == null) { lastStamp = new AtomicLong(0L); myLastIndexedDocStamps.put(document, lastStamp); } } return lastStamp; } private void setDataBufferingEnabled(final boolean enabled) { if (!enabled) { synchronized (myLastIndexedDocStamps) { myLastIndexedDocStamps.clear(); myLastIndexedUnsavedContent.clear(); } } for (ID<?, ?> indexId : myIndices.keySet()) { final MapReduceIndex index = (MapReduceIndex)getIndex(indexId); assert index != null; final IndexStorage indexStorage = index.getStorage(); ((MemoryIndexStorage)indexStorage).setBufferingEnabled(enabled); } } private void dropUnregisteredIndices() { final Set<String> indicesToDrop = readRegistsredIndexNames(); for (ID<?, ?> key : myIndices.keySet()) { indicesToDrop.remove(key.toString()); } for (String s : indicesToDrop) { FileUtil.delete(IndexInfrastructure.getIndexRootDir(ID.create(s))); } } public void requestRebuild(ID<?, ?> indexId) { cleanupProcessedFlag(); myRebuildStatus.get(indexId).set(REQUIRES_REBUILD); } @Nullable private <K, V> UpdatableIndex<K, V, FileContent> getIndex(ID<K, V> indexId) { final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId); //noinspection unchecked return pair != null? (UpdatableIndex<K,V, FileContent>)pair.getFirst() : null; } @Nullable private InputFilter getInputFilter(ID<?, ?> indexId) { final Pair<UpdatableIndex<?, ?, FileContent>, InputFilter> pair = myIndices.get(indexId); return pair != null? pair.getSecond() : null; } public void indexFileContent(com.intellij.ide.startup.FileContent content) { myChangedFilesUpdater.ensureAllInvalidateTasksCompleted(); final VirtualFile file = content.getVirtualFile(); FileContent fc = null; FileContent oldContent = null; final byte[] oldBytes = myFileContentAttic.remove(file); final boolean forceIndexing = oldBytes != null; PsiFile psiFile = null; for (ID<?, ?> indexId : myIndices.keySet()) { if (forceIndexing? getInputFilter(indexId).acceptInput(file) : shouldIndexFile(file, indexId)) { if (fc == null) { byte[] currentBytes; try { currentBytes = content.getBytes(); } catch (IOException e) { currentBytes = ArrayUtil.EMPTY_BYTE_ARRAY; } fc = new FileContent(file, currentBytes); psiFile = content.getUserData(PSI_FILE); if (psiFile != null) { psiFile.putUserData(PsiFileImpl.BUILDING_STUB, true); fc.putUserData(PSI_FILE, psiFile); } oldContent = oldBytes != null? new FileContent(file, oldBytes) : null; } try { updateSingleIndex(indexId, file, fc, oldContent); } catch (StorageException e) { requestRebuild(indexId); LOG.info(e); } } } if (psiFile != null) { psiFile.putUserData(PsiFileImpl.BUILDING_STUB, null); } IndexingStamp.flushCache(); } //private final TIntHashSet myInvalidationInProgress = new TIntHashSet(); private void updateSingleIndex(final ID<?, ?> indexId, final VirtualFile file, final FileContent currentFC, final FileContent oldFC) throws StorageException { setDataBufferingEnabled(false); final int inputId = Math.abs(getFileId(file)); //if ("Stubs".equals(indexId.toString())) { // synchronized (myInvalidationInProgress) { // if (currentFC == null) { // if (!myInvalidationInProgress.contains(inputId)) { // LOG.assertTrue(false); // else { // if (myInvalidationInProgress.contains(inputId)) { // LOG.assertTrue(false); final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId); assert index != null; index.update(inputId, currentFC, oldFC); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { if (file.isValid()) { if (currentFC != null) { IndexingStamp.update(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId)); } else { // mark the file as unindexed IndexingStamp.update(file, indexId, -1L); } } } }); } public static int getFileId(final VirtualFile file) { if (file instanceof VirtualFileWithId) { return ((VirtualFileWithId)file).getId(); } throw new IllegalArgumentException("Virtual file doesn't support id: " + file + ", implementation class: " + file.getClass().getName()); } private static CharSequence loadContent(VirtualFile file) { return LoadTextUtil.loadText(file, true); } private static abstract class InvalidationTask implements Runnable { private VirtualFile mySubj; protected InvalidationTask(final VirtualFile subj) { mySubj = subj; } public VirtualFile getSubj() { return mySubj; } } private final class ChangedFilesUpdater extends VirtualFileAdapter implements CacheUpdater{ private final Set<VirtualFile> myFilesToUpdate = Collections.synchronizedSet(new HashSet<VirtualFile>()); private final Queue<InvalidationTask> myFutureInvalidations = new LinkedList<InvalidationTask>(); private final ManagingFS myManagingFS = ManagingFS.getInstance(); // No need to react on movement events since files stay valid, their ids don't change and all associated attributes remain intact. public void fileCreated(final VirtualFileEvent event) { markDirty(event); } public void fileDeleted(final VirtualFileEvent event) { myFilesToUpdate.remove(event.getFile()); // no need to update it anymore } public void fileCopied(final VirtualFileCopyEvent event) { markDirty(event); } public void beforeFileDeletion(final VirtualFileEvent event) { scheduleInvalidation(event.getFile(), false); } public void beforeContentsChange(final VirtualFileEvent event) { scheduleInvalidation(event.getFile(), true); } public void contentsChanged(final VirtualFileEvent event) { markDirty(event); } public void beforePropertyChange(final VirtualFilePropertyEvent event) { if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) { // indexes may depend on file name final VirtualFile file = event.getFile(); if (!file.isDirectory()) { scheduleInvalidation(file, true); } } } public void propertyChanged(final VirtualFilePropertyEvent event) { if (event.getPropertyName().equals(VirtualFile.PROP_NAME)) { // indexes may depend on file name if (!event.getFile().isDirectory()) { markDirty(event); } } } private void markDirty(final VirtualFileEvent event) { cleanProcessedFlag(event.getFile()); iterateIndexableFiles(event.getFile(), new Processor<VirtualFile>() { public boolean process(final VirtualFile file) { FileContent fileContent = null; for (ID<?, ?> indexId : myIndices.keySet()) { if (getInputFilter(indexId).acceptInput(file)) { if (myNeedContentLoading.contains(indexId)) { myFilesToUpdate.add(file); } else { try { if (fileContent == null) { fileContent = new FileContent(file); } updateSingleIndex(indexId, file, fileContent, null); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } } IndexingStamp.flushCache(); return true; } }); } private void scheduleInvalidation(final VirtualFile file, final boolean saveContent) { if (file.isDirectory()) { if (isMock(file) || myManagingFS.wereChildrenAccessed(file)) { for (VirtualFile child : file.getChildren()) { scheduleInvalidation(child, saveContent); } } } else { cleanProcessedFlag(file); if (SingleRootFileViewProvider.isTooLarge(file)) return; final List<ID<?, ?>> affectedIndices = new ArrayList<ID<?, ?>>(myIndices.size()); FileContent fileContent = null; //final int fileId = getFileId(file); //LOG.assertTrue(fileId >= 0); //synchronized (myInvalidationInProgress) { // myInvalidationInProgress.add(fileId); for (ID<?, ?> indexId : myIndices.keySet()) { if (shouldUpdateIndex(file, indexId)) { if (myNeedContentLoading.contains(indexId)) { affectedIndices.add(indexId); } else { // invalidate it synchronously try { if (fileContent == null) { fileContent = new FileContent(file); } updateSingleIndex(indexId, file, null, fileContent); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } } //synchronized (myInvalidationInProgress) { // myInvalidationInProgress.remove(fileId); IndexingStamp.flushCache(); if (!affectedIndices.isEmpty()) { if (saveContent) { myFileContentAttic.offer(file); } else { //synchronized (myInvalidationInProgress) { // myInvalidationInProgress.add(fileId); // first check if there is an unprocessed content from previous events byte[] content = myFileContentAttic.remove(file); try { if (content == null) { content = file.contentsToByteArray(); } } catch (IOException e) { content = ArrayUtil.EMPTY_BYTE_ARRAY; } final FileContent fc = new FileContent(file, content); synchronized (myFutureInvalidations) { final InvalidationTask invalidator = new InvalidationTask(file) { public void run() { Throwable unexpectedError = null; for (ID<?, ?> indexId : affectedIndices) { try { updateSingleIndex(indexId, file, null, fc); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } catch (Throwable e) { LOG.info(e); if (unexpectedError == null) { unexpectedError = e; } } } //synchronized (myInvalidationInProgress) { // myInvalidationInProgress.remove(fileId); IndexingStamp.flushCache(); if (unexpectedError != null) { LOG.error(unexpectedError); } } }; myFutureInvalidations.offer(invalidator); } } iterateIndexableFiles(file, new Processor<VirtualFile>() { public boolean process(final VirtualFile file) { myFilesToUpdate.add(file); return true; } }); } } } public void ensureAllInvalidateTasksCompleted() { final boolean doProgressThing; final int size; synchronized (myFutureInvalidations) { size = myFutureInvalidations.size(); if (size == 0) return; doProgressThing = size > 1 && ApplicationManager.getApplication().isDispatchThread(); } final Task.Modal task = new Task.Modal(null, "Invalidating Index Entries", false) { public void run(@NotNull final ProgressIndicator indicator) { indicator.setText(""); int count = 0; while (true) { InvalidationTask r; synchronized (myFutureInvalidations) { r = myFutureInvalidations.poll(); } if (r == null) return; indicator.setFraction(((double)count++)/size); indicator.setText2(r.getSubj().getPresentableUrl()); r.run(); } } }; if (doProgressThing) { task.queue(); } else { ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); task.run(indicator != null ? indicator : new EmptyProgressIndicator()); } } private void iterateIndexableFiles(final VirtualFile file, final Processor<VirtualFile> processor) { if (file.isDirectory()) { final ContentIterator iterator = new ContentIterator() { public boolean processFile(final VirtualFile fileOrDir) { if (!fileOrDir.isDirectory()) { processor.process(fileOrDir); } return true; } }; for (IndexableFileSet set : myIndexableSets) { set.iterateIndexableFilesIn(file, iterator); } } else { for (IndexableFileSet set : myIndexableSets) { if (set.isInSet(file)) { processor.process(file); break; } } } } public VirtualFile[] queryNeededFiles() { synchronized (myFilesToUpdate) { return myFilesToUpdate.toArray(new VirtualFile[myFilesToUpdate.size()]); } } public void processFile(final com.intellij.ide.startup.FileContent fileContent) { ensureAllInvalidateTasksCompleted(); processFileImpl(fileContent); } private final ThreadLocal<Boolean> myAlreadyAquired = new ThreadLocal<Boolean>() { protected Boolean initialValue() { return Boolean.FALSE; } }; private final Semaphore myForceUpdateSemaphore = new Semaphore(); public void forceUpdate() { ensureAllInvalidateTasksCompleted(); final Boolean alreadyAquired = myAlreadyAquired.get(); assert !alreadyAquired : "forceUpdate() is not reentrant!"; if (alreadyAquired) { return; } myAlreadyAquired.set(Boolean.TRUE); myForceUpdateSemaphore.down(); try { for (VirtualFile file: queryNeededFiles()) { processFileImpl(new com.intellij.ide.startup.FileContent(file)); } } finally { myForceUpdateSemaphore.up(); myAlreadyAquired.set(Boolean.FALSE); myForceUpdateSemaphore.waitFor(); // possibly wait until another thread completes indexing } } public void updatingDone() { } public void canceled() { } private void processFileImpl(final com.intellij.ide.startup.FileContent fileContent) { final VirtualFile file = fileContent.getVirtualFile(); final boolean reallyRemoved = myFilesToUpdate.remove(file); if (reallyRemoved && file.isValid()) { indexFileContent(fileContent); } } } private class UnindexedFilesFinder implements CollectingContentIterator { private final List<VirtualFile> myFiles = new ArrayList<VirtualFile>(); private final Collection<ID<?, ?>> myIndexIds; private final Collection<ID<?, ?>> mySkipContentLoading; private final ProgressIndicator myProgressIndicator; public UnindexedFilesFinder(final Collection<ID<?, ?>> indexIds) { myIndexIds = new ArrayList<ID<?, ?>>(); mySkipContentLoading = new ArrayList<ID<?, ?>>(); for (ID<?, ?> indexId : indexIds) { if (myNeedContentLoading.contains(indexId)) { myIndexIds.add(indexId); } else { mySkipContentLoading.add(indexId); } } myProgressIndicator = ProgressManager.getInstance().getProgressIndicator(); } public List<VirtualFile> getFiles() { return myFiles; } public boolean processFile(final VirtualFile file) { if (!file.isDirectory()) { if (file instanceof NewVirtualFile) { if (((NewVirtualFile)file).getFlag(ALREADY_PROCESSED)) return true; } if (file instanceof VirtualFileWithId && !SingleRootFileViewProvider.isTooLarge(file)) { boolean oldStuff = true; for (ID<?, ?> indexId : myIndexIds) { if (myFileContentAttic.containsContent(file) ? getInputFilter(indexId).acceptInput(file) : shouldIndexFile(file, indexId)) { myFiles.add(file); oldStuff = false; break; } } FileContent fileContent = null; for (ID<?, ?> indexId : mySkipContentLoading) { if (shouldIndexFile(file, indexId)) { oldStuff = false; try { if (fileContent == null) { fileContent = new FileContent(file); } updateSingleIndex(indexId, file, fileContent, null); } catch (StorageException e) { LOG.info(e); requestRebuild(indexId); } } } IndexingStamp.flushCache(); if (oldStuff && file instanceof NewVirtualFile) { ((NewVirtualFile)file).setFlag(ALREADY_PROCESSED, true); } } } else { if (myProgressIndicator != null) { myProgressIndicator.setText("Scanning files to index"); myProgressIndicator.setText2(file.getPresentableUrl()); } } return true; } } private boolean shouldUpdateIndex(final VirtualFile file, final ID<?, ?> indexId) { return getInputFilter(indexId).acceptInput(file) && (isMock(file) || IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId))); } private boolean shouldIndexFile(final VirtualFile file, final ID<?, ?> indexId) { return getInputFilter(indexId).acceptInput(file) && (isMock(file) || !IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId))); } private static boolean isMock(final VirtualFile file) { return !(file instanceof NewVirtualFile); } public CollectingContentIterator createContentIterator() { return new UnindexedFilesFinder(myIndices.keySet()); } public void registerIndexableSet(IndexableFileSet set) { myIndexableSets.add(set); } public void removeIndexableSet(IndexableFileSet set) { myChangedFilesUpdater.forceUpdate(); myIndexableSets.remove(set); } @Nullable private static PsiFile findLatestKnownPsiForUncomittedDocument(Document doc) { PsiFile target = null; long modStamp = -1L; for (Project project : ProjectManager.getInstance().getOpenProjects()) { final PsiDocumentManager pdm = PsiDocumentManager.getInstance(project); final PsiFile file = pdm.getCachedPsiFile(doc); if (file != null && file.getModificationStamp() > modStamp) { target = file; modStamp = file.getModificationStamp(); } } return target; } private static class IndexableFilesFilter implements InputFilter { private final InputFilter myDelegate; private IndexableFilesFilter(InputFilter delegate) { myDelegate = delegate; } public boolean acceptInput(final VirtualFile file) { return file instanceof VirtualFileWithId && myDelegate.acceptInput(file); } } private static void cleanupProcessedFlag() { final VirtualFile[] roots = ManagingFS.getInstance().getRoots(); for (VirtualFile root : roots) { cleanProcessedFlag(root); } } private static void cleanProcessedFlag(final VirtualFile file) { if (!(file instanceof NewVirtualFile)) return; final NewVirtualFile nvf = (NewVirtualFile)file; if (file.isDirectory()) { for (VirtualFile child : nvf.getCachedChildren()) { cleanProcessedFlag(child); } } else { nvf.setFlag(ALREADY_PROCESSED, false); } } }
package hex.glrm; import hex.*; import water.H2O; import water.Key; import water.fvec.Frame; import water.fvec.Vec; import water.util.ArrayUtils; import water.util.RandomUtils; import water.util.TwoDimTable; import java.util.Random; public class GLRMModel extends Model<GLRMModel,GLRMModel.GLRMParameters,GLRMModel.GLRMOutput> { public static class GLRMParameters extends Model.Parameters { public int _k = 1; // Rank of resulting XY matrix public Loss _loss = Loss.L2; // Loss function for numeric cols public MultiLoss _multi_loss = MultiLoss.Categorical; // Loss function for categorical cols public Regularizer _regularization_x = Regularizer.L2; // Regularization function for X matrix public Regularizer _regularization_y = Regularizer.L2; // Regularization function for Y matrix public double _gamma_x = 0; // Regularization weight on X matrix public double _gamma_y = 0; // Regularization weight on Y matrix public int _max_iterations = 1000; // Max iterations public double _init_step_size = 1.0; // Initial step size (decrease until we hit min_step_size) public double _min_step_size = 1e-4; // Min step size public long _seed = System.nanoTime(); // RNG seed public DataInfo.TransformType _transform = DataInfo.TransformType.NONE; // Data transformation (demean to compare with PCA) public GLRM.Initialization _init = GLRM.Initialization.PlusPlus; // Initialization of Y matrix public Key<Frame> _user_points; // User-specified Y matrix (for _init = User) public Key<Frame> _loading_key; // Key to save X matrix public boolean _recover_svd = false; // Recover singular values and eigenvectors of XY at the end? public enum Loss { L2, L1, Huber, Poisson, Hinge, Logistic } public enum MultiLoss { Categorical, Ordinal } // Non-negative matrix factorization (NNMF): r_x = r_y = NonNegative // Orthogonal NNMF: r_x = OneSparse, r_y = NonNegative // K-means clustering: r_x = UnitOneSparse, r_y = 0 (\gamma_y = 0) public enum Regularizer { L2, L1, NonNegative, OneSparse, UnitOneSparse } public final boolean hasClosedForm() { // TODO: Currently, no closed form solution when training frame has NAs Vec[] vecs = _train.get().vecs(); boolean has_na = false; for(int i = 0; i < vecs.length; i++) { if(vecs[i].naCnt() > 0) { has_na = true; break; } } return (!has_na && _loss == GLRMParameters.Loss.L2 && (_gamma_x == 0 || _regularization_x == GLRMParameters.Regularizer.L2) && (_gamma_y == 0 || _regularization_y == GLRMParameters.Regularizer.L2)); } // L(u,a): Loss function public final double loss(double u, double a) { switch(_loss) { case L2: return (u-a)*(u-a); case L1: return Math.abs(u - a); case Huber: return Math.abs(u-a) <= 1 ? 0.5*(u-a)*(u-a) : Math.abs(u-a)-0.5; case Poisson: return Math.exp(u) - a*u + a*Math.log(a) - a; case Hinge: return Math.max(1-a*u,0); case Logistic: return Math.log(1+Math.exp(-a*u)); default: throw new RuntimeException("Unknown loss function " + _loss); } } // \grad_u L(u,a): Gradient of loss function with respect to u public final double lgrad(double u, double a) { switch(_loss) { case L2: return 2*(u-a); case L1: return Math.signum(u - a); case Huber: return Math.abs(u-a) <= 1 ? u-a : Math.signum(u-a); case Poisson: return Math.exp(u)-a; case Hinge: return a*u <= 1 ? -a : 0; case Logistic: return -a/(1+Math.exp(a*u)); default: throw new RuntimeException("Unknown loss function " + _loss); } } // L(u,a): Multidimensional loss function public final double mloss(double[] u, int a) { if(a < 0 || a > u.length-1) throw new IllegalArgumentException("Index must be between 0 and " + String.valueOf(u.length-1)); double sum = 0; switch(_multi_loss) { case Categorical: for (int i = 0; i < u.length; i++) sum += Math.max(1 + u[i], 0); sum += Math.max(1 - u[a], 0) - Math.max(1 + u[a], 0); return sum; case Ordinal: for (int i = 0; i < u.length-1; i++) sum += Math.max(a>i ? 1-u[i]:1, 0); return sum; default: throw new RuntimeException("Unknown multidimensional loss function " + _multi_loss); } } // \grad_u L(u,a): Gradient of multidimensional loss function with respect to u public final double[] mlgrad(double[] u, int a) { if(a < 0 || a > u.length-1) throw new IllegalArgumentException("Index must be between 0 and " + String.valueOf(u.length-1)); double[] grad = new double[u.length]; switch(_multi_loss) { case Categorical: for (int i = 0; i < u.length; i++) grad[i] = (1+u[i] > 0) ? 1:0; grad[a] = (1-u[a] > 0) ? -1:0; return grad; case Ordinal: for (int i = 0; i < u.length-1; i++) grad[i] = (a>i && 1-u[i] > 0) ? -1:0; return grad; default: throw new RuntimeException("Unknown multidimensional loss function " + _multi_loss); } } // r_i(x_i): Regularization function for single row x_i public final double regularize_x(double[] u) { return regularize(u, _regularization_x); } public final double regularize_y(double[] u) { return regularize(u, _regularization_y); } public final double regularize(double[] u, Regularizer regularization) { if(u == null) return 0; double ureg = 0; switch(regularization) { case L2: for(int i = 0; i < u.length; i++) ureg += u[i] * u[i]; return ureg; case L1: for(int i = 0; i < u.length; i++) ureg += Math.abs(u[i]); return ureg; case NonNegative: for(int i = 0; i < u.length; i++) { if(u[i] < 0) return Double.POSITIVE_INFINITY; } return 0; case OneSparse: int card = 0; for(int i = 0; i < u.length; i++) { if(u[i] < 0) return Double.POSITIVE_INFINITY; else if(u[i] > 0) card++; } return card == 1 ? 0 : Double.POSITIVE_INFINITY; case UnitOneSparse: int ones = 0, zeros = 0; for(int i = 0; i < u.length; i++) { if(u[i] == 1) ones++; else if(u[i] == 0) zeros++; else return Double.POSITIVE_INFINITY; } return ones == 1 && zeros == u.length-1 ? 0 : Double.POSITIVE_INFINITY; default: throw new RuntimeException("Unknown regularization function " + regularization); } } // \sum_i r_i(x_i): Sum of regularization function for all entries of X public final double regularize_x(double[][] u) { return regularize(u, _regularization_x); } public final double regularize_y(double[][] u) { return regularize(u, _regularization_y); } public final double regularize(double[][] u, Regularizer regularization) { if(u == null) return 0; double ureg = 0; for(int i = 0; i < u.length; i++) { ureg += regularize(u[i], regularization); if(Double.isInfinite(ureg)) return ureg; } return ureg; } // \prox_{\alpha_k*r}(u): Proximal gradient of (step size) * (regularization function) evaluated at vector u public final double[] rproxgrad_x(double[] u, double alpha, Random rand) { return rproxgrad(u, alpha, _gamma_x, _regularization_x, rand); } public final double[] rproxgrad_y(double[] u, double alpha, Random rand) { return rproxgrad(u, alpha, _gamma_y, _regularization_y, rand); } // public final double[] rproxgrad_x(double[] u, double alpha) { return rproxgrad(u, alpha, _gamma_x, _regularization_x, RandomUtils.getRNG(_seed)); } // public final double[] rproxgrad_y(double[] u, double alpha) { return rproxgrad(u, alpha, _gamma_y, _regularization_y, RandomUtils.getRNG(_seed)); } public final double[] rproxgrad(double[] u, double alpha, double gamma, Regularizer regularization, Random rand) { if(u == null || alpha == 0 || gamma == 0) return u; double[] v = new double[u.length]; int idx; switch(regularization) { case L2: for(int i = 0; i < u.length; i++) v[i] = u[i]/(1+2*alpha*gamma); return v; case L1: for(int i = 0; i < u.length; i++) v[i] = Math.max(u[i]-alpha*gamma,0) + Math.min(u[i]+alpha*gamma,0); return v; case NonNegative: for(int i = 0; i < u.length; i++) v[i] = Math.max(u[i],0); return v; case OneSparse: idx = ArrayUtils.maxIndex(u, rand); v[idx] = u[idx] > 0 ? u[idx] : 1e-6; return v; case UnitOneSparse: idx = ArrayUtils.maxIndex(u, rand); v[idx] = 1; return v; default: throw new RuntimeException("Unknown regularization function " + regularization); } } } public static class GLRMOutput extends Model.Output { // Iterations executed public int _iterations; // Current value of objective function public double _objective; // Average change in objective function this iteration public double _avg_change_obj; // Mapping from training data to lower dimensional k-space (Y) public double[][] _archetypes; // Final step size public double _step_size; // SVD of output XY public double[/*feature*/][/*k*/] _eigenvectors; public double[] _singular_vals; // Frame key of X matrix public Key<Frame> _loading_key; // Number of categorical and numeric columns public int _ncats; public int _nnums; // Number of good rows in training frame (not skipped) public long _nobs; // Categorical offset vector public int[] _catOffsets; // If standardized, mean of each numeric data column public double[] _normSub; // If standardized, one over standard deviation of each numeric data column public double[] _normMul; // Permutation matrix mapping training col indices to adaptedFrame public int[] _permutation; // Expanded column names of adapted training frame public String[] _names_expanded; public GLRMOutput(GLRM b) { super(b); } /** Override because base class implements ncols-1 for features with the * last column as a response variable; for GLRM all the columns are features. */ @Override public int nfeatures() { return _names.length; } @Override public ModelCategory getModelCategory() { return ModelCategory.DimReduction; } } public GLRMModel(Key selfKey, GLRMParameters parms, GLRMOutput output) { super(selfKey,parms,output); } // TODO: What should we do for scoring GLRM? @Override protected double[] score0(double[] data, double[] preds) { throw H2O.unimpl(); } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { return new ModelMetricsGLRM.GLRMModelMetrics(_parms._k); } public static class ModelMetricsGLRM extends ModelMetricsUnsupervised { public ModelMetricsGLRM(Model model, Frame frame) { super(model, frame, Double.NaN); } // GLRM currently does not have any model metrics to compute during scoring public static class GLRMModelMetrics extends MetricBuilderUnsupervised { public GLRMModelMetrics(int dims) { _work = new double[dims]; } @Override public double[] perRow(double[] dataRow, float[] preds, Model m) { return dataRow; } @Override public ModelMetrics makeModelMetrics(Model m, Frame f) { return m._output.addModelMetrics(new ModelMetricsGLRM(m, f)); } } } }
package water.api; import water.*; import water.api.CascadeHandler.Cascade; import water.util.Log; public class CascadeV1 extends Schema<Cascade, CascadeV1> { // Input fields @API(help="An Abstract Syntax Tree.") String ast; // Output @API(help="Parsing error, if any") String error; @API(help="Result key" ) Key key; @API(help="Rows in Frame result" ) long num_rows; @API(help="Columns in Frame result" ) int num_cols; @API(help="Scalar result" ) double scalar; @API(help="Function result" ) String funstr; @API(help="Column Names") String[] col_names; // Pretty-print of result. For Frames, first 10 rows. For scalars, just the // value. For functions, the pretty-printed AST. @API(help="String result" ) String result; // TODO @API(help="Array of Column Summaries.") Inspect2.ColSummary cols[]; @Override public Cascade createImpl() { Cascade c = new Cascade(); if (ast.equals("")) throw H2O.fail("No ast supplied! Nothing to do."); c._ast = ast; return c; } @Override public CascadeV1 fillFromImpl(Cascade cascade) { ast = cascade._ast; key = cascade._key; num_rows = cascade._num_rows; num_cols = cascade._num_cols; scalar = cascade._scalar; funstr = cascade._funstr; result = cascade._result; col_names = cascade._col_names; return this; } }
package water.fvec; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import water.*; import water.exceptions.H2OConcurrentModificationException; import water.util.ArrayUtils; import water.util.FileUtils; import java.io.File; import java.io.IOException; import static org.junit.Assert.*; public class FVecTest extends TestUtil { static final double EPSILON = 1e-6; @BeforeClass public static void setup() { stall_till_cloudsize(1); } @Test public void testBasicCRUD() throws IOException { // Make and insert a FileVec to the global store File file = FileUtils.getFile("./smalldata/junit/cars.csv"); NFSFileVec nfs = NFSFileVec.make(file); int sum = ArrayUtils.sum(new ByteHisto().doAll(nfs)._x); assertEquals(file.length(),sum); nfs.remove(); } private static class ByteHisto extends MRTask<ByteHisto> { public int[] _x; // Count occurrences of bytes @Override public void map( Chunk bv ) { _x = new int[256]; // One-time set histogram array for( int i=0; i< bv._len; i++ ) _x[(int)bv.atd(i)]++; } // ADD together all results @Override public void reduce( ByteHisto bh ) { ArrayUtils.add(_x,bh._x); } } @Test public void testSet() { Frame fr = null; try { fr = parseTestFile("./smalldata/airlines/allyears2k_headers.zip"); double[] mins =new double[fr.numCols()]; for (int i=0; i < mins.length; i++) mins[i] = fr.vecs()[i].min(); // Scribble into a freshly parsed frame new SetDoubleInt(mins).doAll(fr); } finally { if( fr != null ) fr.delete(); } } static class SetDoubleInt extends MRTask { final double _mins[]; public SetDoubleInt(double [] mins) {_mins = mins;} @Override public void map( Chunk chks[] ) { Chunk c=null; int i; for(i=0; i < chks.length; i++) { if( chks[i].getClass()==water.fvec.C2Chunk.class ) { c=chks[i]; break; } } Assert.assertNotNull("Expect to find a C2Chunk", c); assertTrue(c._vec.writable()); double d=_mins[i]; for(i=0; i< c._len; i++ ) { double e = c.atd(i); c.set(i, d); d=e; } } } // Test making a appendable vector from a plain vector @Test public void testNewVec() { // Make and insert a File8Vec to the global store NFSFileVec nfs = TestUtil.makeNfsFileVec("./smalldata/junit/cars.csv"); Vec res = new TestNewVec().doAll(new byte[]{Vec.T_NUM},nfs).outputFrame(new String[]{"v"},new String[][]{null}).anyVec(); assertEquals(nfs.at8(0)+1,res.at8(0)); assertEquals(nfs.at8(1)+1,res.at8(1)); assertEquals(nfs.at8(2)+1,res.at8(2)); nfs.remove(); res.remove(); } private static class TestNewVec extends MRTask<TestNewVec> { @Override public void map( Chunk in, NewChunk out ) { for( int i=0; i< in._len; i++ ) out.addNum( in.at8_abs(i)+(in.at8_abs(i) >= ' ' ? 1 : 0),0); } } @Test public void testParse2() { Frame fr = null; Vec vz = null; try { fr = parseTestFile("smalldata/junit/syn_2659x1049.csv.gz"); assertEquals(fr.numCols(),1050); // Count of columns assertEquals(fr.numRows(),2659); // Count of rows double[] sums = new Sum().doAll(fr)._sums; assertEquals(3949,sums[0],EPSILON); assertEquals(3986,sums[1],EPSILON); assertEquals(3993,sums[2],EPSILON); // Create a temp column of zeros Vec v0 = fr.vecs()[0]; Vec v1 = fr.vecs()[1]; vz = v0.makeZero(); // Add column 0 & 1 into the temp column new PairSum().doAll(vz,v0,v1); // Add the temp to frame // Now total the temp col fr.delete(); // Remove all other columns fr = new Frame(Key.<Frame>make(), new String[]{"tmp"}, new Vec[]{vz}); // Add just this one sums = new Sum().doAll(fr)._sums; assertEquals(3949+3986,sums[0],EPSILON); } finally { if( vz != null ) vz.remove(); if( fr != null ) fr.delete(); } } // Sum each column independently private static class Sum extends MRTask<Sum> { double _sums[]; @Override public void map( Chunk[] bvs ) { _sums = new double[bvs.length]; int len = bvs[0]._len; for( int i=0; i<len; i++ ) for( int j=0; j<bvs.length; j++ ) _sums[j] += bvs[j].atd(i); } @Override public void reduce( Sum mrt ) { ArrayUtils.add(_sums, mrt._sums); } } // Simple vector sum C=A+B private static class PairSum extends MRTask<Sum> { @Override public void map( Chunk out, Chunk in1, Chunk in2 ) { for( int i=0; i< out._len; i++ ) out.set(i, in1.at8(i) + in2.at8(i)); } } @Test public void testRollups() { // Frame fr = null; // try { Key rebalanced = Key.make("rebalanced"); Vec v = null; Frame fr = null; try { v = Vec.makeVec(new double[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, Vec.newKey()); assertEquals(0, v.min(), 0); assertEquals(9, v.max(), 0); assertEquals(4.5,v.mean(),1e-8); H2O.submitTask(new RebalanceDataSet(new Frame(v), rebalanced, 10)).join(); fr = DKV.get(rebalanced).get(); Vec v2 = fr.anyVec(); assertEquals(0, v2.min(), 0); assertEquals(9, v2.max(), 0); assertEquals(4.5, v.mean(), 1e-8); v2.set(5, -100); assertEquals(-100, v2.min(), 0); v2.set(5, 5); // Make several rollups requests in parallel with and without histo and then get histo { Futures fs = new Futures(); v2.startRollupStats(fs); v2.startRollupStats(fs); v2.startRollupStats(fs, true); assertEquals(0, v2.min(), 0); long[] bins = v2.bins(); assertEquals(10, bins.length); for (long l : bins) assertEquals(1, l); fs.blockForPending(); } // Check that rollups cannot be access while Vec is being modified { Vec.Writer w = v2.open(); try { v2.min(); fail("should have thrown IAE since we're requesting rollups while changing the Vec (got Vec.Writer)"); // fail - should've thrown } catch (H2OConcurrentModificationException ie) { // if on local node can get CME directly } catch (RuntimeException re) { assertTrue(re.getCause() instanceof H2OConcurrentModificationException); // expect to get CME since we're requesting rollups while also changing the vec } w.close(); assertEquals(0, v2.min(), 0); } fr.delete(); v.remove(); fr = null; } finally { if( v != null)v.remove(); if(fr != null)fr.delete(); } } // The rollups only compute approximate quantiles, not exact. @Test public void test50pct() { Vec vec = null; try { double[] d = new double[]{0.812834256224, 1.56386606237, 3.12702210880, 3.68417563302, 5.51277746586}; vec = Vec.makeVec(d,Vec.newKey()); double pct[] = vec.pctiles(); double eps = (vec.max()-vec.min())/1e-3; Assert.assertEquals(pct[0],d[0],eps); // 0.01 Assert.assertEquals(pct[1],d[0],eps); Assert.assertEquals(pct[2],d[0],eps); // 0.25 Assert.assertEquals(pct[3],d[1],eps); Assert.assertEquals(pct[4],d[2],eps); Assert.assertEquals(pct[5],d[2],eps); Assert.assertEquals(pct[6],d[3],eps); // 0.75 Assert.assertEquals(pct[7],d[4],eps); Assert.assertEquals(pct[8],d[4],eps); // 0.99 vec.remove(); d = new double[]{490,492,494,496,498}; vec = Vec.makeVec(d,Vec.newKey()); pct = vec.pctiles(); eps = (vec.max()-vec.min())/1e-3; System.out.println(java.util.Arrays.toString(pct)); Assert.assertEquals(pct[0],d[0],eps); // 0.01 } finally { if( vec != null ) vec.remove(); } } }
/* public Application(MemoryLine[] code, MemoryLine[] data, SymbolTable symbols) { */ package fi.hu.cs.titokone; import fi.hu.cs.ttk91.TTK91CompileException; import java.util.HashMap; import java.util.Vector; /** This class knows everything about the relation between symbolic code and binary code. It can transform a full source to binary or one symbolic command to binary or vice versa. Empty out all compiler commands and empty lines at the start of round 2.*/ public class Compiler { /** This field contains the source code as a String array. */ private String[] source; /** This field holds the declared variables, labels and other symbols. It acts as a pointer to the symbolTable Vector where the actual data is stored. */ private HashMap symbols; /** This field holds the invalid values to be introduced (i.e. already used labels can't be re-used. */ private HashMap invalidLabels; /** This field tells the next line to be checked. */ private int nextLine; /** This field holds all the valid symbols on a label. */ private final String VALIDLABELCHARS = "0123456789abcdefghijklmnopqrstuvwxyz_"; private final int NOTVALID = -1; private final int EMPTY = -1; /** Maximum value of the address part. */ private final int MAXINT = 32767; /** Minimum value of the address part. */ private final int MININT = -32767; /** This field holds the value of Stdin if it was set with DEF command. */ private String defStdin; /** This field holds the value of Stdout if it was set with DEF command. */ private String defStdout; /** This field keeps track of whether we are in the first round of compilation or the second. It is set by compile() and updated by compileLine(). */ private boolean firstRound; /** This field counts the number of actual command lines found during the first round. */ private int commandLineCount; /** This array contains the code. During the first round this field holds the clean version of the code (stripped of compiler commands like def, ds, dc etc.) */ private Vector code; /** This field acts as a symboltable, it is a String array vector where 1:st position holds the name of the symbol and the second either it's value (label, equ) or the command (ds 10, dc 10) */ private Vector symbolTable; /** This array contains the data. */ private String[] data; // Second Round /** This field holds the Memoryline objects for the code. These are passed to the Application constructor at the end of the compile process, and are gathered during the second round from first round commands in code-array */ private MemoryLine[] codeMemoryLines; /** This field holds the Memoryline objects for the data area. Much like the code part, this is gathered during the second round and passed to the Application when getApplication() method is called. */ private MemoryLine[] dataMemoryLines; /** This value tells if all the lines are processed twice and getApplication can be run. */ private boolean compileFinished; /** This field contains the CompileDebugger instance to inform of any compilation happenings. */ private CompileDebugger compileDebugger; /** This field contains the SymbolicInterpreter instance to use as part of the compilation. */ private SymbolicInterpreter symbolicInterpreter; /** This constructor sets up the class. It also initializes an instance of CompileDebugger. */ public Compiler() { compileDebugger = new CompileDebugger(); symbolicInterpreter = new SymbolicInterpreter(); } /** This function initializes transforms a symbolic source code into an application class. After this, call compileLine() to actually compile the application one line at a time, and finally getApplication() to get the finished application. @param source The symbolic source code to be compiled. */ public void compile(String source) { firstRound = true; compileFinished = false; this.source = source.split("[\n\r\f\u0085\u2028\u2029]+"); nextLine = 0; defStdin = ""; defStdout = ""; code = new Vector(); symbols = new HashMap(); symbolTable = new Vector(); invalidLabels = new HashMap(); invalidLabels.put("crt", new Integer(0)); invalidLabels.put("kbd", new Integer(1)); invalidLabels.put("stdin", new Integer(6)); invalidLabels.put("stdout", new Integer(7)); invalidLabels.put("halt", new Integer(11)); invalidLabels.put("read", new Integer(12)); invalidLabels.put("write", new Integer(13)); invalidLabels.put("time", new Integer(14)); invalidLabels.put("date", new Integer(15)); } /** This function goes through one line of the code. On the first round, it gathers the symbols and their definitions to a symbol table and conducts syntax-checking, on the second round it transforms each command to its binary format. For the transformations, the CompileConstants class is used. It calls the private methods firstRoundProcess() and secondRoundProcess() to do the actual work, if there is any to do. The transfer from first round of compilation to the second is done automatically; during it, initializeSecondRound() is called. @return A CompileInfo debug information object, describing what happened during the compilation of this line and whether this is the first or second round of compilation or null if there are no more lines left to process. @throws TTK91CompileException If a) there is a syntax error during the first round of checking (error code 101) or b) a symbol is still undefined after the first round of compilation is finished. */ public CompileInfo compileLine() throws TTK91CompileException { CompileInfo info; if (firstRound) { if (nextLine == source.length) { compileDebugger.firstPhase(); info = initializeSecondRound(); return info; } else { compileDebugger.firstPhase(nextLine, source[nextLine]); info = firstRoundProcess(source[nextLine]); ++nextLine; return info; } } else { if (nextLine == code.size()) { compileDebugger.finalPhase(); compileFinished = true; return null; } else { compileDebugger.secondPhase(nextLine, source[nextLine]); info = secondRoundProcess((String)code.get(nextLine)); ++nextLine; return info; } } } /** This method returns the readily-compiled application if the compilation is complete, or null otherwise. */ public Application getApplication() throws IllegalStateException { if (compileFinished) { dataMemoryLines = new MemoryLine[data.length]; for (int i = 0; i < data.length; ++i) { dataMemoryLines[i] = new MemoryLine(Integer.parseInt(data[i]), ""); } SymbolTable st = new SymbolTable(); String[] tempSTLine; for (int i = 0; i < symbolTable.size(); ++i) { tempSTLine = (String[])symbolTable.get(i); st.addSymbol(tempSTLine[0], Integer.parseInt(tempSTLine[1])); } if (!defStdin.equals("")) { st.addDefinition("stdin", defStdin); } if (!defStdout.equals("")) { st.addDefinition("stdout", defStdout); } return new Application(codeMemoryLines, dataMemoryLines, st); } else { throw new IllegalStateException(new Message("Compilation is not " + "finished " + "yet.").toString()); } } /** This function transforms a binary command number to a MemoryLine containing both the binary and the symbolic command corresponding to it. @param binary The command to be translated as binary. @return A MemoryLine instance containing both the information about the symbolic command and the binary version of it. */ public MemoryLine getSymbolicAndBinary(int binary) { BinaryInterpreter bi = new BinaryInterpreter(); return new MemoryLine(binary, bi.binaryToString(binary)); } /** This function transforms a MemoryLine containing only the binary command to a MemoryLine containing both the binary and the symbolic command corresponding to it. @param binaryOnly A MemoryLine containing the binary only of the command to be translated as binary. If the MemoryLine contains both, the pre-set symbolic value is ignored. @return A MemoryLine instance containing both the information about the symbolic command and the binary version of it. */ public MemoryLine getSymbolicAndBinary(MemoryLine binaryOnly) { BinaryInterpreter bi = new BinaryInterpreter(); return new MemoryLine(binaryOnly.getBinary(), bi.binaryToString(binaryOnly.getBinary())); } /** This function gathers new symbol information from the given line and checks its syntax. If a data reservation is detected, the dataAreaSize is incremented accordingly. If the line contains an actual command, commandLineCount is incremented. @param line The line of code to process. @return A CompileInfo object describing what was done, or null if the first round has been completed. This will be the sign for the compiler to prepare for the second round and start it. */ private CompileInfo firstRoundProcess(String line) throws TTK91CompileException { String[] lineTemp = parseCompilerCommandLine(line); boolean nothingFound = true; String comment = ""; String[] commentParameters; int intValue = 0; String[] symbolTableEntry = new String[2]; boolean labelFound = false; boolean variableUsed = false; if (lineTemp == null) { lineTemp = parseLine(line); if (lineTemp == null) { // not a valid command comment = new Message("Not a valid command.").toString(); throw new TTK91CompileException(comment); } else { if (lineTemp[1].equals("")) { // line empty; } else { code.add(line); if (!lineTemp[0].equals("")) { nothingFound = false; labelFound = true; // label found if (invalidLabels.containsKey(lineTemp[0])) { // not a valid label comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } else { invalidLabels.put(lineTemp[0], null); if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = "" + (code.size() - 1); symbolTable.add(Integer.parseInt((String) symbols.get(lineTemp[0])), symbolTableEntry); } else { symbols.put(lineTemp[0], new Integer(code.size() - 1)); symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = "" + (code.size() - 1); symbolTable.add(symbolTableEntry); } compileDebugger.foundLabel(lineTemp[0], code.size() -1); } } try { Integer.parseInt(lineTemp[4]); } catch(NumberFormatException e) { // variable used nothingFound = false; variableUsed = true; compileDebugger.foundSymbol(lineTemp[4]); if (!symbols.containsKey(lineTemp[0])) { if (invalidLabels.get(lineTemp[4]) == null) { symbols.put(lineTemp[4], new Integer(symbolTable.size())); symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = ""; symbolTable.add(symbolTableEntry); } else { // reserver word was used symbols.put(lineTemp[4], new Integer(symbolTable.size())); symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = "" + (Integer) invalidLabels.get(lineTemp[4]); symbolTable.add(symbolTableEntry); } } } if (variableUsed && labelFound) { commentParameters = new String[2]; commentParameters[0] = lineTemp[0]; commentParameters[1] = lineTemp[4]; comment = new Message("Found label {0} and variable " + "{1}.").toString(); compileDebugger.setComment(comment); } else { if (variableUsed) { comment = new Message("Variable {0} used.", lineTemp[4]).toString(); compileDebugger.setComment(comment); } else { if (labelFound) { comment = new Message("Label {0} found.", lineTemp[0]).toString(); compileDebugger.setComment(comment); } } } } } } else { // compiler command boolean allCharsValid = true; boolean atLeastOneNonNumber = false; if (invalidLabels.containsKey(lineTemp[0])) { // not a valid label comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } if(!validLabelName(lineTemp[0])) { // not a valid label; comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); // REMOVED CODE (This did what the above now does) //for (int i = 0; i < lineTemp[0].length(); ++i) { // if (atLeastOneNonNumber == false) { // if (VALIDLABELCHARS.indexOf(lineTemp[0].charAt(i)) > 9) { // atLeastOneNonNumber = true; // if (VALIDLABELCHARS.indexOf(lineTemp[0].charAt(i)) < 0) { // allCharsValid = false; //if (atLeastOneNonNumber == false || allCharsValid == false) { // (report) } else { if (invalidLabels.containsKey(lineTemp[0])) { comment = new Message("Invalid label.").toString(); throw new TTK91CompileException(comment); } if (lineTemp[1].equalsIgnoreCase("ds")) { intValue = 0; try { intValue = Integer.parseInt(lineTemp[2]); } catch(NumberFormatException e) { comment = new Message("Invalid size for a " + "DS.").toString(); throw new TTK91CompileException(comment); } if (intValue < 0 || intValue > MAXINT) { comment = new Message("Invalid size for a " + "DS.").toString(); throw new TTK91CompileException(comment); } } if (lineTemp[1].equalsIgnoreCase("dc")) { intValue = 0; if (lineTemp[2].trim().length() > 0) { try { intValue = Integer.parseInt(lineTemp[2]); } catch(NumberFormatException e) { comment = new Message("Invalid value for a " + "DC.").toString(); throw new TTK91CompileException(comment); } if (intValue < MININT || intValue > MAXINT) { comment = new Message("Invalid value for a " + "DC.").toString(); throw new TTK91CompileException(comment); } } } if (lineTemp[1].equalsIgnoreCase("equ")) { if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[2]; symbolTable.add(Integer.parseInt((String) symbols.get(lineTemp[0])), symbolTableEntry); } else { symbols.put(lineTemp[0], new Integer(symbolTable.size())); symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[2]; symbolTable.add(symbolTableEntry); } compileDebugger.foundEQU(lineTemp[0], intValue); commentParameters = new String[2]; commentParameters[0] = lineTemp[0]; commentParameters[1] = lineTemp[2]; comment = new Message("Variable {0} defined as {1}.", commentParameters).toString(); compileDebugger.setComment(comment); } if (lineTemp[1].equals("ds")) { if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(Integer.parseInt((String)symbols.get(lineTemp[0])), symbolTableEntry); } else { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(symbolTableEntry); } compileDebugger.foundDS(lineTemp[0]); comment = new Message("Found variable {0}.", lineTemp[0]).toString(); compileDebugger.setComment(comment); } if (lineTemp[1].equals("dc")) { compileDebugger.foundDC(lineTemp[0]); if (symbols.containsKey(lineTemp[0])) { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(Integer.parseInt((String)symbols.get(lineTemp[0])), symbolTableEntry); } else { symbolTableEntry[0] = lineTemp[0]; symbolTableEntry[1] = lineTemp[1] + " " + lineTemp[2]; symbolTable.add(symbolTableEntry); } compileDebugger.foundDC(lineTemp[0]); comment = new Message("Found variable {0}.", lineTemp[0]).toString(); compileDebugger.setComment(comment); } if (lineTemp[1].equals("def")) { if (lineTemp[0].equals("stdin") || lineTemp[0].equals("stdout")) { if (lineTemp[0].equals("stdin")) { defStdin = lineTemp[2]; } else { defStdout = lineTemp[2]; } compileDebugger.foundDEF(lineTemp[0], lineTemp[2]); commentParameters = new String[2]; commentParameters[0] = lineTemp[0].toUpperCase(); commentParameters[1] = lineTemp[2]; comment = new Message("{0} defined as {1}.", commentParameters).toString(); compileDebugger.setComment(comment); } else { comment = new Message("Invalid DEF " + "operation.").toString(); throw new TTK91CompileException(comment); } } } } return compileDebugger.lineCompiled(); } /** This method initializes the code and data area arrays for the second round processing according to the dataAreaSize and commandLineCount variables. It also resets the StringTokenizer by calling tokenize(). Before entering the second round we must clear all the empty lines like compiler-codes (pseudo-codes) and lines with nothing but comments. */ private CompileInfo initializeSecondRound() { nextLine = 0; firstRound = false; // copy the code. String[] newCode = new String[code.size()]; for (int i= 0; i < newCode.length; ++i) newCode[i] = (String)code.get(i); String[] lineTemp; int dataAreaSize = 0; // calculate the size of data-area for (int i = 0; i < symbolTable.size(); ++i) { lineTemp = (String[])symbolTable.get(i); if (lineTemp[1].trim().length() > 3) { if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) { dataAreaSize += Integer.parseInt(lineTemp[1].substring(3)); } else { if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc")) ++dataAreaSize; } } } if (!defStdin.equals("")) ++dataAreaSize; if (!defStdout.equals("")) ++dataAreaSize; String[] data = new String[dataAreaSize]; String[] newSymbolTableLine = new String[2]; newSymbolTableLine[0] = ""; newSymbolTableLine[1] = ""; int nextPosition = 0; int nextMemorySlot = newCode.length; int dsValue = 0; // update variable values to symbolTable for (int i = 0; i < symbolTable.size(); ++i) { lineTemp = (String[])symbolTable.get(i); if (lineTemp[1].trim().length() > 2) { if (lineTemp[1].substring(0,2).equalsIgnoreCase("ds")) { dsValue = Integer.parseInt(lineTemp[1].substring(3)); newSymbolTableLine[0] = lineTemp[0]; newSymbolTableLine[1] = "" + nextMemorySlot; symbolTable.add(i, newSymbolTableLine); ++nextMemorySlot; for (int j = nextPosition; j < nextPosition + dsValue; ++nextPosition) { data[j] = "" + 0; } } else { if (lineTemp[1].substring(0,2).equalsIgnoreCase("dc")) { if (lineTemp[1].length() > 3) { data[nextPosition] = lineTemp[1].substring(3); } else { data[nextPosition] = "" + 0; } newSymbolTableLine[0] = lineTemp[0]; newSymbolTableLine[1] = "" + nextMemorySlot; symbolTable.add(i, newSymbolTableLine); ++nextMemorySlot; ++nextPosition; } } } } if (!defStdin.equals("")) { data[nextPosition] = "STDIN " + defStdin; ++nextPosition; } if (!defStdout.equals("")) { data[nextPosition] = "STDOUT " + defStdout; } // make new SymbolTable String[][] newSymbolTable = new String[symbolTable.size()][2]; for (int i= 0; i < newSymbolTable.length; ++i) { newSymbolTable[i] = (String[])symbolTable.get(i); } // prepare for the second round. codeMemoryLines = new MemoryLine[newCode.length]; compileDebugger.finalFirstPhase(newCode, data, newSymbolTable); return compileDebugger.lineCompiled(); } /** This function transforms any commands to binary and stores both forms in the code array, or sets any initial data values in the data array. It uses CompileConstants as its aid. @param line The line of code to process. @return A CompileInfo object describing what was done, or null if the second round and thus the compilation has been completed. */ private CompileInfo secondRoundProcess(String line) throws TTK91CompileException { /* Antti: 04.03.04 Do a pure binary translation first, then when all sections are complete, convert the binary to an integer. Needs variables for opcode(8bit), first operand(3 bit)(r0 to r7), m-part(memory format, direct, indirect or from code), possible index register (3 bit) and 16 bits for the address. Once STORE is converted to a 00000001 and the rest of the code processed we get 32bit binary that is the opcode from symbolic opcode. Antti 08.03.04 Teemu said that we should support the machine spec instead of Koksi with this one. No need to support opcodes like Muumuu LOAD R1, 100 kissa etc. Only tabs and extra spacing. So we need to support opcodes like LOAD R1, 100 but not codes like LOAD R1, =R2. Basic functionality: (Trim between each phase.) Check if there is a label (8 first are the meaningful ones also must have one non-number)) Convert opcode (8bit) check which register (0 to 7) =, Rj/addr or @ (00, 01 or 10) if addr(Ri) or Rj(Ri)(0 to 7) convert address (16bit) check if the rest is fine (empty or starts with ;) Store both formats to a data array (symbolic and binary). */ // check if variable is set! int addressAsInt = 0; int lineAsBinary; String comment; String[] symbolTableEntry; String[] lineTemp = parseLine(line); if (!lineTemp[4].equals("")) { try { addressAsInt = Integer.parseInt(lineTemp[4]); } catch (NumberFormatException e) { symbolTableEntry = (String[])symbolTable.get(Integer.parseInt((String)symbols.get(lineTemp[4]))); if (symbolTableEntry[1].equals("")) { comment = new Message("").toString(); throw new TTK91CompileException(comment); } addressAsInt = Integer.parseInt((String)symbolTableEntry[1]); } } lineAsBinary = symbolicInterpreter.stringToBinary(lineTemp[1], lineTemp[2], lineTemp[3], addressAsInt + "", lineTemp[5]); compileDebugger.setBinary(lineAsBinary); codeMemoryLines[nextLine] = new MemoryLine(lineAsBinary, line); // comment String lineAsZerosAndOnes = symbolicInterpreter.intToBinary(lineAsBinary, 32); String binaryByPositions = symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(0, 8), true) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(8, 11), false) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(11, 13), false) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(13, 16), false) + ":" + symbolicInterpreter.binaryToInt(lineAsZerosAndOnes.substring(16), true); String[] commentParameters = {line, "" + lineAsBinary, binaryByPositions}; comment = new Message("{0} --> {1} ({2}) ", commentParameters).toString(); compileDebugger.setComment(comment); return compileDebugger.lineCompiled(); } /** This method parses a String and tries to find a label, opCode and all the other parts of a Command line. @param symbolicOpCode Symbolic form of an operation code. */ public String[] parseLine(String symbolicOpcode) { String label = ""; String opcode = ""; String firstRegister = ""; String addressingMode = ""; String secondRegister = ""; String address = ""; String[] parsedLine; String wordTemp = ""; int nextToCheck = 0; // for looping out the spacing int fieldEnd = 0; // searches the end of a field (' ', ',') symbolicOpcode = symbolicOpcode.replace('\t',' '); symbolicOpcode = symbolicOpcode.toLowerCase(); symbolicOpcode = symbolicOpcode.trim(); fieldEnd = symbolicOpcode.indexOf(";"); if (fieldEnd != -1) { symbolicOpcode = symbolicOpcode.substring(0, fieldEnd); } /*label or opCode*/ fieldEnd = symbolicOpcode.indexOf(" "); if (fieldEnd == -1) { wordTemp = symbolicOpcode.substring(nextToCheck); fieldEnd = symbolicOpcode.length() -1; } else { wordTemp = symbolicOpcode.substring(nextToCheck, fieldEnd); } if (symbolicInterpreter.getOpcode(wordTemp) == -1) { // Try to find a label of a valid form. if(!validLabelName(wordTemp)) return null; // REMOVED CODE (This did what the above now does.) // try to find a label (not a valid opCode) // label must have one non-number (valid chars A-, 0-9 and _) //boolean allCharsValid = true; //boolean atLeastOneNonNumber = false; //for (int i = 0; i < wordTemp.length(); ++i) { //if (atLeastOneNonNumber == false) { // if (VALIDLABELCHARS.indexOf(wordTemp.charAt(i)) > 9) { // atLeastOneNonNumber = true; //if (VALIDLABELCHARS.indexOf(wordTemp.charAt(i)) < 0) { // allCharsValid = false; //if (atLeastOneNonNumber == false || allCharsValid == false) { // return null; label = wordTemp; nextToCheck = fieldEnd; while (symbolicOpcode.charAt(nextToCheck) == ' ') { ++nextToCheck; } fieldEnd = symbolicOpcode.indexOf(" ", nextToCheck); if (fieldEnd == -1) { wordTemp = symbolicOpcode.substring(nextToCheck); fieldEnd = symbolicOpcode.length(); } else { wordTemp = symbolicOpcode.substring(nextToCheck, fieldEnd); } } opcode = wordTemp; if (symbolicInterpreter.getOpcode(opcode) < 0) { return null; } nextToCheck = fieldEnd + 1; /*first register*/ if (nextToCheck < symbolicOpcode.length()) { while (symbolicOpcode.charAt(nextToCheck) == ' ') { ++nextToCheck; } fieldEnd = symbolicOpcode.indexOf(",", nextToCheck); if (fieldEnd == -1) { if (symbolicInterpreter.getRegisterId(symbolicOpcode.substring(nextToCheck)) != -1) { firstRegister = symbolicOpcode.substring(nextToCheck); fieldEnd = symbolicOpcode.length(); } else { fieldEnd = nextToCheck - 1; } } else { if (symbolicInterpreter.getRegisterId(symbolicOpcode.substring(nextToCheck, fieldEnd)) != -1) { firstRegister = symbolicOpcode.substring(nextToCheck, fieldEnd); } } nextToCheck = fieldEnd + 1; } /*addressingMode*/ if (nextToCheck < symbolicOpcode.length()) { while (symbolicOpcode.charAt(nextToCheck) == ' ') { ++nextToCheck; } if (symbolicOpcode.charAt(nextToCheck) == '=' || symbolicOpcode.charAt(nextToCheck) == '@') { addressingMode = "" + symbolicOpcode.charAt(nextToCheck); ++nextToCheck; } else { addressingMode = ""; } } /*address and second register*/ if (nextToCheck < symbolicOpcode.length()) { while (nextToCheck == ' ') { ++nextToCheck; } if (symbolicOpcode.indexOf("(", nextToCheck) != -1) { if (symbolicOpcode.indexOf(")", nextToCheck) < symbolicOpcode.indexOf("(", nextToCheck)) { return null; } else { address = symbolicOpcode.substring(nextToCheck, symbolicOpcode.indexOf("(", nextToCheck)); secondRegister = symbolicOpcode.substring(symbolicOpcode.indexOf("(", nextToCheck) + 1, symbolicOpcode.indexOf(")", nextToCheck)); if (symbolicInterpreter.getRegisterId(secondRegister) == -1) { return null; } } } else { address = symbolicOpcode.substring(nextToCheck); } } if (symbolicInterpreter.getRegisterId(address) != -1) { secondRegister = address; address = ""; } if (opcode.length() > 0) { if (opcode.charAt(0) == 'j' || opcode.charAt(0) == 'J') { // Opcode matches jneg/jzer/jpos or the negations // jnneg/jnzer/jnpos. if(opcode.toLowerCase().matches("j" + "n?" + "((neg)|(zer)|(pos))")) { // REMOVED CODE (this did what the above now does) //if ("-jneg-jzer-jpos-jnneg-jnzer-jnpos-".indexOf("-" + //opcode.toLowerCase() + "-") != -1) { if (firstRegister.equals("")) return null; } if (addressingMode.equals("=") || address.equals("")) return null; } else { if (opcode.equalsIgnoreCase("nop")) { // (do nothing) } else { if (opcode.equalsIgnoreCase("pop")) { if (addressingMode.equals("@") || addressingMode.equals("=") || !address.equals("")) return null; } else { if (firstRegister.equals("") || (address.equals("") && secondRegister.equals(""))) return null; } } } } if (addressingMode.equals("=") && address.equals("")) return null; if (opcode.equalsIgnoreCase("store") && address.equals("")) return null; if (opcode.equalsIgnoreCase("store") && addressingMode.equals("=")) return null; if (opcode.equals("") && (!label.equals("") || !firstRegister.equals("") || !addressingMode.equals("") || !address.equals("") || !secondRegister.equals(""))) { return null; } parsedLine = new String[6]; parsedLine[0] = label.trim(); parsedLine[1] = opcode.trim(); parsedLine[2] = firstRegister.trim(); parsedLine[3] = addressingMode.trim(); parsedLine[4] = address.trim(); parsedLine[5] = secondRegister.trim(); return parsedLine; } /** This function tries to find a compiler command from the line. Works much like parseLine but this time valid opcodes are DEF, EQU, DC and DS. @param line String representing one line from source code. @return String array with label in position 0, command in the position 1 and position 2 contains the parameter. */ public String[] parseCompilerCommandLine(String line) { int fieldEnd = 0; int nextToCheck = 0; String label = ""; String opcode = ""; String value = ""; int intValue; String[] parsedLine; /* preprosessing */ line = line.trim(); line = line.toLowerCase(); line = line.replace('\t',' '); fieldEnd = line.indexOf(";"); if (fieldEnd != -1) { line = line.substring(0, fieldEnd); } /* LABEL opcode value */ fieldEnd = line.indexOf(" "); if (fieldEnd == -1) { label = line.substring(nextToCheck); fieldEnd = line.length(); } else { label = line.substring(nextToCheck, fieldEnd); } nextToCheck = fieldEnd + 1; /* label OPCODE value */ if (nextToCheck < line.length()) { while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; } fieldEnd = line.indexOf(' ', nextToCheck); if (fieldEnd == -1) { opcode = line.substring(nextToCheck); fieldEnd = line.length(); } else { opcode = line.substring(nextToCheck, fieldEnd); } if (!opcode.matches("((dc)|(ds)|(equ)|(def))")) { return null; } // REMOVED CODE (this did what the above does now) //if ("dcdsequdef".indexOf(opcode) == -1) { // return null; nextToCheck = fieldEnd; } /* label opcode VALUE */ if (nextToCheck < line.length()) { while (line.charAt(nextToCheck) == ' ') { ++nextToCheck; } value = line.substring(nextToCheck); if (value.length() > 0) { try { intValue = Integer.parseInt(value); if (opcode.equalsIgnoreCase("ds") && intValue < 1) { return null; } } catch (NumberFormatException e) { return null; } } } if (!opcode.equalsIgnoreCase("dc") && value.equals("")) return null; parsedLine = new String[3]; parsedLine[0] = label; parsedLine[1] = opcode; parsedLine[2] = value; return parsedLine; } /** This method tests whether a label name contains at least one non-number and consists of 0-9, A- and _. It does not check whether the label is in use already or if it is a reserved word. @param labelName The label name to test. @return True if the label consists of valid characters, false otherwise. */ private boolean validLabelName(String labelName) { // It must have one non-number. Valid characters are A-, 0-9 and _. // Test 1: the word contains one or more of the following: // a-z, A-Z, _, 0-9, , , in any order. // Test 2: the word also contains one non-number (class \D // means anything but 0-9) surrounded by any number of // any character. All these 'anything buts' and 'anys' are // also valid characters, since we check that in Test 1. if(labelName.matches("[\\w]+") && labelName.matches(".*\\D.*")) { return true; } return false; } }
package fi.hu.cs.titokone; import java.text.ParseException; import java.util.HashMap; import java.util.Set; import java.util.Iterator; import java.util.logging.Logger; /** This class keeps track of the settings. It can parse and save settings file content. It provides support for a standard set of settings, but basically anything can be stored in it. Keys used in this file cannot contain KEY_VALUE_SEPARATOR. Whitespace around KEY_VALUE_SEPARATOR is ignored. */ public class Settings { private HashMap settings; /** This string separates keys from values in the settings file. It cannot be included in the key strings. */ public static final String KEY_VALUE_SEPARATOR = "="; /** This field stores the comment marker to put before any comment lines. */ private static final String COMMENT_MARKER = " /** This is one of the default settings keys of values that can be stored here. */ public static final String UI_LANGUAGE = "Language"; public static final String RUN_MODE = "Running mode"; public static final String COMPILE_MODE = "Compilation mode"; public static final String DEFAULT_STDIN = "Stdin file"; public static final String STDIN_PATH = "Stdin path"; public static final String DEFAULT_STDOUT = "Stdout file"; public static final String STDOUT_USE = "Stdout use"; public static final String STDOUT_PATH = "Stdout path"; public static final String MEMORY_SIZE = "Memory size"; /** This constructor sets up a settings class with default values. The settingsFileContent is parsed with the help fo the parseSettingsFile() method. @param settingsFileContent A String containing what has been in a settings file for parsing. @throws ParseException If the settings text was not syntactically correct. */ public Settings(String settingsFileContent) throws ParseException { settings = new HashMap(); if(settingsFileContent != null) parseSettingsFile(settingsFileContent); } public void setValue(String key, String value) { String expMessage; String[] parameters = new String[3]; StringTokenizer tokenChecker; parameters[0] = new Message("value").toString(); // Check that the value string does not contain linebreaks // in other positions than its end. To check that, match against // a pattern of 1 or more characters (there is a start of a line // in the start of each String, hence ignore the first character), // then 1 or more periods where there is at least one start of // line (\n\n would match ^^) and then 0 or more other characters. // We assume here that since Pattern.MULTILINE mode is on // by default now, it will be on in other places as well. if(value.matches(".+[^+&&.*]+")) { parameters[1] = value; parameters[2] = new Message("a linebreak"); expMessage = new Message("Illegal {0} \"{1}\", contains {2}.", parameters).toString(); throw new IllegalArgumentException(expMessage); } if(value == null) { expMessage = new Message("Illegal {0}: null. Try an empty " + "string instead.", parameters).toString(); throw new IllegalArgumentException(expMessage); } doSetValue(key, value); } /** This method sets a key to a certain integer value. @param key The key to point to the value. @param value The value to be stored. */ public void setValue(String key, int value) { doSetValue(key, new Integer(value)); } private void doSetValue(String key, Object value) { String[] parameters = new String[3]; parameters[0] = new Message("key").toString(); // The regular expression below matches any character (.) // 0 or more times (*) followed by a KEY_VALUE_SEPARATOR, // followed by any character 0 or more times. if(key.matches(".*" + KEY_VALUE_SEPARATOR + ".*")) { parameters[1] = key; parameters[2] = "'" + KEY_VALUE_SEPARATOR + "'"; expMessage = new Message("Illegal {0} \"{1}\", contains {2}.", parameters).toString(); throw new IllegalArgumentException(expMessage); } if(key == null) { expMessage = new Message("Illegal {0}: null. Try an empty " + "string instead.", parameters).toString(); throw new IllegalArgumentException(expMessage); } settings.put(key, value); } /** This method returns the value of a certain key. It will try to cast it to an integer before returning. @param key The key pointing to the value to be returned. @return The value the key points to, cast to an int. @throws ClassCastException If the value was not an int. @throws NullPointerException If there was no value stored by that key (or if the value stored was null for some reason). The problem is that int cannot be null, while String in getStrValue can. */ public int getIntValue(String key) { return ((Integer) settings.get(key)).toInt(); } /** This method returns the value of a certain key. It will try to cast it to a string before returning. @param key The key pointing to the value to be returned. @return The value the key points to, cast to a String. @throws ClassCastException If the value was not a String. */ public String getStrValue(String key) { return (String) settings.get(key); } /** This method transforms this settings class into a format which can be parsed by parseSettingsFile. @return String containing the non-fixed data in this class. */ public String toString() { String keyString, valueString; StringBuffer result; Object value; Iterator keyIterator = settings.keySet().iterator(); result = ""; while(iterator.hasNext()) { keyString = (String) iterator.next(); value = settings.get(key); try { valueString = (String) settings.get(key); } catch(ClassCastException mustBeAnIntegerThen) { valueString = "" + ((Integer) value).intValue(); } result.append(keyString + " " + KEY_VALUE_SEPARATOR + " " + valueString + System.getProperty("line.separator", "\n")); } return result.toString(); } /** This method parses the fileContent string and sets up the settings HashMap values accordingly. It will try to cast number strings to integers. @param fileContent A String containing what has been in a settings file for parsing. @throws ParseException If the settings text was not syntactically correct. */ private void parseSettingsFile(String fileContent) throws ParseException { StringTokenizer rowenizer; String[] parameters = new String[2], parts; String line, errorMessage, key, valueString; int lineCounter; Logger logger; // We accept \n,\r and whatever this system uses as a line separator. // StringTokenizer will not mind matching against eg. \r\r; it will // be considered the same as \r. rowenizer = new StringTokenizer(fileContent, "\n\r" + System.getProperty("line.separator", "\n")); int lineCounter = 0; while(rowenizer.hasMoreTokens()) { lineCounter++; line = rowenizer.nextToken(); // First, check if it is an empty line or a comment line. // Ignore those. // (Trimming does not modify the string.) if(line.trim() != "" && !line.startsWith(COMMENT_MARKER)) { parts = line.split(KEY_VALUE_SEPARATOR); if(parts.length != 2) { // Log where we failed and on what. parameters[0] = "" + lineCounter; parameters[1] = line; errorMessage = new Message("Syntax error on line {0}, " + "which was: \"{1}\".", parameters).toString(); throw new ParseException(errorMessage); } else { // Line has 2 parts as it should. key = parts[0].trim(); valueString = parts[1].trim(); try { setValue(key, Integer.parseInt(valueString)); } catch(NumberFormatException notAnIntegerThen) { setValue(key, valueString); } } } } parameters[0] = "" + lineCounter; parameters[1] = "" + settings.size(); logger = Logger.getLogger(this.getClass().getPackage()); logger.info(new Message("Settings successfully parsed, lines: " + "{0}, unique keys found: {1}.", parameters)); } }
package foam.dao; import foam.core.*; import foam.lib.json.ExprParser; import foam.lib.json.JSONParser; import foam.lib.json.Outputter; import foam.lib.json.OutputterMode; import foam.lib.parse.*; import foam.mlang.order.Comparator; import foam.mlang.predicate.Predicate; import foam.nanos.auth.User; import foam.nanos.logger.*; import foam.util.SafetyUtil; import java.io.*; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.regex.Pattern; import java.util.TimeZone; import java.util.List; import java.util.Iterator; public abstract class AbstractJDAO extends ProxyDAO { protected Pattern COMMENT = Pattern.compile("(/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|( protected static final ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); return sdf; } }; protected final File outFile_; protected final BufferedWriter out_; protected Logger logger_ = new StdoutLogger(); public AbstractJDAO(foam.core.X x, ClassInfo classInfo, String filename) { this(x, new MapDAO(classInfo), filename); setOf(classInfo); } public AbstractJDAO(foam.core.X x, DAO delegate, String filename){ setX(x); setOf(delegate.getOf()); setDelegate(delegate); Logger logger = logger_; if ( x != null ) { logger = (Logger) x.get("logger"); if ( logger == null ) logger = logger_; } logger_ = new PrefixLogger(new Object[] { "[JDAO]", filename }, logger); try { //get repo entries in filename.0 journal first File inFile = getX().get(foam.nanos.fs.Storage.class).get(filename + ".0"); //load repo entries into DAO if ( inFile.exists() ) loadJournal(inFile); //get output journal outFile_ = getX().get(foam.nanos.fs.Storage.class).get(filename); //if output journal does not existing, create one if ( ! outFile_.exists() ) { //if output journal does not exist, create one outFile_.createNewFile(); } else { //if output journal file exists, load entries into DAO loadJournal(outFile_); } //link output journal file to BufferedWriter out_ = new BufferedWriter(new FileWriter(outFile_, true)); } catch ( IOException e ) { logger_.error(e); throw new RuntimeException(e); } } protected abstract Outputter getOutputter(); protected void loadJournal(File file) throws IOException { JSONParser parser = getX().create(JSONParser.class); BufferedReader br = new BufferedReader(new FileReader(file)); for ( String line ; ( line = br.readLine() ) != null ; ) { // skip empty lines & comment lines if ( SafetyUtil.isEmpty(line) ) continue; if ( COMMENT.matcher(line).matches() ) continue; try { char operation = line.charAt(0); // remove first two characters and last character line = line.trim().substring(2, line.trim().length() - 1); FObject object = parser.parseString(line); if ( object == null ) { logger_.error("parse error", getParsingErrorMessage(line), "line:", line); continue; } switch ( operation ) { case 'p': PropertyInfo id = getOf().getPrimaryKey("id"); if ( getDelegate().find(id.get(object)) != null ) { //If data exists, merge difference //get old date FObject old = getDelegate().find(id.get(object)); //merge difference object = mergeChange(old, object); } getDelegate().put(object); break; case 'r': getDelegate().remove(object); break; } } catch (Throwable t) { logger_.error("error replaying journal line:", line, t); } } br.close(); } /** * Gets the result of a failed parsing of a journal line * @param line the line that was failed to be parse * @return the error message */ protected String getParsingErrorMessage(String line) { Parser parser = new ExprParser(); PStream ps = new StringPStream(); ParserContext x = new ParserContextImpl(); ((StringPStream) ps).setString(line); x.set("X", ( getX() == null ) ? new ProxyX() : getX()); ErrorReportingPStream eps = new ErrorReportingPStream(ps); ps = eps.apply(parser, x); return eps.getMessage(); } protected void writeComment(User user) throws IOException { out_.write(" out_.write(user.getFirstName()); if ( ! SafetyUtil.isEmpty(user.getLastName()) ) { out_.write(" "); out_.write(user.getLastName()); } out_.write(" ("); out_.write(String.valueOf(user.getId())); out_.write(")"); out_.write(" at "); out_.write(sdf.get().format(Calendar.getInstance().getTime())); out_.newLine(); } /** * persists data into FileJournal then calls the delegated DAO. * * @param obj * @returns FObject */ @Override public FObject put_(X x, FObject obj) { PropertyInfo id = getOf().getPrimaryKey("id"); FObject o = getDelegate().find_(x, id.get(obj)); FObject ret = null; String record = null; if ( o == null ) { //data does not exist ret = getDelegate().put_(x, obj); //stringify to json string record = getOutputter().stringify(ret); } else { //compare with old data if old data exists //get difference FObject ret = difference(o, obj); //if no difference, then return if ( ret == null ) return obj; //stringify difference FObject into json string record = getOutputter().stringify(ret); //put new data into memory ret = getDelegate().put_(x, obj); } try { // TODO(drish): supress class name from output writeComment((User) x.get("user")); out_.write("p(" + record + ")"); out_.newLine(); out_.flush(); } catch (Throwable e) { logger_.error("put", e); } return ret; } @Override public FObject remove_(X x, FObject obj) { Object id = getPrimaryKey().get(obj); FObject ret = getDelegate().remove_(x, obj); try { writeComment((User) x.get("user")); // TODO: Would be more efficient to output the ID portion of the object. But // if ID is an alias or multi part id we should only output the // true properties that ID/MultiPartID maps too. FObject r = generateFObject(ret); PropertyInfo idInfo = (PropertyInfo) getOf().getAxiomByName("id"); idInfo.set(r, idInfo.get(ret)); out_.write("r(" + getOutputter().stringify(r) + ")"); out_.newLine(); out_.flush(); } catch (IOException e) { logger_.error("remove", e); } return ret; } @Override public void removeAll_(final X x, long skip, final long limit, Comparator order, Predicate predicate) { // file.delete(); getDelegate().select_(x, new RemoveSink(x, this), skip, limit, order, predicate); getDelegate().removeAll_(x, skip, limit, order, predicate); } protected FObject difference(FObject o, FObject n) { FObject diff = hasDiff(o, n); //no difference, then return null if ( diff == null ) return null; //get the PropertyInfo for the id PropertyInfo idInfo = (PropertyInfo) getOf().getAxiomByName("id"); //set id property to new instance idInfo.set(diff, idInfo.get(o)); return diff; } protected FObject hasDiff(FObject o, FObject n) { // if either new or old is null, return new instance. if ( o == null || n == null ) return n; // if two instances are same, return new instance because cannot check the difference; if ( o == n ) return n; FObject ret = null; List list = o.getClassInfo().getAxiomsByClass(PropertyInfo.class); Iterator e = list.iterator(); while( e.hasNext() ) { PropertyInfo prop = (PropertyInfo) e.next(); if ( prop instanceof AbstractFObjectPropertyInfo ) { FObject diff = hasDiff((FObject) prop.get(o), (FObject) prop.get(n)); //if there is difference, set difference if ( diff != null ) { //create only when there is difference if ( ret == null ) ret = generateFObject(o); //set diff prop.set(ret, diff); } } else if ( prop instanceof AbstractFObjectArrayPropertyInfo ) { //TODO: if instances are same, can not check array //create only when there is array if ( ret == null ) ret = generateFObject(o); prop.set(ret, prop.get(n)); } else if ( ! (prop instanceof AbstractEnumPropertyInfo) && (prop instanceof AbstractObjectPropertyInfo || prop instanceof AbstractArrayPropertyInfo) ) { //can not handle reference type except enum if ( ret == null ) ret = generateFObject(o); prop.set(ret, prop.get(n)); } else { //handle primitive value and enum int same = prop.comparePropertyToObject(o, prop.get(n)); if ( same != 0 ) { //create only when there is difference if ( ret == null ) ret = generateFObject(o); prop.set(ret, prop.get(n)); } } } return ret; } protected FObject mergeChange(FObject o, FObject c) { //if no change to merge, return FObject; if ( c == null ) return o; //merge change return maybeMerge(o, c); } protected FObject maybeMerge(FObject o, FObject c) { if ( o == null ) return o = c; //get PropertyInfos List list = o.getClassInfo().getAxiomsByClass(PropertyInfo.class); Iterator e = list.iterator(); while ( e.hasNext() ) { PropertyInfo prop = (PropertyInfo) e.next(); if ( prop instanceof AbstractFObjectPropertyInfo ) { //do nested merge //check if change if ( ! prop.isSet(c) ) continue; maybeMerge((FObject) prop.get(o), (FObject) prop.get(c)); } else { //check if change if ( ! prop.isSet(c) ) continue; //set new value prop.set(o, prop.get(c)); } } return o; } //return a new Fobject protected FObject generateFObject(FObject o) { try { ClassInfo classInfo = o.getClassInfo(); //create a new Instance FObject ret = (FObject) classInfo.getObjClass().newInstance(); return ret; } catch ( Throwable t ) { throw new RuntimeException(t); } } }
package graphic; import org.newdawn.slick.SlickException; import org.newdawn.slick.*; /** * Balloon Sprite, Player of the game */ public class Balloon extends Sprite{ private float speed; protected Balloon() throws SlickException { super("data/image/balloon.png", true); } public Balloon(float x, float y) throws SlickException { super(x, y, "data/image/balloon.png",true); setSpeed(0); } public void reset(float x, float y) { setX(x); setY(y); setSpeed(0); } public void setSpeed(float speed){ this.speed = speed; } public float getSpeed(){ return speed; } public void move(float offsetX, float offsetY){ setX(getX() + offsetX); setY(getY() + offsetY); } public void update(GameContainer gameContainer, int delta){ float deltaTime = delta / 1000.0f; Input input = gameContainer.getInput(); updatePlayer(deltaTime, input); } private void updatePlayer(float deltaTime, Input input) { if (input.isKeyDown(Input.KEY_SPACE)) { setSpeed(getSpeed() - (deltaTime * 500.0f)); move(0.0f, getSpeed() * deltaTime); } else { setSpeed(getSpeed() + (deltaTime * 500.0f)); move(0.0f, getSpeed() * deltaTime); } } }
package ext.drawable; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.PixelFormat; import android.graphics.Rect; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.view.animation.DecelerateInterpolator; import ext.R; public class MaterialEditTextDrawable extends AnimatedDrawable { protected Rect mBounds; protected Paint mPaint; protected Paint mFocusedPaint; protected ObjectAnimator mAnimator; protected boolean mFocused; protected boolean mStartAnimation; protected boolean mAnimateFromCenter; protected int mWidth; protected int mStrokeWidth; public MaterialEditTextDrawable(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); TypedArray array = context.obtainStyledAttributes(R.styleable.ThemeExtension); int colorPrimary = array.getColor(R.styleable.ThemeExtension_colorPrimary, Color.TRANSPARENT); int colorPrimaryDark = array.getColor(R.styleable.ThemeExtension_colorPrimaryDark, Color.TRANSPARENT); array.recycle(); array = context.obtainStyledAttributes(attrs, R.styleable.EditText, defStyleAttr, defStyleRes); mStrokeWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, context.getResources().getDisplayMetrics()); mStrokeWidth = array.getDimensionPixelSize(R.styleable.EditText_backgroundStrokeWidth, mStrokeWidth); mAnimateFromCenter = array.getBoolean(R.styleable.EditText_animateFromCenter, mAnimateFromCenter); array.recycle(); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Style.FILL); mPaint.setColor(colorPrimary); mFocusedPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mFocusedPaint.setStyle(Style.FILL); mFocusedPaint.setColor(colorPrimaryDark); mBounds = new Rect(); } @Override protected void onBoundsChange(Rect bounds) { mBounds.set(bounds); if (mStartAnimation) { startAnimation(); } } @Override public int getIntrinsicHeight() { return mBounds.isEmpty() ? -1 : (mBounds.bottom - mBounds.top); } @Override public int getIntrinsicWidth() { return mBounds.isEmpty() ? -1 : (mBounds.right - mBounds.left); } @Override public void draw(Canvas canvas) { final Rect bounds = getBounds(); final int saveCount = canvas.save(); canvas.translate(bounds.left, bounds.top); canvas.drawRect(getBounds().left, getBounds().bottom - mStrokeWidth, getBounds().right, getBounds().bottom, mPaint); if (mAnimateFromCenter) { int w = getIntrinsicWidth(); float left = ((float) (w - mWidth)) / 2.0f; float right = left + mWidth; canvas.drawRect(left, getBounds().bottom - mStrokeWidth, right, getBounds().bottom, mFocusedPaint); } else { canvas.drawRect(getBounds().left, getBounds().bottom - mStrokeWidth, getBounds().left + mWidth, getBounds().bottom, mFocusedPaint); } canvas.restoreToCount(saveCount); } @Override public void setAlpha(int alpha) { // nothing } @Override public void setColorFilter(ColorFilter cf) { // nothing } @Override public int getOpacity() { return PixelFormat.UNKNOWN; } public void setWidth(int width) { mWidth = width; invalidateSelf(); } @Override public void startAnimation() { if (mAnimator == null) { mAnimator = ObjectAnimator.ofInt(this, "width", 0, getIntrinsicWidth()); mAnimator.setDuration(mAnimationDuration); mAnimator.setInterpolator(new DecelerateInterpolator()); mAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mStartAnimation = false; } }); } mAnimator.start(); } @Override public void reverseAnimation() { mAnimator.reverse(); } @Override public void onViewAttachedToWindow(View view) { // nothing } @Override public void onViewDetachedToWindow(View view) { if (mAnimator != null) { mAnimator.cancel(); } } @Override public void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { mFocused = focused; if (mBounds.isEmpty()) { mStartAnimation = true; } else { animateFocus(); } } private void animateFocus() { if (mFocused) { startAnimation(); } else { reverseAnimation(); } } }
package net.divlight.retainer; import android.os.Bundle; import android.support.annotation.UiThread; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.util.Log; /** * An utility class that helps retaining objects in an Activity / Fragment during configuration * changes. * <p> * Call <code>Retainer.onCreate(this)</code> and <code>Retainer.onDestroy(this)</code> in your * activity or fragment. {@link net.divlight.retainer.annotation.Retain} annotated fields will be * automatically preserved by Retainer. */ public class Retainer { private static final String TAG = Retainer.class.getSimpleName(); private Retainer() { } /** * To preserve {@link net.divlight.retainer.annotation.Retain} annotated fields, Bind a target * to a container object(a auto-generated fragment that is called setRetainInstance(true)). * <p> * This method is intended to be called in {@link FragmentActivity#onCreate(Bundle)}. * * @param target Target activity for retaining objects. */ @UiThread public static <T extends FragmentActivity> void onCreate(T target) { onCreate(target, target.getSupportFragmentManager(), RetainFragment.DEFAULT_TAG); } /** * To preserve {@link net.divlight.retainer.annotation.Retain} annotated fields, Bind a target * to a container object(a auto-generated fragment that is called setRetainInstance(true)). * <p> * This method is intended to be called in {@link Fragment#onCreate(Bundle)}. * * @param target Target fragment for retaining objects. */ @UiThread public static <T extends Fragment> void onCreate(T target) { onCreate(target, target.getChildFragmentManager(), RetainFragment.DEFAULT_TAG); } /** * To preserve {@link net.divlight.retainer.annotation.Retain} annotated fields, Bind a target * to a container object(a auto-generated fragment that is called setRetainInstance(true)). * <p> * This method is intended to be called in {@link FragmentActivity#onCreate(Bundle)} or * {@link Fragment#onCreate(Bundle)}. * * @param target Target activity or fragment for retaining objects. * @param fragmentManager FragmentManager used for committing the container fragment. * @param tag The tag name for the container fragment. */ @SuppressWarnings("unchecked") @UiThread public static <T> void onCreate(T target, FragmentManager fragmentManager, String tag) { final Fragment fragment = fragmentManager.findFragmentByTag(tag); if (fragment != null) { final Object<T> object = ((RetainFragment<T>) fragment).getObject(); if (object != null) { object.restore(target); } } else { fragmentManager.beginTransaction() .add(new RetainFragment<T>(), tag) .commitAllowingStateLoss(); } } /** * Save {@link net.divlight.retainer.annotation.Retain} annotated fields to a container object. * <p> * This method is intended to be called in {@link FragmentActivity#onDestroy()}. * * @param target Target activity for retaining objects. */ @UiThread public static <T extends FragmentActivity> void onDestroy(T target) { onDestroy(target, target.getSupportFragmentManager(), RetainFragment.DEFAULT_TAG); } /** * Save {@link net.divlight.retainer.annotation.Retain} annotated fields to a container object. * <p> * This method is intended to be called in {@link Fragment#onDestroy()}. * * @param target Target fragment for retaining objects. */ @UiThread public static <T extends Fragment> void onDestroy(T target) { onDestroy(target, target.getChildFragmentManager(), RetainFragment.DEFAULT_TAG); } /** * Save {@link net.divlight.retainer.annotation.Retain} annotated fields to a container object. * <p> * This method is intended to be called in {@link FragmentActivity#onDestroy()} or * {@link Fragment#onDestroy()}. * * @param target Target activity or fragment for retaining objects. * @param fragmentManager FragmentManager used for finding the container fragment. * @param tag The tag name for the container fragment. */ @SuppressWarnings("unchecked") @UiThread public static <T> void onDestroy(T target, FragmentManager fragmentManager, String tag) { final Fragment fragment = fragmentManager.findFragmentByTag(tag); if (fragment == null) { Log.w(TAG, "Could not find the fragment for preserving instance states." + " Make sure not to forget calling Retainer#onCreate."); return; } try { final String packageName = target.getClass().getPackage().getName(); final String className = getObjectClassName(target.getClass()); final Class<?> clazz = Class.forName(packageName + "." + className); final Object<T> object = (Object<T>) clazz.newInstance(); object.save(target); ((RetainFragment<T>) fragment).setObject(object); } catch (Exception e) { Log.w(TAG, "Failed to create a object instance for preserving instance states."); } } private static String getObjectClassName(Class<?> targetClass) { final String targetClassName = targetClass.getSimpleName(); final ObjectClassNameBuilder builder = new ObjectClassNameBuilder(targetClassName); Class<?> clazz = targetClass.getEnclosingClass(); while (clazz != null) { builder.addEnclosingClassSimpleName(clazz.getSimpleName()); clazz = clazz.getEnclosingClass(); } return builder.build(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder.resources; import io.milton.http.Range; import io.milton.http.exceptions.BadRequestException; import java.io.*; import java.math.BigInteger; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.UnknownHostException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import lombok.extern.java.Log; import nl.uva.cs.lobcder.util.Constants; import nl.uva.cs.lobcder.util.DesEncrypter; import nl.uva.cs.lobcder.util.SpeedLogger; import nl.uva.vlet.Global; import nl.uva.vlet.GlobalConfig; import nl.uva.vlet.data.StringUtil; import nl.uva.vlet.exception.ResourceNotFoundException; import nl.uva.vlet.exception.VRLSyntaxException; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.io.CircularStreamBufferTransferer; import nl.uva.vlet.util.cog.GridProxy; import nl.uva.vlet.vfs.*; import nl.uva.vlet.vfs.cloud.CloudFile; import nl.uva.vlet.vrl.VRL; import nl.uva.vlet.vrs.ServerInfo; import nl.uva.vlet.vrs.VRS; import nl.uva.vlet.vrs.VRSContext; import nl.uva.vlet.vrs.io.VRandomReadable; /** * A test PDRI to implement the delete get/set data methods with the VRS API * * @author S. koulouzis */ @Log public class VPDRI implements PDRI { static { try { InitGlobalVFS(); } catch (Exception ex) { Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex); } } private static void InitGlobalVFS() throws MalformedURLException, VlException, Exception { try { GlobalConfig.setBaseLocation(new URL("http://dummy/url")); } catch (MalformedURLException ex) { Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex); } // runtime configuration GlobalConfig.setHasUI(false); // GlobalConfig.setIsApplet(true); GlobalConfig.setPassiveMode(true); // GlobalConfig.setIsService(true); GlobalConfig.setInitURLStreamFactory(false); GlobalConfig.setAllowUserInteraction(false); GlobalConfig.setUserHomeLocation(new URL("file:///" + System.getProperty("user.home"))); // GlobalConfig.setUsePersistantUserConfiguration(false); GlobalConfig.setCACertificateLocations(Constants.CERT_LOCATION); // user configuration // GlobalConfig.setUsePersistantUserConfiguration(false); // GlobalConfig.setUserHomeLocation(new URL("file:////" + this.tmpVPHuserHome.getAbsolutePath())); // Global.setDebug(true); VRS.getRegistry().addVRSDriverClass(nl.uva.vlet.vfs.cloud.CloudFSFactory.class); Global.init(); } private VFSClient vfsClient; // private MyStorageSite storageSite; private VRL vrl; private final String username; private final String password; private final Long storageSiteId; private final String baseDir = "LOBCDER-REPLICA-vTEST";//"LOBCDER-REPLICA-v2.0"; private final String fileName; private int reconnectAttemts = 0; private final static boolean debug = true; private BigInteger keyInt; private boolean encrypt; private final String resourceUrl; private boolean doChunked; private int sleeTime = 5; private static final Map<String, GridProxy> proxyCache = new HashMap<>(); public VPDRI(String fileName, Long storageSiteId, String resourceUrl, String username, String password, boolean encrypt, BigInteger keyInt, boolean doChunkUpload) throws IOException { try { this.fileName = fileName; this.resourceUrl = resourceUrl; String encoded = VRL.encode(fileName); vrl = new VRL(resourceUrl).appendPath(baseDir).append(encoded); // vrl = new VRL(resourceUrl).appendPath(baseDir).append(URLEncoder.encode(fileName, "UTF-8").replace("+", "%20")); this.storageSiteId = storageSiteId; this.username = username; this.password = password; this.encrypt = encrypt; this.keyInt = keyInt; this.doChunked = doChunkUpload; // this.resourceUrl = resourceUrl; VPDRI.log.log(Level.FINE, "fileName: {0}, storageSiteId: {1}, username: {2}, password: {3}, VRL: {4}", new Object[]{fileName, storageSiteId, username, password, vrl}); initVFS(); } catch (VlException | IOException | URISyntaxException ex) { throw new IOException(ex); } } private void initVFS() throws VlException, MalformedURLException, IOException, FileNotFoundException, URISyntaxException { this.vfsClient = new VFSClient(); VRSContext context = this.getVfsClient().getVRSContext(); //Bug in sftp: We have to put the username in the url ServerInfo info = context.getServerInfoFor(vrl, true); String authScheme = info.getAuthScheme(); if (StringUtil.equals(authScheme, ServerInfo.GSI_AUTH)) { copyVomsAndCerts(); GridProxy gridProxy = proxyCache.get(password); if (gridProxy == null) { String proxyFile = "/tmp/myProxy"; context.setProperty("grid.proxy.location", proxyFile); // Default to $HOME/.globus context.setProperty("grid.certificate.location", Global.getUserHome() + "/.globus"); String vo = username; context.setProperty("grid.proxy.voName", vo); context.setProperty("grid.proxy.lifetime", "200"); // gridProxy = GridProxy.loadFrom(context, proxyFile); gridProxy = context.getGridProxy(); if (gridProxy.isValid() == false) { gridProxy.setEnableVOMS(true); gridProxy.setDefaultVOName(vo); gridProxy.createWithPassword(password); if (gridProxy.isValid() == false) { throw new VlException("Created Proxy is not Valid!"); } gridProxy.saveProxyTo(proxyFile); proxyCache.put(password, gridProxy); } } } if (StringUtil.equals(authScheme, ServerInfo.PASSWORD_AUTH) || StringUtil.equals(authScheme, ServerInfo.PASSWORD_OR_PASSPHRASE_AUTH) || StringUtil.equals(authScheme, ServerInfo.PASSPHRASE_AUTH)) { // String username = storageSite.getCredential().getStorageSiteUsername(); if (username == null) { throw new NullPointerException("Username is null!"); } info.setUsername(username); // String password = storageSite.getCredential().getStorageSitePassword(); if (password == null) { throw new NullPointerException("password is null!"); } info.setPassword(password); } info.setAttribute(ServerInfo.ATTR_DEFAULT_YES_NO_ANSWER, true); // if(getVrl().getScheme().equals(VRS.SFTP_SCHEME)){ //patch for bug with ssh driver info.setAttribute("sshKnownHostsFile", System.getProperty("user.home") + "/.ssh/known_hosts"); context.setProperty("chunk.upload", doChunked); // info.setAttribute(new VAttribute("chunk.upload", true)); info.store(); } @Override public void delete() throws IOException { try { getVfsClient().openLocation(vrl).delete(); } catch (VlException ex) { //Maybe it's from assimilation. We must remove the baseDir if (ex instanceof ResourceNotFoundException || ex.getMessage().contains("Couldn open location. Get NULL object for location")) { try { // VRL assimilationVRL = new VRL(resourceUrl).append(URLEncoder.encode(fileName, "UTF-8").replace("+", "%20")); // String encoded = VRL.encode(fileName); VRL assimilationVRL = new VRL(resourceUrl).append(fileName); getVfsClient().openLocation(assimilationVRL).delete(); } catch (IOException | VlException ex1) { Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex1); } } else { Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex); } } finally { } // //it's void so do it asynchronously // Runnable asyncDel = getAsyncDelete(this.vfsClient, vrl); // asyncDel.run(); } @Override public void copyRange(Range range, OutputStream out) throws IOException { VFile file; try { file = (VFile) getVfsClient().openLocation(vrl); doCopy(file, range, out, getEncrypted()); } catch (IOException | VlException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) { if (ex instanceof ResourceNotFoundException || ex.getMessage().contains("Couldn open location. Get NULL object for location:")) { try { // VRL assimilationVRL = new VRL(resourceUrl).append(URLEncoder.encode(fileName, "UTF-8")); VRL assimilationVRL = new VRL(resourceUrl).append(fileName); file = (VFile) getVfsClient().openLocation(assimilationVRL); doCopy(file, range, out, getEncrypted()); sleeTime = 5; } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | VRLSyntaxException ex1) { throw new IOException(ex1); } catch (VlException ex1) { if (reconnectAttemts < Constants.RECONNECT_NTRY) { try { sleeTime = sleeTime + 5; Thread.sleep(sleeTime); reconnect(); getData(); } catch (InterruptedException ex2) { throw new IOException(ex1); } } else { throw new IOException(ex1); } } } else if (reconnectAttemts < Constants.RECONNECT_NTRY && !ex.getMessage().contentEquals("does not support random reads")) { try { sleeTime = sleeTime + 5; Thread.sleep(sleeTime); reconnect(); copyRange(range, out); } catch (InterruptedException ex1) { throw new IOException(ex); } } else { throw new IOException(ex); } } finally { } } private void doCopy(VFile file, Range range, OutputStream out, boolean decript) throws VlException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { long len = range.getFinish() - range.getStart() + 1; InputStream in = null; int buffSize; Long start = range.getStart(); if (len <= Constants.BUF_SIZE) { buffSize = (int) len; } else { buffSize = Constants.BUF_SIZE; } DesEncrypter en = null; if (decript) { en = new DesEncrypter(getKeyInt()); } int read; try { if (file instanceof VRandomReadable) { VRandomReadable ra = (VRandomReadable) file; len = range.getFinish() - range.getStart() + 1; byte[] buff = new byte[buffSize]; int totalBytesRead = 0; while (totalBytesRead < len) { read = ra.readBytes(start, buff, 0, buff.length); totalBytesRead += read; start += buff.length; if (decript) { byte[] tmp = en.decrypt(buff); buff = tmp; } out.write(buff, 0, read); } } else { in = getData(); if (decript) { InputStream tmp = en.wrapInputStream(in); in = tmp; } if (start > 0) { throw new IOException("Backend at " + vrl.getScheme() + "://" + vrl.getHostname() + "does not support random reads"); // long skiped = in.skip(start); // if (skiped != start) { // long n = start; // int buflen = (int) Math.min(Constants.BUF_SIZE, n); // byte data[] = new byte[buflen]; // while (n > 0) { // int r = in.read(data, 0, (int) Math.min((long) buflen, n)); // if (r < 0) { // break; // n -= r; } // int totalBytesRead = 0; // byte[] buff = new byte[buffSize]; // while (totalBytesRead < len) { // read = in.read(buff, 0, buff.length); // totalBytesRead += read; // start += buff.length; // out.write(buff, 0, read); CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer(buffSize, in, out); cBuff.startTransfer(len); } } finally { if (in != null) { in.close(); } } } @Override public InputStream getData() throws IOException { InputStream in = null; VFile file; int read; try { file = (VFile) getVfsClient().openLocation(vrl); in = file.getInputStream(); } catch (IOException | VlException ex) { if (ex instanceof ResourceNotFoundException || ex.getMessage().contains("Couldn open location. Get NULL object for location:")) { try { // VRL assimilationVRL = new VRL(resourceUrl).append(URLEncoder.encode(fileName, "UTF-8")); VRL assimilationVRL = new VRL(resourceUrl).append(fileName); in = ((VFile) getVfsClient().openLocation(assimilationVRL)).getInputStream(); sleeTime = 5; } catch (VRLSyntaxException ex1) { throw new IOException(ex1); } catch (VlException ex1) { if (reconnectAttemts < Constants.RECONNECT_NTRY) { try { sleeTime = sleeTime + 5; Thread.sleep(sleeTime); reconnect(); getData(); } catch (InterruptedException ex2) { throw new IOException(ex1); } } else { throw new IOException(ex1); } } } else if (reconnectAttemts < Constants.RECONNECT_NTRY) { try { sleeTime = sleeTime + 5; Thread.sleep(sleeTime); reconnect(); getData(); } catch (InterruptedException ex1) { throw new IOException(ex); } } else { throw new IOException(ex); } } finally { // reconnect(); } return in; } @Override public void putData(InputStream in) throws IOException { OutputStream out = null; VPDRI.log.log(Level.FINE, "putData:"); // VFile tmpFile = null; try { // upload(in); VRL parentVrl = vrl.getParent(); VDir remoteDir = getVfsClient().mkdirs(parentVrl, true); getVfsClient().createFile(vrl, true); out = getVfsClient().getFile(vrl).getOutputStream(); if (!getEncrypted()) { CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((Constants.BUF_SIZE), in, out); cBuff.startTransfer(new Long(-1)); // int read; // byte[] copyBuffer = new byte[Constants.BUF_SIZE]; // while ((read = in.read(copyBuffer, 0, copyBuffer.length)) != -1) { // out.write(copyBuffer, 0, read); } else { DesEncrypter encrypter = new DesEncrypter(getKeyInt()); encrypter.encrypt(in, out); } reconnectAttemts = 0; } catch (nl.uva.vlet.exception.VlAuthenticationException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException ex) { throw new IOException(ex); } catch (VlException ex) { if (ex.getMessage() != null) { VPDRI.log.log(Level.FINE, "\tVlException {0}", ex.getMessage()); } if (reconnectAttemts <= 2) { VPDRI.log.log(Level.FINE, "\treconnectAttemts {0}", reconnectAttemts); reconnect(); putData(in); } else { throw new IOException(ex); } // if (ex instanceof ResourceNotFoundException || ex.getMessage().contains("not found") || ex.getMessage().contains("Couldn open location") || ex.getMessage().contains("not found in container")) { // try { // vfsClient.mkdirs(vrl.getParent(), true); // vfsClient.createFile(vrl, true); // putData(in); // } catch (VlException ex1) { // throw new IOException(ex1); } finally { if (out != null) { try { out.flush(); out.close(); } catch (java.io.IOException ex) { } } if (in != null) { in.close(); } } } @Override public Long getStorageSiteId() { return this.storageSiteId;//storageSite.getStorageSiteId(); } @Override public String getFileName() { return this.fileName; } @Override public String getHost() throws UnknownHostException { VPDRI.log.log(Level.FINE, "getHostName: {0}", InetAddress.getLocalHost().getHostName()); if (vrl.getScheme().equals("file") || StringUtil.isEmpty(vrl.getHostname()) || vrl.getHostname().equals("localhost") || vrl.getHostname().equals("127.0.0.1")) { return InetAddress.getLocalHost().getHostName(); } else { return vrl.getHostname(); } } @Override public long getLength() throws IOException { try { return getVfsClient().getFile(vrl).getLength(); } catch (IOException | VlException ex) { if (reconnectAttemts < Constants.RECONNECT_NTRY) { reconnect(); getLength(); } else { throw new IOException(ex); } } finally { } return 0; } @Override public void reconnect() throws IOException { reconnectAttemts++; getVfsClient().close(); getVfsClient().dispose(); // VRS.exit(); try { initVFS(); } catch (VlException | IOException | URISyntaxException ex1) { throw new IOException(ex1); } } @Override public Long getChecksum() throws IOException { try { VFile physicalFile = getVfsClient().getFile(vrl); if (physicalFile instanceof VChecksum) { BigInteger bi = new BigInteger(((VChecksum) physicalFile).getChecksum("MD5"), 16); return bi.longValue(); } } catch (VlException ex) { throw new IOException(ex); } finally { } return null; } // private void debug(String msg) { // if (debug) { //// System.err.println(this.getClass().getName() + ": " + msg); // log.debug(msg); private void upload(PDRI source) throws VlException, IOException { if (getVfsClient() == null) { reconnect(); } CloudFile thisFile = (CloudFile) getVfsClient().createFile(vrl, true); VFile sourceFile = getVfsClient().openFile(new VRL(source.getURI())); thisFile.uploadFrom(sourceFile); } @Override public void replicate(PDRI source) throws IOException { try { VRL sourceVRL = new VRL(source.getURI()); String sourceScheme = sourceVRL.getScheme(); String desteScheme = vrl.getScheme(); VPDRI.log.log(Level.INFO, "Start replicating {0} to {1}", new Object[]{source.getURI(), getURI()}); double start = System.currentTimeMillis(); if (!vfsClient.existsDir(vrl.getParent())) { VDir remoteDir = vfsClient.mkdirs(vrl.getParent(), true); } if (desteScheme.equals("swift") && sourceScheme.equals("file")) { upload(source); } else { VFile destFile = getVfsClient().createFile(vrl, true); VFile sourceFile = getVfsClient().openFile(sourceVRL); getVfsClient().copy(sourceFile, destFile); } // putData(source.getData()); double elapsed = System.currentTimeMillis() - start; double speed = ((source.getLength() * 8.0) * 1000.0) / (elapsed * 1000.0); String msg = "Source: " + source.getHost() + " Destination: " + vrl.getScheme() + "://" + getHost() + " Replication_Speed: " + speed + " Kbites/sec Repl_Size: " + (getLength()) + " bytes"; VPDRI.log.log(Level.INFO, msg); SpeedLogger.logSpeed(msg); // getAsyncDelete(getVfsClient(), vrl).run(); } catch (VlException ex) { Logger.getLogger(VPDRI.class.getName()).log(Level.SEVERE, null, ex); } } // @Override // public void setKeyInt(BigInteger keyInt) { // this.keyInt = keyInt; @Override public BigInteger getKeyInt() { return this.keyInt; } @Override public boolean getEncrypted() { return this.encrypt; } // @Override // public void replicate(PDRI source) throws IOException { // try { // VRL sourceVRL = new VRL(source.getURI()); //// VRL destVRL = this.vrl.getParent(); // log.debug("replicate from "+sourceVRL+" to "+vrl); // VFile sourceFile = this.vfsClient.openFile(sourceVRL); // VFile destFile = this.vfsClient.createFile(vrl, true); // if (destFile instanceof CloudFile) { // ((CloudFile) destFile).uploadFrom(sourceFile); // } else { // putData(source.getData()); // } catch (VlException ex) { // throw new IOException(ex); @Override public String getURI() throws IOException { try { return this.vrl.toURIString(); } catch (VRLSyntaxException ex) { throw new IOException(ex); } } /** * @return the vfsClient */ private VFSClient getVfsClient() throws IOException { if (vfsClient == null) { reconnect(); } return vfsClient; } private void copyVomsAndCerts() throws FileNotFoundException, VlException, URISyntaxException { File f = new File(System.getProperty("user.home") + "/.globus/vomsdir"); File vomsFile = new File(f.getAbsoluteFile() + "/voms.xml"); if (!vomsFile.exists()) { f.mkdirs(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream in = classLoader.getResourceAsStream("/voms.xml"); FileOutputStream out = new FileOutputStream(vomsFile); CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((Constants.BUF_SIZE), in, out); cBuff.startTransfer(new Long(-1)); } f = new File(Constants.CERT_LOCATION); if (!f.exists() || f.list().length == 0) { f.mkdirs(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL res = classLoader.getResource("/certs/"); File sourceCerts = new File(res.toURI()); File[] certs = sourceCerts.listFiles(); for (File src : certs) { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(f.getAbsoluteFile() + "/" + src.getName()); CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((Constants.BUF_SIZE), in, out); cBuff.startTransfer(new Long(-1)); } } } }
package org.neo4j.kernel.ha.zookeeper; import java.util.Map; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.helpers.Pair; import org.neo4j.kernel.ha.MasterClient; import org.neo4j.kernel.ha.MasterImpl; import org.neo4j.kernel.ha.MasterServer; import org.neo4j.kernel.impl.ha.Broker; import org.neo4j.kernel.impl.ha.Master; public class ZooKeeperBroker implements Broker { private final ZooClient zooClient; private final int machineId; private final Map<Integer,String> haServers; private int machineIdForMasterClient; private MasterClient masterClient; public ZooKeeperBroker( String storeDir, int machineId, String zooKeeperServers, Map<Integer,String> haServers ) { this.machineId = machineId; this.haServers = haServers; NeoStoreUtil store = new NeoStoreUtil( storeDir ); this.zooClient = new ZooClient( zooKeeperServers, machineId, store.getCreationTime(), store.getStoreId(), store.getLastCommittedTx() ); // int masterId = zooClient.getMaster(); // if ( masterId != this.machineId ) // getAndCacheMaster( masterId ); } public Master getMaster() { int masterId = zooClient.getMaster(); if ( masterId == machineId ) { throw new ZooKeeperException( "I am master, so can't call getMaster() here", new Exception() ); // throw new RuntimeException( "I am master" ); } return getAndCacheMaster( masterId ); } private Master getAndCacheMaster( int masterId ) { if ( masterClient == null || masterId != machineIdForMasterClient || zooClient.isNewConnection() ) { machineIdForMasterClient = masterId; // TODO synchronization Pair<String, Integer> host = getHaServer( masterId ); masterClient = new MasterClient( host.first(), host.other() ); // To make sure the flag is reset (it may not have been called in the if-statement) zooClient.isNewConnection(); } return masterClient; } private Pair<String, Integer> getHaServer( int machineId ) { String host = haServers.get( machineId ); if ( host == null ) { throw new RuntimeException( "No HA server for machine ID " + machineId ); } int pos = host.indexOf( ":" ); return new Pair<String, Integer>( host.substring( 0, pos ), Integer.parseInt( host.substring( pos + 1 ) ) ); } public Object instantiateMasterServer( GraphDatabaseService graphDb ) { return new MasterServer( new MasterImpl( graphDb ), getHaServer( getMyMachineId() ).other() ); } public void setLastCommittedTxId( long txId ) { zooClient.setCommittedTx( txId ); } public boolean thisIsMaster() { return zooClient.getMaster() == machineId; } public int getMyMachineId() { return machineId; } }
package eu.nerro.wolappla.ui; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import eu.nerro.wolappla.R; import eu.nerro.wolappla.provider.DeviceContract; import static eu.nerro.wolappla.util.LogUtils.LOGV; import static eu.nerro.wolappla.util.LogUtils.makeLogTag; public class DevicesFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(DevicesFragment.class); private static final int URL_LOADER = 0; private CursorAdapter mAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_list_devices, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mAdapter = new DevicesAdapter(getActivity()); setListAdapter(mAdapter); getLoaderManager().restartLoader(URL_LOADER, null, this); } @Override public Loader<Cursor> onCreateLoader(int loaderId, Bundle data) { switch (loaderId) { case URL_LOADER: LOGV(TAG, "onCreateLoader() - cursor loader for devices is created"); return new CursorLoader( getActivity(), DeviceContract.Devices.CONTENT_URI, DevicesQuery.PROJECTION, null, null, DeviceContract.Devices.DEFAULT_SORT); default: return null; } } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (getActivity() == null) { return; } mAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } /** * {@link DeviceContract.Devices} query parameters. */ private interface DevicesQuery { String[] PROJECTION = { DeviceContract.Devices._ID, DeviceContract.Devices.DEVICE_NAME, DeviceContract.Devices.DEVICE_MAC_ADDRESS, DeviceContract.Devices.DEVICE_IP_ADDRESS, DeviceContract.Devices.DEVICE_PORT, }; int ID = 0; int NAME = 1; int MAC_ADDRESS = 2; int IP_ADDRESS = 3; int PORT = 4; } /** * {@link CursorAdapter} that renders a {@link DevicesQuery}. */ private class DevicesAdapter extends CursorAdapter { public DevicesAdapter(Context context) { super(context, null, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_device, parent, false); } @Override public void bindView(View view, Context context, final Cursor cursor) { final String deviceId = cursor.getString(DevicesQuery.ID); if (deviceId == null) { return; } final TextView nameView = (TextView) view.findViewById(R.id.device_name); final TextView macAddressView = (TextView) view.findViewById(R.id.device_mac_address); final TextView ipAddressView = (TextView) view.findViewById(R.id.device_ip_address); final TextView portView = (TextView) view.findViewById(R.id.device_port); final String deviceName = cursor.getString(DevicesQuery.NAME); final String deviceMacAddress = cursor.getString(DevicesQuery.MAC_ADDRESS); final String deviceIpAddress = cursor.getString(DevicesQuery.IP_ADDRESS); final String devicePort = cursor.getString(DevicesQuery.PORT); nameView.setText(deviceName); macAddressView.setText(deviceMacAddress); ipAddressView.setText(deviceIpAddress); portView.setText(devicePort); } } }
package com.handson.rx; import com.handson.infra.EventStreamClient; import com.handson.infra.RxNettyEventEventStreamClient; import rx.schedulers.Schedulers; import java.io.IOException; public class Application { public static void main(String[] args) throws IOException { EventStreamClient forexEventStreamClient = new RxNettyEventEventStreamClient(8096); ForexServer forexServer = new ForexServer(8080, forexEventStreamClient); forexServer.createServer().start(); EventStreamClient stockEventStreamClient = new RxNettyEventEventStreamClient(8097); StockServer stockServer = new StockServer(8081, stockEventStreamClient, forexEventStreamClient); stockServer.createServer().start(); EventStreamClient tradeEventStreamClient = new RxNettyEventEventStreamClient(8098); VwapServer vwapServer = new VwapServer(8082, tradeEventStreamClient, Schedulers.immediate()); vwapServer.createServer().start(); System.out.println("Servers ready!"); System.out.println("Press any key to exit"); //new RxNettyEventEventStreamClient(8080).readServerSideEvents().toBlocking().forEach(System.out::println); System.in.read(); } }
package org.noear.weed; import org.noear.weed.ext.Fun0; import java.sql.SQLException; @Deprecated public class DbTable extends DbTableQueryBase<DbTable> { protected DataItemEx _item = new DataItemEx(); //null public DbTable(DbContext context) { super(context); } protected void set(String name, Fun0<Object> valueGetter) { _item.set(name, valueGetter); } //null public long insert() throws SQLException { return insert(_item); } //null public int update() throws SQLException { return update(_item); } //null public long insert(GetHandler source) throws SQLException { return insert(DataItem.create(_item, source)); } //null public void update(GetHandler source) throws SQLException { update(DataItem.create(_item, source)); } // public <T> void insertList(List<T> valuesList, Fun1<GetHandler, T> hander) throws SQLException { // List<GetHandler> list2 = new ArrayList<>(); // for (T item : valuesList) { // list2.add(hander.run(item)); // insertList(list2); // public <T extends GetHandler> boolean insertList(List<T> valuesList) throws SQLException { // return insertList(_item, valuesList); }
package global; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; public class HttpClientUtil implements GlobalConstant{ static Logger logger = Logger.getLogger("http"); /** * URLhtml * @param url * @return html */ public static String getHtmlByUrl(String url){ String html = null; //httpClient HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT); //getURL HttpGet httpget = new HttpGet(url); httpget.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30 * 1000); httpget.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30 * 1000); try { //responce HttpResponse responce = httpClient.execute(httpget); int resStatu = responce.getStatusLine().getStatusCode(); //200 if (resStatu== HttpStatus.SC_OK) { HttpEntity entity = responce.getEntity(); if (entity!=null) { //html html = EntityUtils.toString(entity); EntityUtils.consume(entity); } } } catch (Exception e) { logger.error(""+url+"!"); logger.error(e); } finally { httpget.abort(); httpClient.getConnectionManager().shutdown(); } return html; } }
package grundkurs_java; import java.awt.*; import java.awt.event.KeyEvent; import javax.swing.*; public class Chap14 { public static void main(String[] args) { // FrameMitTextUndToolTip.main(args); // FrameMitSchwarzemLabel.main(args); // FrameMitMonospacedText.main(args); // FrameMitFlowLayout.main(args); // FrameMitBorderLayout.main(args); // FrameMitGridLayout.main(args); // FrameMitBild.main(args); // FrameMitButtons.main(args); // FrameMitToggleButtons.main(args); // FrameMitCheckBoxes.main(args); // FrameMitRadioButtons.main(args); // FrameMitComboBoxes.main(args); // FrameMitListe.main(args); // FrameMitTextFeldern.main(args); // FrameMitTextArea.main(args); // FrameMitScrollText.main(args); // FrameMitPanels.main(args); // TopLevelContainer.main(args); FrameMitMenuBar.main(args); } } class FrameMitMenuBar extends JFrame { Container c; // Container dieses Frames JMenuBar menuBar; // Menueleiste JMenu menu; // Menue JMenuItem menuItem; // Menue-Eintrag JToolBar toolBar; // Werkzeugleiste JButton button; // Knoepfe der Werkzeugleiste JLabel textLabel; // Label, das im Frame erscheinen soll public FrameMitMenuBar() { // Konstruktor // Bestimme die Referenz auf den eigenen Container c = getContentPane(); // Erzeuge die Menueleiste. menuBar = new JMenuBar(); // Erzeuge ein Menue menu = new JMenu("Bilder"); menu.setMnemonic(KeyEvent.VK_B); // Erzeuge die Menue-Eintraege und fuege sie dem Menue hinzu menuItem = new JMenuItem("Hund"); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_H); menu.add(menuItem); menuItem = new JMenuItem("Katze"); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_K); menu.add(menuItem); menuItem = new JMenuItem("Maus"); menuItem.setMnemonic(java.awt.event.KeyEvent.VK_M); menu.add(menuItem); // Fuege das Menue der Menueleiste hinzu menuBar.add(menu); // Fuegt das Menue dem Frame hinzu setJMenuBar(menuBar); // Erzeuge die Werkzeugleiste toolBar = new JToolBar("Rahmenfarbe"); // Erzeuge die Knoepfe button = new JButton(new ImageIcon("images/rot.gif")); button.setToolTipText("roter Rahmen"); toolBar.add(button); button = new JButton(new ImageIcon("images/gruen.gif")); button.setToolTipText("gruener Rahmen"); toolBar.add(button); button = new JButton(new ImageIcon("images/blau.gif")); button.setToolTipText("blauer Rahmen"); toolBar.add(button); // Erzeuge das Labelobjekt textLabel = new JLabel("Hier erscheint mal ein Bild mit Rahmen.", JLabel.CENTER); // Fuege Label und Toolbar dem Container hinzu c.add(textLabel, BorderLayout.CENTER); c.add(toolBar, BorderLayout.NORTH); } public static void main(String[] args) { FrameMitMenuBar fenster = new FrameMitMenuBar(); fenster.setTitle("Frame mit Menueleiste und Toolbar"); fenster.setSize(350, 170); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class TopLevelContainer { public static void main(String[] args) { // Hauptfenster erzeugen und beschriften JFrame f = new JFrame(); f.getContentPane().add(new JLabel("Frame", JLabel.CENTER)); f.setTitle("Frame"); f.setSize(300, 150); f.setLocation(100, 100); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Unterfenster (Window) erzeugen und beschriften JWindow w = new JWindow(f); w.getContentPane().add(new JLabel("Window", JLabel.CENTER)); w.setSize(150, 150); w.setLocation(410, 100); w.setVisible(true); // Modales Unterfenster (Dialog) erzeugen und beschriften JDialog d = new JDialog(f, true); d.getContentPane().add(new JLabel("Dialog", JLabel.CENTER)); d.setTitle("Dialog"); d.setSize(150, 100); d.setLocation(300, 180); d.setVisible(true); d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } class FrameMitPanels extends JFrame { Container c; // Container dieses Frames JPanel jp1, jp2, jp3; // Panels public FrameMitPanels() { c = getContentPane(); // Panels erzeugen jp1 = new JPanel(); // Konstruktor // Container bestimmen14.5 Einige Grundkomponenten jp2 = new JPanel(); jp3 = new JPanel(new GridLayout(2, 3)); // Vier Tasten in Panel 1 einfuegen for (int i = 1; i <= 4; i++) jp1.add(new JButton("Taste " + i)); // Bildobjekt erzeugen Icon bild = new ImageIcon("kitten.jpg"); // Bild drei mal in Panel 2 einfuegen for (int i = 1; i <= 3; i++) jp2.add(new JLabel(bild)); // Sechs Haekchen-Kaestchen in Panel 3 einfuegen for (int i = 1; i <= 6; i++) jp3.add(new JCheckBox("Auswahl-Box " + i)); // Panels in den Container einfuegen c.add(jp1, BorderLayout.NORTH); c.add(jp2, BorderLayout.CENTER); c.add(jp3, BorderLayout.SOUTH); } public static void main(String[] args) { FrameMitPanels fenster = new FrameMitPanels(); fenster.setTitle("Label mit Panels"); fenster.setSize(350, 200); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitScrollText extends JFrame { Container c; // Container dieses Frames JLabel info; // Label JTextArea ta; // TextArea JScrollPane sp; // ScrollPane public FrameMitScrollText() { c = getContentPane(); // Konstruktor // Container bestimmen // Erzeuge Label und TextArea info = new JLabel("Hier kann Text bearbeitet werden"); ta = new JTextArea("Einiges an Text steht auch schon hier rum."); // Setze die Schriftart Font schrift = new Font("SansSerif", Font.BOLD + Font.ITALIC, 16); ta.setFont(schrift); ta.setLineWrap(true); // Automatischer Zeilenumbruch ta.setWrapStyleWord(true); // wortweise sp = new JScrollPane(ta); // Scrollpane erzeugen // Fuege die Komponenten hinzu c.add(info, BorderLayout.NORTH); c.add(sp); } public static void main(String[] args) { FrameMitScrollText fenster = new FrameMitScrollText(); fenster.setTitle("Frame mit ScrollTextArea"); fenster.setSize(250, 160); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitTextArea extends JFrame { Container c; // Container dieses Frames JLabel info; // Label JTextArea ta; // TextArea public FrameMitTextArea() { c = getContentPane(); // Konstruktor // Container bestimmen // Erzeuge Label und TextArea info = new JLabel("Hier kann Text bearbeitet werden"); ta = new JTextArea("Einiges an Text steht auch schon hier rum."); // Setze die Schriftart Font schrift = new Font("SansSerif", Font.BOLD + Font.ITALIC, 16); ta.setFont(schrift); // Automatischen Umbruch aktivieren ta.setLineWrap(true); ta.setWrapStyleWord(true); // Fuege die Komponenten hinzu c.add(info, BorderLayout.NORTH); c.add(ta); } public static void main(String[] args) { FrameMitTextArea fenster = new FrameMitTextArea(); fenster.setTitle("Frame mit TextArea"); fenster.setSize(200, 160); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitTextFeldern extends JFrame { Container c; // Container dieses Frames JLabel name, passwd; // Labels JTextField tf; // Textfeld JPasswordField pf; // Passwortfeld public FrameMitTextFeldern() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new GridLayout(2, 2)); // Layout setzen14.5 Einige // Grundkomponenten // Erzeuge die Labels und Textfelder name = new JLabel("Name:", JLabel.RIGHT); passwd = new JLabel("Passwort:", JLabel.RIGHT); tf = new JTextField(); pf = new JPasswordField(); // Setze die Schriftart Font schrift = new Font("SansSerif", Font.BOLD, 18); name.setFont(schrift); passwd.setFont(schrift); tf.setFont(schrift); pf.setFont(schrift); // Fuege die Komponenten hinzu c.add(name); c.add(tf); c.add(passwd); c.add(pf); } public static void main(String[] args) { FrameMitTextFeldern fenster = new FrameMitTextFeldern(); fenster.setTitle("Frame mit Textfeldern"); fenster.setSize(220, 100); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitListe extends JFrame { Container c; // Container dieses Frames // Liste und Combo-Box, die im Frame erscheinen sollen JList vornamen; JComboBox nachnamen; public FrameMitListe() { // Konstruktor446 c = getContentPane(); c.setLayout(new FlowLayout()); // Container bestimmen // Layout setzen // Eintraege fuer Vornamen-Combo-Box festlegen String[] namen = new String[] { "Bilbo", "Frodo", "Samwise", "Meriadoc", "Peregrin" }; vornamen = new JList(namen); // Liste mit Eintraegen nachnamen = new JComboBox(); // Leere Combo-Box nachnamen.addItem("Baggins"); // Eintraege hinzufuegen nachnamen.addItem("Brandybuck"); nachnamen.addItem("Gamgee"); nachnamen.addItem("Took"); // Liste und Combo-Box dem Frame hinzufuegen c.add(vornamen); c.add(nachnamen); } public static void main(String[] args) { FrameMitListe fenster = new FrameMitListe(); fenster.setTitle("Frame mit Liste"); fenster.setSize(240, 160); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitComboBoxes extends JFrame { Container c; // Container dieses Frames // Combo-Boxes, die im Frame erscheinen sollen JComboBox vornamen, nachnamen; public FrameMitComboBoxes() { // Konstruktor14.5 Einige Grundkomponenten c = getContentPane(); c.setLayout(new FlowLayout()); // Container bestimmen // Layout setzen // Eintraege fuer Vornamen-Combo-Box festlegen String[] namen = new String[] { "Bilbo", "Frodo", "Samwise", "Meriadoc", "Peregrin" }; vornamen = new JComboBox(namen); // Combo-Box mit Eintraegen nachnamen = new JComboBox(); // Leere Combo-Box nachnamen.addItem("Baggins"); // Eintraege hinzufuegen nachnamen.addItem("Brandybuck"); nachnamen.addItem("Gamgee"); nachnamen.addItem("Took"); // Den dritten Nachnamen (Index 2) selektieren nachnamen.setSelectedIndex(2); // Combo-Boxes dem Frame hinzufuegen c.add(vornamen); c.add(nachnamen); } public static void main(String[] args) { FrameMitComboBoxes fenster = new FrameMitComboBoxes(); fenster.setTitle("Frame mit ComboBoxes"); fenster.setSize(240, 160); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitRadioButtons extends JFrame { Container c; // Container dieses Frames // Feld fuer Radio-Buttons, die im Frame erscheinen sollen JRadioButton rb[] = new JRadioButton[4]; public FrameMitRadioButtons() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new FlowLayout()); // Layout setzen // Gruppe erzeugen ButtonGroup bg = new ButtonGroup(); // Erzeuge die Button-Objekte und fuege // sie dem Frame und der Gruppe hinzu for (int i = 0; i < 4; i++) { rb[i] = new JRadioButton("Box " + (i + 1)); // erzeugen bg.add(rb[i]); // der Gruppe hinzufuegen c.add(rb[i]); // dem Frame hinzufuegen } } public static void main(String[] args) { FrameMitRadioButtons fenster = new FrameMitRadioButtons(); fenster.setTitle("Frame mit RadioButtons"); fenster.setSize(330, 60); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitCheckBoxes extends JFrame { Container c; // Container dieses Frames // Feld fuer Check-Boxes, die im Frame erscheinen sollen14.5 Einige // Grundkomponenten JCheckBox cb[] = new JCheckBox[4]; public FrameMitCheckBoxes() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new FlowLayout()); // Layout setzen // Erzeuge die Button-Objekte for (int i = 0; i < 4; i++) cb[i] = new JCheckBox("Box " + (i + 1)); cb[0].setSelected(true); cb[2].setSelected(true); // Fuege die Buttons dem Frame hinzu for (int i = 0; i < 4; i++) { c.add(cb[i]); } } public static void main(String[] args) { FrameMitCheckBoxes fenster = new FrameMitCheckBoxes(); fenster.setTitle("Frame mit CheckBoxes"); fenster.setSize(280, 60); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitToggleButtons extends JFrame { Container c; // Container dieses Frames // Feld fuer Toggle-Buttons, die im Frame erscheinen sollen JToggleButton b[] = new JToggleButton[4]; public FrameMitToggleButtons() { c = getContentPane(); c.setLayout(new FlowLayout()); // Konstruktor // Container bestimmen // Layout setzen // Erzeuge die Button-Objekte for (int i = 0; i < 4; i++) { b[i] = new JToggleButton("Schalter " + (i + 1)); b[i].setFont(new Font("SansSerif", Font.ITALIC, 24)); } b[0].setSelected(true); b[2].setSelected(true); // Fuege die Buttons dem Frame hinzu for (int i = 0; i < 4; i++) { c.add(b[i]); } } public static void main(String[] args) { FrameMitToggleButtons fenster = new FrameMitToggleButtons(); fenster.setTitle("Frame mit Buttons"); fenster.setSize(330, 130); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitButtons extends JFrame { Container c; // Container dieses Frames // Feld fuer Buttons, die im Frame erscheinen sollen JButton b[] = new JButton[4]; public FrameMitButtons() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new FlowLayout()); // Layout setzen // Erzeuge die Button-Objekte for (int i = 0; i < 4; i++) { b[i] = new JButton("Taste " + (i + 1)); b[i].setFont(new Font("SansSerif", Font.ITALIC, 24)); } // Fuege die Buttons dem Frame hinzu for (int i = 0; i < 4; i++) { c.add(b[i]); } } public static void main(String[] args) { FrameMitButtons fenster = new FrameMitButtons(); fenster.setTitle("Frame mit Buttons"); fenster.setSize(250, 130); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitBild extends JFrame { Container c; // Container dieses Frames JLabel lab; // Label das im Frame erscheinen soll public FrameMitBild() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new FlowLayout()); // Layout setzen // Bildobjekt erzeugen Icon bild = new ImageIcon("kitten.jpg"); // Label mit Text und Bild beschriften lab = new JLabel("Spotty", bild, JLabel.CENTER); // Text unter das Bild setzen lab.setHorizontalTextPosition(JLabel.CENTER); lab.setVerticalTextPosition(JLabel.BOTTOM); // Fuege das Label dem Frame hinzu c.add(lab); } public static void main(String[] args) { FrameMitBild fenster = new FrameMitBild(); fenster.setTitle("Label mit Bild und Text"); fenster.setSize(250, 185); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitGridLayout extends JFrame { Container c; // Container dieses Frames // Feld fuer Labels, die im Frame erscheinen sollen FarbigesLabel fl[] = new FarbigesLabel[6]; public FrameMitGridLayout() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new GridLayout(2, 3, 10, 40)); // Layout setzen /* Erzeuge die Labelobjekte mit Text und Farbe */ for (int i = 0; i < 6; i++) { int rgbFg = 255 - i * 50; int rgbBg = i * 50; fl[i] = new FarbigesLabel("Nummer " + (i + 1), new Color(rgbFg, rgbFg, rgbFg), new Color(rgbBg, rgbBg, rgbBg)); fl[i].setFont(new Font("Serif", Font.ITALIC, 10 + i * 3)); } // Fuege die Labels dem Frame hinzu for (int i = 0; i < 6; i++) { c.add(fl[i]); } } public static void main(String[] args) { FrameMitGridLayout fenster = new FrameMitGridLayout(); fenster.setTitle("Frame mit Grid-Layout"); fenster.setSize(300, 150); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitBorderLayout extends JFrame { Container c; // Container dieses Frames // Labelfeld fuer Label, die im Frame erscheinen sollen430 FarbigesLabel fl[] = new FarbigesLabel[5]; public FrameMitBorderLayout() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new BorderLayout()); // Layout setzen /* Erzeuge die Labelobjekte mit Text und Farbe */ fl[0] = new FarbigesLabel("Norden", Color.BLACK, Color.WHITE); fl[1] = new FarbigesLabel("Sueden", Color.WHITE, Color.LIGHT_GRAY); fl[2] = new FarbigesLabel("Osten", Color.WHITE, Color.GRAY); fl[3] = new FarbigesLabel("Westen", Color.WHITE, Color.DARK_GRAY); fl[4] = new FarbigesLabel("Zentrum", Color.WHITE, Color.BLACK); for (int i = 0; i < 5; i++) { // Setze die Schriftart der Labelbeschriftung fl[i].setFont(new Font("SansSerif", Font.BOLD, 14)); // Setze die horizontale Position des Labeltextes auf dem Label fl[i].setHorizontalAlignment(JLabel.CENTER); } // Fuege die Labels dem Frame hinzu c.add(fl[0], BorderLayout.NORTH); c.add(fl[1], BorderLayout.SOUTH); c.add(fl[2], BorderLayout.EAST); c.add(fl[3], BorderLayout.WEST); c.add(fl[4], BorderLayout.CENTER); } public static void main(String[] args) { FrameMitBorderLayout fenster = new FrameMitBorderLayout(); fenster.setTitle("Frame mit Border-Layout"); fenster.setSize(300, 150); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitFlowLayout extends JFrame { Container c; // Container dieses Frames // Feld fuer Labels, die im Frame erscheinen sollen FarbigesLabel fl[] = new FarbigesLabel[4]; public FrameMitFlowLayout() { // Konstruktor c = getContentPane(); // Container bestimmen c.setLayout(new FlowLayout()); // Layout setzen // Erzeuge die Labelobjekte mit Uebergabe der Labeltexte for (int i = 0; i < 4; i++) { int rgbFg = 255 - i * 80; // Farbwert fuer Vordergrund int rgbBg = i * 80; // Farbwert fuer Hintergrund fl[i] = new FarbigesLabel("Nummer " + (i + 1), new Color(rgbFg, rgbFg, rgbFg), new Color(rgbBg, rgbBg, rgbBg)); fl[i].setFont(new Font("Serif", Font.ITALIC, 28)); } // Fuege die Labels dem Frame hinzu for (int i = 0; i < 4; i++) { c.add(fl[i]); } } public static void main(String[] args) { FrameMitFlowLayout fenster = new FrameMitFlowLayout(); fenster.setTitle("Frame mit Flow-Layout"); fenster.setSize(300, 150); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitMonospacedText extends JFrame { Container c; // Container dieses Frames JLabel textLabel; // Label das im Frame erscheinen soll public FrameMitMonospacedText() { c = getContentPane(); c.setLayout(new FlowLayout()); // Konstruktor // Container bestimmen // Layout setzen // Erzeuge das Labelobjekt mit Uebergabe des Labeltextes textLabel = new JLabel("Monospaced Text"); // Setze die Schriftart fuer die Labelschriftart textLabel.setFont(new Font("Monospaced", Font.BOLD + Font.ITALIC, 30)); // Fuege das Label dem Frame hinzu c.add(textLabel); } public static void main(String[] args) { FrameMitMonospacedText fenster = new FrameMitMonospacedText(); fenster.setTitle("Frame mit monospaced Text"); fenster.setSize(300, 80); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FrameMitSchwarzemLabel extends JFrame { Container c; // Container dieses Frames FarbigesLabel schwarzesLabel; // Label, das im Frame erscheinen soll public FrameMitSchwarzemLabel() { c = getContentPane(); c.setLayout(new FlowLayout()); // Konstruktor // Container bestimmen // Layout setzen // Erzeuge das Labelobjekt mit Uebergabe des Labeltextes schwarzesLabel = new FarbigesLabel("schwarzes Label", new Color(255, 255, 255), Color.BLACK); // Fuege das Label dem Frame hinzu c.add(schwarzesLabel); } public static void main(String[] args) { FrameMitSchwarzemLabel fenster = new FrameMitSchwarzemLabel(); fenster.setTitle("Frame mit schwarzem Label"); fenster.setSize(300, 60); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class FarbigesLabel extends JLabel { public FarbigesLabel(String text, Color fG, Color bG) { // Konstruktor // Uebergabe des Labeltextes an den Super-Konstruktor super(text); // Setze den Hintergrund des Labels auf undurchsichtig setOpaque(true); // Setze die Farbe der Beschriftung des Labels setForeground(fG); // Setze die Hintergrundfarbe des Labels setBackground(bG); } } class FrameMitTextUndToolTip extends JFrame { Container c; // Container dieses Frames JLabel beschriftung; // Label das im Frame erscheinen soll public FrameMitTextUndToolTip() { // Konstruktor // Bestimme die Referenz auf den eigenen Container c = getContentPane(); // Setze das Layout c.setLayout(new FlowLayout()); // Erzeuge das Labelobjekt mit Uebergabe des Labeltextes beschriftung = new JLabel("Label-Text im Frame"); // Fuege das Label dem Frame hinzu c.add(beschriftung); // Fuege dem Label einen Tooltip hinzu beschriftung.setToolTipText("Des isch nur en Tescht!"); } public static void main(String[] args) { FrameMitTextUndToolTip fenster = new FrameMitTextUndToolTip(); fenster.setTitle("Frame mit Text im Label mit Tooltip"); fenster.setSize(400, 150); fenster.setVisible(true); fenster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
package net.spy.db; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.StringTokenizer; import net.spy.SpyObject; import net.spy.util.SpyConfig; /** * SpyDB is an abstraction of both net.spy.pool and java.sql. */ public class SpyDB extends SpyObject { // The actual database connection from the PooledObject. private Connection conn=null; // Our configuration. private SpyConfig conf = null; // Is this thing closed? private boolean isClosed=false; // The connection source. private ConnectionSource source=null; // Exceptions that occur during initialization. private DBInitException initializationException=null; /** * Initialization type for SpyDB initialized from a config. */ protected static final int INIT_FROM_CONFIG=1; /** * Initialization type for SpyDB initialized from a Connection. */ protected static final int INIT_FROM_CONN=2; private int initType=0; /** * Create a SpyDB object based on the description found in the passed * in SpyConfig object. * * <p> * * The configuration may vary greatly depending on the connector. The * only configuration option for SpyDB itself is * <i>dbConnectionSource</i> which specifies the name of the class that * implements {@link ConnectionSource} that will be providing * connections for this SpyDB instance. The default is * {@link net.spy.db.ObjectPoolConnectionSource net.spy.db.ObjectPoolConnectionSource}. * You will also need to provide any additional parameters that are * required by the ConnectionSource in this config. * * @param c SpyConfig object describing how to connect. */ public SpyDB(SpyConfig c) { super(); this.conf=c; initType=INIT_FROM_CONFIG; source=ConnectionSourceFactory.getInstance().getConnectionSource(c); init(); } /** * Get a SpyDB object wrapping the given connection. * * @param c the connection to wrap. */ public SpyDB(Connection c) { super(); this.conn=c; initType=INIT_FROM_CONN; init(); } /** * Get the type of initialization that created this object. * * @return either INIT_FROM_CONFIG or INIT_FROM_CONN */ public int getInitType() { return(initType); } /** * Execute a query and return a resultset, will establish a database * connection if necessary. * * @param query SQL query to execute. * * @exception SQLException an exception is thrown if the connection fails, * or the SQL query fails. */ public ResultSet executeQuery(String query) throws SQLException { Connection c=getConn(); Statement st = c.createStatement(); ResultSet rs = st.executeQuery(query); return(rs); } /** * Execute a query that doesn't return a ResultSet, such as an update, * delete, or insert. * * @param query SQL query to execute. * * @exception SQLException an exception is thrown if the connection fails, * or the SQL query fails. */ public int executeUpdate(String query) throws SQLException { int rv=0; Connection c=getConn(); Statement st = c.createStatement(); rv=st.executeUpdate(query); return(rv); } /** * Prepare a statement. * * @param query SQL query to prepare. * * @exception SQLException thrown if something bad happens. */ public PreparedStatement prepareStatement(String query) throws SQLException { Connection c=getConn(); PreparedStatement pst = c.prepareStatement(query); return(pst); } /** * Prepare a callable statement. * * @param query SQL query to prepare for call. * * @exception SQLException thrown if something bad happens. */ public CallableStatement prepareCall(String query) throws SQLException { Connection c=getConn(); CallableStatement cst = c.prepareCall(query); return(cst); } /** * Get a connection out of the pool. A given SpyDB object can only * maintain a single database connection, so if multiple connections * from the pool are needed, multiple SpyDB objects will be required. * * @exception SQLException An exception may be thrown if a database * connection cannot be obtained. */ public Connection getConn() throws SQLException { if(conn==null) { getDBConn(); } return(conn); } /** * Free an established database connection. The connection is whatever * connection has already been instablished by this instance of the * object. If a connection has not been established, this does * nothing. */ public void freeDBConn() { // Don't touch it unless it came from a ConnectionSource if(source!=null) { // If there's a source, this came from something that will want // to hear that we're done with it. if(conn!=null) { source.returnConnection(conn); conn=null; } } isClosed=true; } /** * Free an established database connection - alias to freeDBConn() */ public void close() { freeDBConn(); } /** * Initialize SpyDB. This allows any subclasses to perform further * initialization. */ protected void init() { // Subclass initialization } // Actually dig up a DB connection private void getDBConn() throws SQLException { // Different behavior whether we're using a pool or not if(initializationException!=null) { throw initializationException; } // Get the connection from the source. conn=source.getConnection(conf); } /** * Make a string safe for usage in a SQL query, quoting apostrophies, * etc... * * @param in the string that needs to be quoted * * @return a new, quoted string */ public static String dbquoteStr(String in) { // Quick...handle null if(in == null) { return(null); } String sout = null; if(in.indexOf('\'') < 0) { sout = in; } else { StringBuffer sb=new StringBuffer(in.length()); StringTokenizer st = new StringTokenizer(in, "\'", true); while(st.hasMoreTokens()) { String part = st.nextToken(); sb.append(part); // If this is a quote, add another one if(part.equals("'")) { sb.append('\''); } } sout=sb.toString(); } return(sout); } /** * Has close() been called? */ public boolean isClosed() { return(isClosed); } /** * Get the source of connections. * * @return a ConnectionSource instance, or null if this SpyDB instance * was created from a config */ public ConnectionSource getSource() { return(source); } /** * Get the configuration from which this SpyDB was instatiated. * * @return the config, or null if the SpyDB was created from a * connection */ protected SpyConfig getConfig() { return(conf); } }
package javapresso; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; public class JavaPresso { public static final String JAVA_PRESSO_VERSION = "1.0.1"; /** * @param args the command line arguments */ public static void main(String[] args) { JavaPresso app = new JavaPresso(); app.run(args); } private void run(String[] args) { info(); try { if (args.length < 2) { help(); } else { if (args.length < 3) { System.out.println("Info: you omitted the version argument, using 'undefined' instead"); packClasses(args[0], args[1], "undefined"); } else { packClasses(args[0], args[1], args[2]); } } } catch (Exception ex) { System.out.printf(ex.getLocalizedMessage()); } finally { } } /** * Prints help. */ private void help() { System.out.println("Usage: java -jar JavaPresso.jar input_folder_path namespace_name compressed_file_version"); System.out.println("Example: 'java -jar JavaPresso.jar C:\\JCMathLib\\src\\opencrypto\\jcmathlib\\ jcmathlib 0.4.2'"); } /** * Prints info. */ private void info() { System.out.println("\n System.out.println("JavaPresso " + JAVA_PRESSO_VERSION + " - compress multiple source files of library into a single include."); System.out.println("Petr Svenda 2016-2021 (https://github.com/petrs/)."); help(); System.out.println("Please check if you use the latest version at\n https://github.com/petrs/JavaPresso/releases/latest."); System.out.println(" } class JavaFileInfo { String packageLine; ArrayList<String> importLines; ArrayList<String> fileContent; JavaFileInfo() { importLines = new ArrayList<>(); fileContent = new ArrayList<>(); } } private void packClasses(String basePath, String namespaceName, String version) throws FileNotFoundException, IOException { String filesPath = basePath + File.separator; File dir = new File(filesPath); String[] filesArray = dir.list(); System.out.println("\r\n"); System.out.println(String.format("input folder = '%s'", filesPath)); System.out.println(String.format("namespace name = '%s'", namespaceName)); System.out.println(String.format("version = '%s'", version)); System.out.println("\r\n"); if ((filesArray != null) && (dir.isDirectory() == true)) { ArrayList<JavaFileInfo> filesContent = new ArrayList<>(filesArray.length); for (int i = 0; i < filesArray.length; i++) { filesContent.add(i, loadJavaFile(filesPath + filesArray[i])); } // Header String fileName = String.format("%s\\%s.java", basePath, namespaceName); FileOutputStream file = new FileOutputStream(fileName); String header = " header += "// TODO: Change 'your_package' to your real package name as necessary\r\n"; header += String.format("// TODO: Add 'import your_package.%s.*;' to access all classes as usual\r\n\r\n", namespaceName); header += "package your_package;\r\n"; header += "\r\n"; // Add import lines without duplicities Set set = new TreeSet(String.CASE_INSENSITIVE_ORDER); for (JavaFileInfo fileInfo : filesContent) { set.addAll(fileInfo.importLines); } ArrayList<String> importLines = new ArrayList(set); for (String importLine : importLines) { header += importLine; } header += String.format("\r\npublic class %s {\r\n", namespaceName); header += String.format(" public static String version = \"%s\"; \r\n\r\n", version); file.write(header.getBytes()); file.flush(); // Separate classes String indent = " "; for (JavaFileInfo fileInfo : filesContent) { for (String line : fileInfo.fileContent) { file.write(indent.getBytes()); file.write(line.getBytes()); } file.flush(); } // Footer String footer = "}\r\n"; file.write(footer.getBytes()); file.flush(); file.close(); System.out.println(String.format("Successfully compressed into '%s'", fileName)); } else { System.out.println("directory '" + filesPath + "' is empty"); } } private JavaFileInfo loadJavaFile(String filePath) { JavaFileInfo fileInfo = new JavaFileInfo(); try { //create BufferedReader to read csv file BufferedReader br = new BufferedReader(new FileReader(filePath)); String strLine; //read file line by line while ((strLine = br.readLine()) != null) { strLine += "\r\n"; String trimedStrLine = strLine.trim(); if (trimedStrLine.startsWith("package ")) { fileInfo.packageLine = strLine; } else if (trimedStrLine.startsWith("import ")) { fileInfo.importLines.add(strLine); } else if (trimedStrLine.startsWith("public class ")) { fileInfo.fileContent.add(strLine.replaceAll("public class ", "public static class ")); } else { fileInfo.fileContent.add(strLine); } } } catch (Exception e) { System.out.println("Exception while reading csv file: " + e); } return fileInfo; } }
package de.independit.scheduler.jobserver; import java.io.*; import java.util.*; import de.independit.scheduler.server.repository.SDMSSubmittedEntity; public class Environment extends HashMap { public static final String __version = "@(#) $Id: Environment.java,v 2.3.14.1 2013/03/14 10:24:06 ronald Exp $"; public static final Environment systemEnvironment = new Environment(); private Environment() { super(System.getenv()); } public Environment (final Vector settings) { super(); for (int i = 0; i < settings.size(); i += 2) put (settings.get (i), settings.get (i + 1)); } public Environment (final HashMap settings) { super (settings); } public boolean containsKey (Object key) { if(Config.isWindows()) return super.containsKey (((String) key).toUpperCase()); else return super.containsKey (key); } public Object get (Object key) { if(Config.isWindows()) return super.get (((String) key).toUpperCase()); else return super.get (key); } public Object put (Object key, Object value) { if(Config.isWindows()) return super.put (((String) key).toUpperCase(), value); else return super.put (key, value); } public void putAll (Map m) { final Vector keys = new Vector (m.keySet()); final int size = keys.size(); for (int i = 0; i < size; ++i) { final Object key = keys.get (i); put (key, m.get (key)); } } public Object remove (Object key) { if(Config.isWindows()) return super.remove (((String) key).toUpperCase()); else return super.remove (key); } public final Environment merge (final Environment env, final RepoIface ri, final Config cfg) { final Environment result = new Environment (this); final HashMap mapping = (HashMap) cfg.get (Config.ENV_MAPPING); if ((env != null) && (mapping != null) && (! mapping.isEmpty())) { final Vector keyList = new Vector (mapping.keySet()); final int size = keyList.size(); for (int i = 0; i < size; ++i) { final String exp = (String) keyList.get (i); final String key = (String) mapping.get (exp); String val = null; if (key.equals (SDMSSubmittedEntity.S_SDMSHOST)) val = ri.getHost(); else if (key.equals (SDMSSubmittedEntity.S_SDMSPORT)) val = String.valueOf (ri.getPort()); else val = (String) env.get (key); result.put (exp, val != null ? val : ""); } } return result; } public final String[] toArray() { final int size = size(); final String[] result = new String [size]; final Vector keyList = new Vector (keySet()); for (int i = 0; i < size; ++i) { final String key = (String) keyList.get (i); final String val = (String) get (key); result [i] = key + '=' + val; } return result; } }
package org.jetbrains.idea.devkit.run; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.*; import com.intellij.execution.filters.TextConsoleBuidlerFactory; import com.intellij.execution.runners.JavaProgramRunner; import com.intellij.execution.runners.RunnerInfo; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdk; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.*; import org.jdom.Element; import org.jetbrains.idea.devkit.module.PluginModuleType; import org.jetbrains.idea.devkit.projectRoots.IdeaJdk; import org.jetbrains.idea.devkit.projectRoots.Sandbox; import java.io.File; import java.util.ArrayList; import java.util.List; public class PluginRunConfiguration extends RunConfigurationBase { private Module myModule; private String myModuleName; public String VM_PARAMETERS; public PluginRunConfiguration(final Project project, final ConfigurationFactory factory, final String name) { super(project, factory, name); } public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { return new PluginRunConfigurationEditor(this); } public JDOMExternalizable createRunnerSettings(ConfigurationInfoProvider provider) { return null; } public SettingsEditor<JDOMExternalizable> getRunnerSettingsEditor(JavaProgramRunner runner) { return null; } public RunProfileState getState(DataContext context, RunnerInfo runnerInfo, RunnerSettings runnerSettings, ConfigurationPerRunnerSettings configurationSettings) throws ExecutionException { if (getModule() == null){ throw new ExecutionException("No module specified for configuration"); } final ModuleRootManager rootManager = ModuleRootManager.getInstance(getModule()); final ProjectJdk jdk = rootManager.getJdk(); if (jdk == null) { throw CantRunException.noJdkForModule(getModule()); } if (!(jdk.getSdkType() instanceof IdeaJdk)) { throw new ExecutionException("Wrong jdk type for plugin module"); } final String sandboxHome = ((Sandbox)jdk.getSdkAdditionalData()).getSandboxHome(); IdeaLicenseHelper.copyIDEALicencse(sandboxHome, jdk); final JavaCommandLineState state = new JavaCommandLineState(runnerSettings, configurationSettings) { protected JavaParameters createJavaParameters() throws ExecutionException { final JavaParameters params = new JavaParameters(); ParametersList vm = params.getVMParametersList(); final String[] userVMOptions = VM_PARAMETERS != null ? VM_PARAMETERS.split(" ") : null; for (int i = 0; userVMOptions != null && i < userVMOptions.length; i++) { if (userVMOptions[i] != null && userVMOptions[i].length() > 0){ vm.add(userVMOptions[i]); } } String libPath = jdk.getHomePath() + File.separator + "lib"; vm.add("-Xbootclasspath/p:" + libPath + File.separator + "boot.jar"); vm.defineProperty("idea.config.path", sandboxHome + File.separator + "config"); vm.defineProperty("idea.system.path", sandboxHome + File.separator + "system"); vm.defineProperty("idea.plugins.path", sandboxHome + File.separator + "plugins"); if (SystemInfo.isMac) { vm.defineProperty("idea.smooth.progress", "false"); vm.defineProperty("apple.laf.useScreenMenuBar", "true"); } params.setWorkingDirectory(jdk.getHomePath() + File.separator + "bin" + File.separator); params.setJdk(jdk); params.getClassPath().addFirst(libPath + File.separator + "log4j.jar"); params.getClassPath().addFirst(libPath + File.separator + "openapi.jar"); params.getClassPath().addFirst(libPath + File.separator + "extensions.jar"); params.getClassPath().addFirst(libPath + File.separator + "idea.jar"); params.setMainClass("com.intellij.idea.Main"); return params; } }; state.setConsoleBuilder(TextConsoleBuidlerFactory.getInstance().createBuilder(getProject())); state.setModulesToCompile(getModules()); //todo return state; } public void checkConfiguration() throws RuntimeConfigurationException { if (getModule() == null) { throw new RuntimeConfigurationException("Plugin module not specified."); } String moduleName = ApplicationManager.getApplication().runReadAction(new Computable<String>() { public String compute() { return getModule().getName(); } }); final ModuleRootManager rootManager = ModuleRootManager.getInstance(getModule()); final ProjectJdk jdk = rootManager.getJdk(); if (jdk == null) { throw new RuntimeConfigurationException("No jdk specified for plugin module \'" + moduleName + "\'"); } if (!(jdk.getSdkType() instanceof IdeaJdk)) { throw new RuntimeConfigurationException("Wrong jdk type for plugin module \'" + moduleName + "\'"); } } public Module[] getModules() { List<Module> modules = new ArrayList<Module>(); Module[] allModules = ModuleManager.getInstance(getProject()).getModules(); for (int i = 0; i < allModules.length; i++) { Module module = allModules[i]; if (module.getModuleType() == PluginModuleType.getInstance()) { modules.add(module); } } return modules.toArray(new Module[modules.size()]); } public void readExternal(Element element) throws InvalidDataException { Element module = element.getChild("module"); if (module != null) { myModuleName = module.getAttributeValue("name"); } DefaultJDOMExternalizer.readExternal(this, element); } public void writeExternal(Element element) throws WriteExternalException { Element moduleElement = new Element("module"); moduleElement.setAttribute("name", ApplicationManager.getApplication().runReadAction(new Computable<String>() { public String compute() { return getModule() != null ? getModule().getName() : ""; } })); element.addContent(moduleElement); DefaultJDOMExternalizer.writeExternal(this, element); } public Module getModule() { if (myModule == null && myModuleName != null){ myModule = ModuleManager.getInstance(getProject()).findModuleByName(myModuleName); } return myModule; } public void setModule(Module module) { myModule = module; } }
package japicmp.output.xml; import com.google.common.base.Joiner; import japicmp.config.Options; import japicmp.config.PackageFilter; import japicmp.exception.JApiCmpException; import japicmp.exception.JApiCmpException.Reason; import japicmp.model.JApiClass; import japicmp.output.OutputFilter; import japicmp.output.extapi.jpa.JpaAnalyzer; import japicmp.output.extapi.jpa.model.JpaTable; import japicmp.output.xml.model.JApiCmpXmlRoot; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.SchemaOutputResolver; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.util.List; import java.util.logging.Logger; public class XmlOutputGenerator { private static final String XSD_FILENAME = "japicmp.xsd"; private static final String XML_SCHEMA = XSD_FILENAME; private static final Logger LOGGER = Logger.getLogger(XmlOutputGenerator.class.getName()); public void generate(String oldArchivePath, String newArchivePath, List<JApiClass> jApiClasses, Options options) { JApiCmpXmlRoot jApiCmpXmlRoot = createRootElement(oldArchivePath, newArchivePath, jApiClasses, options); //analyzeJpaAnnotations(jApiCmpXmlRoot, jApiClasses); filterClasses(jApiClasses, options); createXmlDocumentAndSchema(options, jApiCmpXmlRoot); } private void analyzeJpaAnnotations(JApiCmpXmlRoot jApiCmpXmlRoot, List<JApiClass> jApiClasses) { JpaAnalyzer jpaAnalyzer = new JpaAnalyzer(); List<JpaTable> jpaEntities = jpaAnalyzer.analyze(jApiClasses); //jApiCmpXmlRoot.setJpaTables(jpaEntities); } private void createXmlDocumentAndSchema(Options options, JApiCmpXmlRoot jApiCmpXmlRoot) { try { JAXBContext jaxbContext = JAXBContext.newInstance(JApiCmpXmlRoot.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, XML_SCHEMA); ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshal(jApiCmpXmlRoot, baos); if (options.getXmlOutputFile().isPresent()) { final File xmlFile = new File(options.getXmlOutputFile().get()); FileOutputStream fos = new FileOutputStream(xmlFile); baos.writeTo(fos); SchemaOutputResolver outputResolver = new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { File schemaFile = xmlFile.getParentFile(); if (schemaFile == null) { LOGGER.warning(String.format("File '%s' has no parent file. Using instead: '%s'.", xmlFile.getAbsolutePath(), XSD_FILENAME)); schemaFile = new File(XSD_FILENAME); } else { schemaFile = new File(schemaFile + File.separator + XSD_FILENAME); } StreamResult result = new StreamResult(schemaFile); result.setSystemId(schemaFile.getAbsolutePath()); return result; } }; jaxbContext.generateSchema(outputResolver); } if (options.getHtmlOutputFile().isPresent()) { TransformerFactory transformerFactory = TransformerFactory.newInstance(); InputStream inputStream = XmlOutputGenerator.class.getResourceAsStream("/html.xslt"); if(inputStream == null) { throw new JApiCmpException(Reason.XsltError, "Failed to load XSLT."); } Transformer transformer = transformerFactory.newTransformer(new StreamSource(inputStream)); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); transformer.transform(new StreamSource(bais), new StreamResult(new FileOutputStream(options.getHtmlOutputFile().get()))); } } catch (JAXBException e) { throw new JApiCmpException(Reason.JaxbException, String.format("Marshalling of XML document failed: %s", e.getMessage()), e); } catch (IOException e) { throw new JApiCmpException(Reason.IoException, String.format("Marshalling of XML document failed: %s", e.getMessage()), e); } catch (TransformerConfigurationException e) { throw new JApiCmpException(Reason.XsltError, String.format("Configuration of XSLT transformer failed: %s", e.getMessage()), e); } catch (TransformerException e) { throw new JApiCmpException(Reason.XsltError, String.format("XSLT transformation failed: %s", e.getMessage()), e); } } private void filterClasses(List<JApiClass> jApiClasses, Options options) { OutputFilter outputFilter = new OutputFilter(options); outputFilter.filter(jApiClasses); } private JApiCmpXmlRoot createRootElement(String oldArchivePath, String newArchivePath, List<JApiClass> jApiClasses, Options options) { JApiCmpXmlRoot jApiCmpXmlRoot = new JApiCmpXmlRoot(); jApiCmpXmlRoot.setOldJar(oldArchivePath); jApiCmpXmlRoot.setNewJar(newArchivePath); jApiCmpXmlRoot.setClasses(jApiClasses); jApiCmpXmlRoot.setAccessModifier(options.getAccessModifier().name()); jApiCmpXmlRoot.setOnlyModifications(options.isOutputOnlyModifications()); jApiCmpXmlRoot.setOnlyBinaryIncompatibleModifications(options.isOutputOnlyBinaryIncompatibleModifications()); jApiCmpXmlRoot.setPackagesInclude(packageListAsString(options.getPackagesInclude(), true)); jApiCmpXmlRoot.setPackagesExclude(packageListAsString(options.getPackagesExclude(), false)); return jApiCmpXmlRoot; } private String packageListAsString(List<PackageFilter> packagesInclude, boolean include) { String join = Joiner.on(",").skipNulls().join(packagesInclude); if (join.length() == 0) { if (include) { join = "all"; } else { join = "n.a."; } } return join; } }
package org.jbpm.test; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.sql.DataSource; import org.drools.core.audit.WorkingMemoryInMemoryLogger; import org.drools.core.audit.event.LogEvent; import org.drools.core.audit.event.RuleFlowNodeLogEvent; import org.jbpm.process.audit.AuditLogService; import org.jbpm.process.audit.JPAAuditLogService; import org.jbpm.process.audit.NodeInstanceLog; import org.jbpm.process.instance.event.DefaultSignalManagerFactory; import org.jbpm.process.instance.impl.DefaultProcessInstanceManagerFactory; import org.jbpm.runtime.manager.impl.RuntimeEnvironmentBuilder; import org.jbpm.services.task.identity.JBossUserGroupCallbackImpl; import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl; import org.junit.After; import org.junit.Before; import org.kie.api.definition.process.Node; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.manager.Context; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.api.runtime.process.NodeInstance; import org.kie.api.runtime.process.NodeInstanceContainer; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.runtime.process.WorkItem; import org.kie.api.runtime.process.WorkItemHandler; import org.kie.api.runtime.process.WorkItemManager; import org.kie.api.runtime.process.WorkflowProcessInstance; import org.kie.internal.io.ResourceFactory; import org.kie.internal.runtime.StatefulKnowledgeSession; import org.kie.internal.runtime.manager.RuntimeEnvironment; import org.kie.internal.runtime.manager.RuntimeManagerFactory; import org.kie.internal.runtime.manager.context.EmptyContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bitronix.tm.resource.jdbc.PoolingDataSource; /** * Base test case class that shall be used for jBPM related tests. It provides four sections: * <ul> * <li>JUnit life cycle methods</li> * <li>Knowledge Base and KnowledgeSession management methods</li> * <li>Assertions</li> * <li>Helper methods</li> * </ul> * <b>JUnit life cycle methods</b>:<br/> * * setUp: executed @Before and configures data source and <code>EntityManagerFactory</code>, cleans up Singleton's session id<br/> * * tearDown: executed @After and clears out history, closes <code>EntityManagerFactory</code> and data source, disposes <code>RuntimeEngine</code>'s and <code>RuntimeManager</code><br/> * <br/> * <b>KnowledgeBase and KnowledgeSession management methods</b> * * createRuntimeManager creates <code>RuntimeManager</code> for gives set of assets and selected strategy * <br/> * * disposeRuntimeManager disposes <code>RuntimeManager</code> currently active in the scope of test * <br/> * * getRuntimeEngine creates new <code>RuntimeEngine</code> for given context<br/> * <br/> * <b>Assertions</b><br/> * Set of useful methods to assert process instance at various stages. * <br/> * <b>Helper methods</b><br/> * * getDs - returns currently configured data source<br/> * * getEmf - returns currently configured <code>EntityManagerFactory</code><br/> * * getTestWorkItemHandler - returns test work item handler that might be registered in addition to what is registered by default<br/> * * clearHistory - clears history log<br/> * * setupPoolingDataSource - sets up data source<br/> */ public abstract class JbpmJUnitBaseTestCase extends AbstractBaseTest { /** * Currently supported RuntimeEngine strategies */ public enum Strategy { SINGLETON, REQUEST, PROCESS_INSTANCE; } private static final Logger logger = LoggerFactory.getLogger(JbpmJUnitBaseTestCase.class); private boolean setupDataSource = false; private boolean sessionPersistence = false; private String persistenceUnitName; private EntityManagerFactory emf; private PoolingDataSource ds; private TestWorkItemHandler workItemHandler = new TestWorkItemHandler(); private RuntimeManagerFactory managerFactory = RuntimeManagerFactory.Factory.get(); private RuntimeManager manager; private AuditLogService logService; private WorkingMemoryInMemoryLogger inMemoryLogger; private List<RuntimeEngine> activeEngines = new ArrayList<RuntimeEngine>(); /** * The most simple test case configuration: * <ul> * <li>does NOT initialize data source</li> * <li>does NOT configure session persistence</li> * </ul> * This is usually used for in memory process management, without human task interaction. */ public JbpmJUnitBaseTestCase() { this(false, false, "org.jbpm.persistence.jpa"); } /** * Allows to explicitly configure persistence and data source. This is the most common way of * bootstrapping test cases for jBPM.<br/> * Use following configuration to execute in memory process management with human tasks persistence <br/> * <code> * super(true, false); * </code> * <br/> * Use following configuration to execute in persistent process management with human tasks persistence <br/> * <code> * super(true, true); * </code> * <br/> * This will use default persistence unit name <code>org.jbpm.persistence.jpa</code> * @param setupDataSource - true to configure data source under JNDI name: jdbc/jbpm-ds * @param sessionPersistence - configures RuntimeEngine to be with JPA persistence enabled */ public JbpmJUnitBaseTestCase(boolean setupDataSource, boolean sessionPersistence) { this(setupDataSource, sessionPersistence, "org.jbpm.persistence.jpa"); } /** * Same as {@link #JbpmJUnitBaseTestCase(boolean, boolean)} but allows to use another persistence unit name. * @param setupDataSource - true to configure data source under JNDI name: jdbc/jbpm-ds * @param sessionPersistence - configures RuntimeEngine to be with JPA persistence enabled * @param persistenceUnitName - custom persistence unit name */ public JbpmJUnitBaseTestCase(boolean setupDataSource, boolean sessionPersistence, String persistenceUnitName) { this.setupDataSource = setupDataSource; this.sessionPersistence = sessionPersistence; this.persistenceUnitName = persistenceUnitName; if (!this.setupDataSource && this.sessionPersistence) { throw new IllegalArgumentException("Unsupported configuration, cannot enable sessionPersistence when setupDataSource is disabled"); } logger.info("Configuring entire test case to have data source enabled {} and session persistence enabled {} with persistence unit name {}", this.setupDataSource, this.sessionPersistence, this.persistenceUnitName); } @Before public void setUp() throws Exception { if (setupDataSource) { ds = setupPoolingDataSource(); logger.debug("Data source configured with unique id {}", ds.getUniqueName()); emf = Persistence.createEntityManagerFactory(persistenceUnitName); } cleanupSingletonSessionId(); } @After public void tearDown() throws Exception { clearHistory(); if (setupDataSource) { if (emf != null) { emf.close(); emf = null; } if (ds != null) { ds.close(); ds = null; } } if (!activeEngines.isEmpty()) { for (RuntimeEngine engine : activeEngines) { manager.disposeRuntimeEngine(engine); } } if (manager != null) { manager.close(); manager = null; } } /** * Creates default configuration of <code>RuntimeManager</code> with SINGLETON strategy and all * <code>processes</code> being added to knowledge base. * <br/> * There should be only one <code>RuntimeManager</code> created during single test. * @param process - processes that shall be added to knowledge base * @return new instance of RuntimeManager */ protected RuntimeManager createRuntimeManager(String... process) { return createRuntimeManager(Strategy.SINGLETON, process); } /** * Creates default configuration of <code>RuntimeManager</code> with given <code>strategy</code> and all * <code>processes</code> being added to knowledge base. * <br/> * There should be only one <code>RuntimeManager</code> created during single test. * @param strategy - selected strategy of those that are supported * @param process - processes that shall be added to knowledge base * @return new instance of RuntimeManager */ protected RuntimeManager createRuntimeManager(Strategy strategy, String... process) { Map<String, ResourceType> resources = new HashMap<String, ResourceType>(); for (String p : process) { resources.put(p, ResourceType.BPMN2); } return createRuntimeManager(strategy, resources); } /** * Creates default configuration of <code>RuntimeManager</code> with SINGLETON strategy and all * <code>resources</code> being added to knowledge base. * <br/> * There should be only one <code>RuntimeManager</code> created during single test. * @param resources - resources (processes, rules, etc) that shall be added to knowledge base * @return new instance of RuntimeManager */ protected RuntimeManager createRuntimeManager(Map<String, ResourceType> resources) { return createRuntimeManager(Strategy.SINGLETON, resources); } /** * Creates default configuration of <code>RuntimeManager</code> with given <code>strategy</code> and all * <code>resources</code> being added to knowledge base. * <br/> * There should be only one <code>RuntimeManager</code> created during single test. * @param strategy - selected strategy of those that are supported * @param resources - resources that shall be added to knowledge base * @return new instance of RuntimeManager */ protected RuntimeManager createRuntimeManager(Strategy strategy, Map<String, ResourceType> resources) { if (manager != null) { throw new IllegalStateException("There is already one RuntimeManager active"); } RuntimeEnvironmentBuilder builder = null; if (!setupDataSource){ builder = RuntimeEnvironmentBuilder.getEmpty() .addConfiguration("drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName()) .addConfiguration("drools.processInstanceManagerFactory", DefaultProcessInstanceManagerFactory.class.getName()); } else if (sessionPersistence) { builder = RuntimeEnvironmentBuilder.getDefault() .entityManagerFactory(emf); } else { builder = RuntimeEnvironmentBuilder.getDefaultInMemory(); } builder.userGroupCallback(new JBossUserGroupCallbackImpl("classpath:/usergroups.properties")); for (Map.Entry<String, ResourceType> entry : resources.entrySet()) { builder.addAsset(ResourceFactory.newClassPathResource(entry.getKey()), entry.getValue()); } switch (strategy) { case SINGLETON: manager = managerFactory.newSingletonRuntimeManager(builder.get()); break; case REQUEST: manager = managerFactory.newPerRequestRuntimeManager(builder.get()); break; case PROCESS_INSTANCE: manager = managerFactory.newPerProcessInstanceRuntimeManager(builder.get()); break; default: manager = managerFactory.newSingletonRuntimeManager(builder.get()); break; } return manager; } /** * The lowest level of creation of <code>RuntimeManager</code> that expects to get <code>RuntimeEnvironment</code> * to be given as argument. It does not assume any particular configuration as it's considered manual creation * that allows to configure every single piece of <code>RuntimeManager</code>. <br/> * Use this only when you know what you do! * @param strategy - selected strategy of those that are supported * @param resources - resources that shall be added to knowledge base * @param environment - runtime environment used for <code>RuntimeManager</code> creation * @return new instance of RuntimeManager */ protected RuntimeManager createRuntimeManager(Strategy strategy, Map<String, ResourceType> resources, RuntimeEnvironment environment) { if (manager != null) { throw new IllegalStateException("There is already one RuntimeManager active"); } switch (strategy) { case SINGLETON: manager = managerFactory.newSingletonRuntimeManager(environment); break; case REQUEST: manager = managerFactory.newPerRequestRuntimeManager(environment); break; case PROCESS_INSTANCE: manager = managerFactory.newPerProcessInstanceRuntimeManager(environment); break; default: manager = managerFactory.newSingletonRuntimeManager(environment); break; } return manager; } /** * Disposes currently active (in scope of a test) <code>RuntimeManager</code> together with all * active <code>RuntimeEngine</code>'s that were created (in scope of a test). Usual use case is * to simulate system shutdown. */ protected void disposeRuntimeManager() { if (!activeEngines.isEmpty()) { for (RuntimeEngine engine : activeEngines) { manager.disposeRuntimeEngine(engine); } activeEngines.clear(); } if (manager != null) { manager.close(); manager = null; } } /** * Returns new <code>RuntimeEngine</code> built from the manager of this test case. * It uses <code>EmptyContext</code> that is suitable for following strategies: * <ul> * <li>Singleton</li> * <li>Request</li> * </ul> * @see #getRuntimeEngine(Context) * @return new RuntimeEngine instance */ protected RuntimeEngine getRuntimeEngine() { return getRuntimeEngine(EmptyContext.get()); } /** * Returns new <code>RuntimeEngine</code> built from the manager of this test case. Common use case is to maintain * same session for process instance and thus <code>ProcessInstanceIdContext</code> shall be used. * @param context - instance of the context that shall be used to create <code>RuntimeManager</code> * @return new RuntimeEngine instance */ protected RuntimeEngine getRuntimeEngine(Context<?> context) { if (manager == null) { throw new IllegalStateException("RuntimeManager is not initialized, did you forgot to create it?"); } RuntimeEngine runtimeEngine = manager.getRuntimeEngine(context); activeEngines.add(runtimeEngine); if (sessionPersistence) { logService = new JPAAuditLogService(runtimeEngine.getKieSession().getEnvironment()); } else { inMemoryLogger = new WorkingMemoryInMemoryLogger((StatefulKnowledgeSession) runtimeEngine.getKieSession()); } return runtimeEngine; } /** * Retrieves value of the variable given by <code>name</code> from process instance given by <code>processInstanceId</code> * using given session. * @param name - name of the variable * @param processInstanceId - id of process instance * @param ksession - ksession used to retrieve the value * @return returns variable value or null if there is no such variable */ public Object getVariableValue(String name, long processInstanceId, KieSession ksession) { return ((WorkflowProcessInstance) ksession.getProcessInstance(processInstanceId)).getVariable(name); } public void assertProcessInstanceCompleted(long processInstanceId, KieSession ksession) { assertNull(ksession.getProcessInstance(processInstanceId)); } public void assertProcessInstanceAborted(long processInstanceId, KieSession ksession) { assertNull(ksession.getProcessInstance(processInstanceId)); } public void assertProcessInstanceActive(long processInstanceId, KieSession ksession) { assertNotNull(ksession.getProcessInstance(processInstanceId)); } public void assertNodeActive(long processInstanceId, KieSession ksession, String... name) { List<String> names = new ArrayList<String>(); for (String n : name) { names.add(n); } ProcessInstance processInstance = ksession.getProcessInstance(processInstanceId); if (processInstance instanceof WorkflowProcessInstance) { assertNodeActive((WorkflowProcessInstance) processInstance, names); } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Node(s) not active: " + s); } } private void assertNodeActive(NodeInstanceContainer container, List<String> names) { for (NodeInstance nodeInstance : container.getNodeInstances()) { String nodeName = nodeInstance.getNodeName(); if (names.contains(nodeName)) { names.remove(nodeName); } if (nodeInstance instanceof NodeInstanceContainer) { assertNodeActive((NodeInstanceContainer) nodeInstance, names); } } } public void assertNodeTriggered(long processInstanceId, String... nodeNames) { List<String> names = new ArrayList<String>(); for (String nodeName : nodeNames) { names.add(nodeName); } if (sessionPersistence) { List<NodeInstanceLog> logs = logService.findNodeInstances(processInstanceId); if (logs != null) { for (NodeInstanceLog l : logs) { String nodeName = l.getNodeName(); if ((l.getType() == NodeInstanceLog.TYPE_ENTER || l.getType() == NodeInstanceLog.TYPE_EXIT) && names.contains(nodeName)) { names.remove(nodeName); } } } } else { for (LogEvent event : inMemoryLogger.getLogEvents()) { if (event instanceof RuleFlowNodeLogEvent) { String nodeName = ((RuleFlowNodeLogEvent) event).getNodeName(); if (names.contains(nodeName)) { names.remove(nodeName); } } } } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Node(s) not executed: " + s); } } public void assertProcessVarExists(ProcessInstance process, String... processVarNames) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; List<String> names = new ArrayList<String>(); for (String nodeName : processVarNames) { names.add(nodeName); } for (String pvar : instance.getVariables().keySet()) { if (names.contains(pvar)) { names.remove(pvar); } } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Process Variable(s) do not exist: " + s); } } public void assertNodeExists(ProcessInstance process, String... nodeNames) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; List<String> names = new ArrayList<String>(); for (String nodeName : nodeNames) { names.add(nodeName); } for (Node node : instance.getNodeContainer().getNodes()) { if (names.contains(node.getName())) { names.remove(node.getName()); } } if (!names.isEmpty()) { String s = names.get(0); for (int i = 1; i < names.size(); i++) { s += ", " + names.get(i); } fail("Node(s) do not exist: " + s); } } public void assertNumOfIncommingConnections(ProcessInstance process, String nodeName, int num) { assertNodeExists(process, nodeName); WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; for (Node node : instance.getNodeContainer().getNodes()) { if (node.getName().equals(nodeName)) { if (node.getIncomingConnections().size() != num) { fail("Expected incomming connections: " + num + " - found " + node.getIncomingConnections().size()); } else { break; } } } } public void assertNumOfOutgoingConnections(ProcessInstance process, String nodeName, int num) { assertNodeExists(process, nodeName); WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; for (Node node : instance.getNodeContainer().getNodes()) { if (node.getName().equals(nodeName)) { if (node.getOutgoingConnections().size() != num) { fail("Expected outgoing connections: " + num + " - found " + node.getOutgoingConnections().size()); } else { break; } } } } public void assertVersionEquals(ProcessInstance process, String version) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; if (!instance.getWorkflowProcess().getVersion().equals(version)) { fail("Expected version: " + version + " - found " + instance.getWorkflowProcess().getVersion()); } } public void assertProcessNameEquals(ProcessInstance process, String name) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; if (!instance.getWorkflowProcess().getName().equals(name)) { fail("Expected name: " + name + " - found " + instance.getWorkflowProcess().getName()); } } public void assertPackageNameEquals(ProcessInstance process, String packageName) { WorkflowProcessInstanceImpl instance = (WorkflowProcessInstanceImpl) process; if (!instance.getWorkflowProcess().getPackageName().equals(packageName)) { fail("Expected package name: " + packageName + " - found " + instance.getWorkflowProcess().getPackageName()); } } protected EntityManagerFactory getEmf() { return this.emf; } protected DataSource getDs() { return this.ds; } protected PoolingDataSource setupPoolingDataSource() { PoolingDataSource pds = new PoolingDataSource(); pds.setUniqueName("jdbc/jbpm-ds"); pds.setClassName("bitronix.tm.resource.jdbc.lrc.LrcXADataSource"); pds.setMaxPoolSize(5); pds.setAllowLocalTransactions(true); pds.getDriverProperties().put("user", "sa"); pds.getDriverProperties().put("password", ""); pds.getDriverProperties().put("url", "jdbc:h2:inmemory:jbpm-db;MVCC=true"); pds.getDriverProperties().put("driverClassName", "org.h2.Driver"); pds.init(); return pds; } protected void clearHistory() { if (sessionPersistence) { logService.clear(); } else { inMemoryLogger.clear(); } } protected TestWorkItemHandler getTestWorkItemHandler() { return workItemHandler; } protected static class TestWorkItemHandler implements WorkItemHandler { private List<WorkItem> workItems = new ArrayList<WorkItem>(); public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { workItems.add(workItem); } public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { } public WorkItem getWorkItem() { if (workItems.size() == 0) { return null; } if (workItems.size() == 1) { WorkItem result = workItems.get(0); this.workItems.clear(); return result; } else { throw new IllegalArgumentException("More than one work item active"); } } public List<WorkItem> getWorkItems() { List<WorkItem> result = new ArrayList<WorkItem>(workItems); workItems.clear(); return result; } } protected static void cleanupSingletonSessionId() { File tempDir = new File(System.getProperty("java.io.tmpdir")); if (tempDir.exists()) { String[] jbpmSerFiles = tempDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith("-jbpmSessionId.ser"); } }); for (String file : jbpmSerFiles) { new File(tempDir, file).delete(); } } } }
package ru.adios.budgeter.jdbcrepo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; interface Wrappable extends AutoCloseable { Logger logger = LoggerFactory.getLogger(Wrappable.class); static void closeSilently(AutoCloseable delegate) { try { delegate.close(); } catch (Exception ignore) { logger.debug("Delegate stream close exception", ignore); } } default <ReturnType, Param> ReturnType wrap(Function<Param, ReturnType> f, Param p) { try { return f.apply(p); } finally { closeSilently(this); } } default <Param> void wrap(Param p, Consumer<Param> c) { try { c.accept(p); } finally { closeSilently(this); } } default <ReturnType> ReturnType wrap(Supplier<ReturnType> f) { try { return f.get(); } finally { closeSilently(this); } } }
package com.jme3.renderer.opengl; import com.jme3.material.RenderState; import com.jme3.material.RenderState.BlendFunc; import com.jme3.material.RenderState.BlendMode; import com.jme3.material.RenderState.StencilOperation; import com.jme3.material.RenderState.TestFunction; import com.jme3.math.*; import com.jme3.opencl.OpenCLObjectManager; import com.jme3.renderer.*; import com.jme3.scene.Mesh; import com.jme3.scene.Mesh.Mode; import com.jme3.scene.VertexBuffer; import com.jme3.scene.VertexBuffer.Format; import com.jme3.scene.VertexBuffer.Type; import com.jme3.scene.VertexBuffer.Usage; import com.jme3.shader.*; import com.jme3.shader.Shader.ShaderSource; import com.jme3.shader.Shader.ShaderType; import com.jme3.texture.FrameBuffer; import com.jme3.texture.FrameBuffer.RenderBuffer; import com.jme3.texture.Image; import com.jme3.texture.Texture; import com.jme3.texture.Texture2D; import com.jme3.texture.Texture.ShadowCompareMode; import com.jme3.texture.Texture.WrapAxis; import com.jme3.texture.image.LastTextureState; import com.jme3.util.BufferUtils; import com.jme3.util.ListMap; import com.jme3.util.MipMapGenerator; import com.jme3.util.NativeObjectManager; import jme3tools.shader.ShaderDebug; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class GLRenderer implements Renderer { private static final Logger logger = Logger.getLogger(GLRenderer.class.getName()); private static final boolean VALIDATE_SHADER = false; private static final Pattern GLVERSION_PATTERN = Pattern.compile(".*?(\\d+)\\.(\\d+).*"); private final ByteBuffer nameBuf = BufferUtils.createByteBuffer(250); private final StringBuilder stringBuf = new StringBuilder(250); private final IntBuffer intBuf1 = BufferUtils.createIntBuffer(1); private final IntBuffer intBuf16 = BufferUtils.createIntBuffer(16); private final FloatBuffer floatBuf16 = BufferUtils.createFloatBuffer(16); private final RenderContext context = new RenderContext(); private final NativeObjectManager objManager = new NativeObjectManager(); private final EnumSet<Caps> caps = EnumSet.noneOf(Caps.class); private final EnumMap<Limits, Integer> limits = new EnumMap<Limits, Integer>(Limits.class); private FrameBuffer mainFbOverride = null; private final Statistics statistics = new Statistics(); private int vpX, vpY, vpW, vpH; private int clipX, clipY, clipW, clipH; private int defaultAnisotropicFilter = 1; private boolean linearizeSrgbImages; private HashSet<String> extensions; private final GL gl; private final GL2 gl2; private final GL3 gl3; private final GL4 gl4; private final GLExt glext; private final GLFbo glfbo; private final TextureUtil texUtil; public GLRenderer(GL gl, GLExt glext, GLFbo glfbo) { this.gl = gl; this.gl2 = gl instanceof GL2 ? (GL2)gl : null; this.gl3 = gl instanceof GL3 ? (GL3)gl : null; this.gl4 = gl instanceof GL4 ? (GL4)gl : null; this.glfbo = glfbo; this.glext = glext; this.texUtil = new TextureUtil(gl, gl2, glext); } @Override public Statistics getStatistics() { return statistics; } @Override public EnumSet<Caps> getCaps() { return caps; } // Not making public yet ... @Override public EnumMap<Limits, Integer> getLimits() { return limits; } private HashSet<String> loadExtensions() { HashSet<String> extensionSet = new HashSet<String>(64); if (caps.contains(Caps.OpenGL30)) { // If OpenGL3+ is available, use the non-deprecated way // of getting supported extensions. gl3.glGetInteger(GL3.GL_NUM_EXTENSIONS, intBuf16); int extensionCount = intBuf16.get(0); for (int i = 0; i < extensionCount; i++) { String extension = gl3.glGetString(GL.GL_EXTENSIONS, i); extensionSet.add(extension); } } else { extensionSet.addAll(Arrays.asList(gl.glGetString(GL.GL_EXTENSIONS).split(" "))); } return extensionSet; } public static int extractVersion(String version) { Matcher m = GLVERSION_PATTERN.matcher(version); if (m.matches()) { int major = Integer.parseInt(m.group(1)); int minor = Integer.parseInt(m.group(2)); if (minor >= 10 && minor % 10 == 0) { // some versions can look like "1.30" instead of "1.3". // make sure to correct for this minor /= 10; } return major * 100 + minor * 10; } else { return -1; } } private boolean hasExtension(String extensionName) { return extensions.contains(extensionName); } private void loadCapabilitiesES() { int oglVer = extractVersion(gl.glGetString(GL.GL_VERSION)); caps.add(Caps.GLSL100); caps.add(Caps.OpenGLES20); caps.add(Caps.Multisample); if (oglVer >= 300) { caps.add(Caps.OpenGLES30); caps.add(Caps.GLSL300); // Instancing is core in GLES300 caps.add(Caps.MeshInstancing); } if (oglVer >= 310) { caps.add(Caps.OpenGLES31); caps.add(Caps.GLSL310); } if (oglVer >= 320) { caps.add(Caps.OpenGLES32); caps.add(Caps.GLSL320); caps.add(Caps.GeometryShader); caps.add(Caps.TesselationShader); } // Important: Do not add OpenGL20 - that's the desktop capability! } private void loadCapabilitiesGL2() { int oglVer = extractVersion(gl.glGetString(GL.GL_VERSION)); if (oglVer >= 200) { caps.add(Caps.OpenGL20); if (oglVer >= 210) { caps.add(Caps.OpenGL21); } if (oglVer >= 300) { caps.add(Caps.OpenGL30); } if (oglVer >= 310) { caps.add(Caps.OpenGL31); } if (oglVer >= 320) { caps.add(Caps.OpenGL32); } if (oglVer >= 330) { caps.add(Caps.OpenGL33); caps.add(Caps.GeometryShader); } if (oglVer >= 400) { caps.add(Caps.OpenGL40); caps.add(Caps.TesselationShader); } if (oglVer >= 410) { caps.add(Caps.OpenGL41); } if (oglVer >= 420) { caps.add(Caps.OpenGL42); } if (oglVer >= 430) { caps.add(Caps.OpenGL43); } if (oglVer >= 440) { caps.add(Caps.OpenGL44); } if (oglVer >= 450) { caps.add(Caps.OpenGL45); } } int glslVer = extractVersion(gl.glGetString(GL.GL_SHADING_LANGUAGE_VERSION)); switch (glslVer) { default: if (glslVer < 400) { break; } // so that future OpenGL revisions won't break jme3 // fall through intentional case 450: caps.add(Caps.GLSL450); case 440: caps.add(Caps.GLSL440); case 430: caps.add(Caps.GLSL430); case 420: caps.add(Caps.GLSL420); case 410: caps.add(Caps.GLSL410); case 400: caps.add(Caps.GLSL400); case 330: caps.add(Caps.GLSL330); case 150: caps.add(Caps.GLSL150); case 140: caps.add(Caps.GLSL140); case 130: caps.add(Caps.GLSL130); case 120: caps.add(Caps.GLSL120); case 110: caps.add(Caps.GLSL110); case 100: caps.add(Caps.GLSL100); break; } // Workaround, always assume we support GLSL100 & GLSL110 // Supporting OpenGL 2.0 means supporting GLSL 1.10. caps.add(Caps.GLSL110); caps.add(Caps.GLSL100); // Fix issue in TestRenderToMemory when GL.GL_FRONT is the main // buffer being used. context.initialDrawBuf = getInteger(GL2.GL_DRAW_BUFFER); context.initialReadBuf = getInteger(GL2.GL_READ_BUFFER); // XXX: This has to be GL.GL_BACK for canvas on Mac // Since initialDrawBuf is GL.GL_FRONT for pbuffer, gotta // change this value later on ... // initialDrawBuf = GL.GL_BACK; // initialReadBuf = GL.GL_BACK; } private void loadCapabilitiesCommon() { extensions = loadExtensions(); limits.put(Limits.VertexTextureUnits, getInteger(GL.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS)); if (limits.get(Limits.VertexTextureUnits) > 0) { caps.add(Caps.VertexTextureFetch); } limits.put(Limits.FragmentTextureUnits, getInteger(GL.GL_MAX_TEXTURE_IMAGE_UNITS)); if (caps.contains(Caps.OpenGLES20)) { limits.put(Limits.FragmentUniformVectors, getInteger(GL.GL_MAX_FRAGMENT_UNIFORM_VECTORS)); limits.put(Limits.VertexUniformVectors, getInteger(GL.GL_MAX_VERTEX_UNIFORM_VECTORS)); } else { limits.put(Limits.FragmentUniformVectors, getInteger(GL.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS) / 4); limits.put(Limits.VertexUniformVectors, getInteger(GL.GL_MAX_VERTEX_UNIFORM_COMPONENTS) / 4); } limits.put(Limits.VertexAttributes, getInteger(GL.GL_MAX_VERTEX_ATTRIBS)); limits.put(Limits.TextureSize, getInteger(GL.GL_MAX_TEXTURE_SIZE)); limits.put(Limits.CubemapSize, getInteger(GL.GL_MAX_CUBE_MAP_TEXTURE_SIZE)); if (hasExtension("GL_ARB_draw_instanced") && hasExtension("GL_ARB_instanced_arrays")) { // TODO: If there were a way to call the EXT extension for GLES2, should check also (hasExtension("GL_EXT_draw_instanced") && hasExtension("GL_EXT_instanced_arrays")) caps.add(Caps.MeshInstancing); } if (hasExtension("GL_OES_element_index_uint") || gl2 != null) { caps.add(Caps.IntegerIndexBuffer); } if (hasExtension("GL_ARB_texture_buffer_object")) { caps.add(Caps.TextureBuffer); } // == texture format extensions == boolean hasFloatTexture; hasFloatTexture = hasExtension("GL_OES_texture_half_float") && hasExtension("GL_OES_texture_float"); if (!hasFloatTexture) { hasFloatTexture = hasExtension("GL_ARB_texture_float") && hasExtension("GL_ARB_half_float_pixel"); if (!hasFloatTexture) { hasFloatTexture = caps.contains(Caps.OpenGL30); } } if (hasFloatTexture) { caps.add(Caps.FloatTexture); } // integer texture format extensions if(hasExtension("GL_EXT_texture_integer") || caps.contains(Caps.OpenGL30)) caps.add(Caps.IntegerTexture); if (hasExtension("GL_OES_depth_texture") || gl2 != null) { caps.add(Caps.DepthTexture); } if (hasExtension("GL_OES_depth24")) { caps.add(Caps.Depth24); } if (hasExtension("GL_OES_rgb8_rgba8") || hasExtension("GL_ARM_rgba8") || hasExtension("GL_EXT_texture_format_BGRA8888")) { caps.add(Caps.Rgba8); } if (caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES30) || hasExtension("GL_OES_packed_depth_stencil")) { caps.add(Caps.PackedDepthStencilBuffer); } if (hasExtension("GL_ARB_color_buffer_float") && hasExtension("GL_ARB_half_float_pixel")) { // XXX: Require both 16 and 32 bit float support for FloatColorBuffer. caps.add(Caps.FloatColorBuffer); } if (caps.contains(Caps.OpenGLES30) || hasExtension("GL_ARB_depth_buffer_float")) { caps.add(Caps.FloatDepthBuffer); } if ((hasExtension("GL_EXT_packed_float") && hasFloatTexture) || caps.contains(Caps.OpenGL30)) { // Either OpenGL3 is available or both packed_float & half_float_pixel. caps.add(Caps.PackedFloatColorBuffer); caps.add(Caps.PackedFloatTexture); } if (hasExtension("GL_EXT_texture_shared_exponent") || caps.contains(Caps.OpenGL30)) { caps.add(Caps.SharedExponentTexture); } if (hasExtension("GL_EXT_texture_compression_s3tc")) { caps.add(Caps.TextureCompressionS3TC); } if (hasExtension("GL_ARB_ES3_compatibility")) { caps.add(Caps.TextureCompressionETC2); caps.add(Caps.TextureCompressionETC1); } else if (hasExtension("GL_OES_compressed_ETC1_RGB8_texture")) { caps.add(Caps.TextureCompressionETC1); } // == end texture format extensions == if (hasExtension("GL_ARB_vertex_array_object") || caps.contains(Caps.OpenGL30)) { caps.add(Caps.VertexBufferArray); } if (hasExtension("GL_ARB_texture_non_power_of_two") || hasExtension("GL_OES_texture_npot") || caps.contains(Caps.OpenGL30)) { caps.add(Caps.NonPowerOfTwoTextures); } else { logger.log(Level.WARNING, "Your graphics card does not " + "support non-power-of-2 textures. " + "Some features might not work."); } if (caps.contains(Caps.OpenGLES20)) { // OpenGL ES 2 has some limited support for NPOT textures caps.add(Caps.PartialNonPowerOfTwoTextures); } if (hasExtension("GL_EXT_texture_array") || caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES30)) { caps.add(Caps.TextureArray); } if (hasExtension("GL_EXT_texture_filter_anisotropic")) { caps.add(Caps.TextureFilterAnisotropic); limits.put(Limits.TextureAnisotropy, getInteger(GLExt.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)); } if (hasExtension("GL_EXT_framebuffer_object") || caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES20)) { caps.add(Caps.FrameBuffer); limits.put(Limits.RenderBufferSize, getInteger(GLFbo.GL_MAX_RENDERBUFFER_SIZE_EXT)); limits.put(Limits.FrameBufferAttachments, getInteger(GLFbo.GL_MAX_COLOR_ATTACHMENTS_EXT)); if (hasExtension("GL_EXT_framebuffer_blit") || caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES30)) { caps.add(Caps.FrameBufferBlit); } if (hasExtension("GL_EXT_framebuffer_multisample") || caps.contains(Caps.OpenGLES30)) { caps.add(Caps.FrameBufferMultisample); limits.put(Limits.FrameBufferSamples, getInteger(GLExt.GL_MAX_SAMPLES_EXT)); } if (hasExtension("GL_ARB_texture_multisample") || caps.contains(Caps.OpenGLES31)) { // GLES31 does not fully support it caps.add(Caps.TextureMultisample); limits.put(Limits.ColorTextureSamples, getInteger(GLExt.GL_MAX_COLOR_TEXTURE_SAMPLES)); limits.put(Limits.DepthTextureSamples, getInteger(GLExt.GL_MAX_DEPTH_TEXTURE_SAMPLES)); if (!limits.containsKey(Limits.FrameBufferSamples)) { // In case they want to query samples on main FB ... limits.put(Limits.FrameBufferSamples, limits.get(Limits.ColorTextureSamples)); } } if (hasExtension("GL_ARB_draw_buffers") || caps.contains(Caps.OpenGL30) || caps.contains(Caps.OpenGLES30)) { limits.put(Limits.FrameBufferMrtAttachments, getInteger(GLExt.GL_MAX_DRAW_BUFFERS_ARB)); if (limits.get(Limits.FrameBufferMrtAttachments) > 1) { caps.add(Caps.FrameBufferMRT); } } else { limits.put(Limits.FrameBufferMrtAttachments, 1); } } if (hasExtension("GL_ARB_multisample") /*|| caps.contains(Caps.OpenGLES20)*/) { boolean available = getInteger(GLExt.GL_SAMPLE_BUFFERS_ARB) != 0; int samples = getInteger(GLExt.GL_SAMPLES_ARB); logger.log(Level.FINER, "Samples: {0}", samples); boolean enabled = gl.glIsEnabled(GLExt.GL_MULTISAMPLE_ARB); if (samples > 0 && available && !enabled) { // Doesn't seem to be necessary .. OGL spec says it's always // set by default? gl.glEnable(GLExt.GL_MULTISAMPLE_ARB); } caps.add(Caps.Multisample); } // Supports sRGB pipeline. if ( (hasExtension("GL_ARB_framebuffer_sRGB") && hasExtension("GL_EXT_texture_sRGB")) || caps.contains(Caps.OpenGL30) ) { caps.add(Caps.Srgb); } // Supports seamless cubemap if (hasExtension("GL_ARB_seamless_cube_map") || caps.contains(Caps.OpenGL32)) { caps.add(Caps.SeamlessCubemap); } if (caps.contains(Caps.OpenGL32) && !hasExtension("GL_ARB_compatibility")) { caps.add(Caps.CoreProfile); } if (hasExtension("GL_ARB_get_program_binary")) { int binaryFormats = getInteger(GLExt.GL_NUM_PROGRAM_BINARY_FORMATS); if (binaryFormats > 0) { caps.add(Caps.BinaryShader); } } if (hasExtension("GL_OES_geometry_shader") || hasExtension("GL_EXT_geometry_shader")) { caps.add(Caps.GeometryShader); } if (hasExtension("GL_OES_tessellation_shader") || hasExtension("GL_EXT_tessellation_shader")) { caps.add(Caps.TesselationShader); } if (hasExtension("GL_ARB_shader_storage_buffer_object")) { caps.add(Caps.ShaderStorageBufferObject); limits.put(Limits.ShaderStorageBufferObjectMaxBlockSize, getInteger(GL4.GL_MAX_SHADER_STORAGE_BLOCK_SIZE)); // Commented out until we support ComputeShaders and the ComputeShader Cap // limits.put(Limits.ShaderStorageBufferObjectMaxComputeBlocks, getInteger(GL4.GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS)); if (caps.contains(Caps.GeometryShader)) { limits.put(Limits.ShaderStorageBufferObjectMaxGeometryBlocks, getInteger(GL4.GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS)); } limits.put(Limits.ShaderStorageBufferObjectMaxFragmentBlocks, getInteger(GL4.GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS)); limits.put(Limits.ShaderStorageBufferObjectMaxVertexBlocks, getInteger(GL4.GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS)); if (caps.contains(Caps.TesselationShader)) { limits.put(Limits.ShaderStorageBufferObjectMaxTessControlBlocks, getInteger(GL4.GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS)); limits.put(Limits.ShaderStorageBufferObjectMaxTessEvaluationBlocks, getInteger(GL4.GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS)); } limits.put(Limits.ShaderStorageBufferObjectMaxCombineBlocks, getInteger(GL4.GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS)); } if (hasExtension("GL_ARB_uniform_buffer_object")) { caps.add(Caps.UniformBufferObject); limits.put(Limits.UniformBufferObjectMaxBlockSize, getInteger(GL3.GL_MAX_UNIFORM_BLOCK_SIZE)); if (caps.contains(Caps.GeometryShader)) { limits.put(Limits.UniformBufferObjectMaxGeometryBlocks, getInteger(GL3.GL_MAX_GEOMETRY_UNIFORM_BLOCKS)); } limits.put(Limits.UniformBufferObjectMaxFragmentBlocks, getInteger(GL3.GL_MAX_FRAGMENT_UNIFORM_BLOCKS)); limits.put(Limits.UniformBufferObjectMaxVertexBlocks, getInteger(GL3.GL_MAX_VERTEX_UNIFORM_BLOCKS)); } if(caps.contains(Caps.OpenGL20)){ caps.add(Caps.UnpackRowLength); } // Print context information logger.log(Level.INFO, "OpenGL Renderer Information\n" + " * Vendor: {0}\n" + " * Renderer: {1}\n" + " * OpenGL Version: {2}\n" + " * GLSL Version: {3}\n" + " * Profile: {4}", new Object[]{ gl.glGetString(GL.GL_VENDOR), gl.glGetString(GL.GL_RENDERER), gl.glGetString(GL.GL_VERSION), gl.glGetString(GL.GL_SHADING_LANGUAGE_VERSION), caps.contains(Caps.CoreProfile) ? "Core" : "Compatibility" }); // Print capabilities (if fine logging is enabled) if (logger.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append("Supported capabilities: \n"); for (Caps cap : caps) { sb.append("\t").append(cap.toString()).append("\n"); } sb.append("\nHardware limits: \n"); for (Limits limit : Limits.values()) { Integer value = limits.get(limit); if (value == null) { value = 0; } sb.append("\t").append(limit.name()).append(" = ") .append(value).append("\n"); } logger.log(Level.FINE, sb.toString()); } texUtil.initialize(caps); } private void loadCapabilities() { if (gl2 != null && !(gl instanceof GLES_30)) { loadCapabilitiesGL2(); } else { loadCapabilitiesES(); } loadCapabilitiesCommon(); } private int getInteger(int en) { intBuf16.clear(); gl.glGetInteger(en, intBuf16); return intBuf16.get(0); } private boolean getBoolean(int en) { gl.glGetBoolean(en, nameBuf); return nameBuf.get(0) != (byte)0; } @SuppressWarnings("fallthrough") @Override public void initialize() { loadCapabilities(); // Initialize default state.. gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1); if (caps.contains(Caps.SeamlessCubemap)) { // Enable this globally. Should be OK. gl.glEnable(GLExt.GL_TEXTURE_CUBE_MAP_SEAMLESS); } if (caps.contains(Caps.CoreProfile)) { // Core Profile requires VAO to be bound. gl3.glGenVertexArrays(intBuf16); int vaoId = intBuf16.get(0); gl3.glBindVertexArray(vaoId); } if (gl2 != null && !(gl instanceof GLES_30)) { gl2.glEnable(GL2.GL_VERTEX_PROGRAM_POINT_SIZE); if (!caps.contains(Caps.CoreProfile)) { gl2.glEnable(GL2.GL_POINT_SPRITE); } } } @Override public void invalidateState() { context.reset(); if (gl2 != null) { context.initialDrawBuf = getInteger(GL2.GL_DRAW_BUFFER); context.initialReadBuf = getInteger(GL2.GL_READ_BUFFER); } } @Override public void resetGLObjects() { logger.log(Level.FINE, "Reseting objects and invalidating state"); objManager.resetObjects(); statistics.clearMemory(); invalidateState(); } @Override public void cleanup() { logger.log(Level.FINE, "Deleting objects and invalidating state"); objManager.deleteAllObjects(this); OpenCLObjectManager.getInstance().deleteAllObjects(); statistics.clearMemory(); invalidateState(); } @Override public void setDepthRange(float start, float end) { gl.glDepthRange(start, end); } @Override public void clearBuffers(boolean color, boolean depth, boolean stencil) { int bits = 0; if (color) { //See explanations of the depth below, we must enable color write to be able to clear the color buffer if (context.colorWriteEnabled == false) { gl.glColorMask(true, true, true, true); context.colorWriteEnabled = true; } bits = GL.GL_COLOR_BUFFER_BIT; } if (depth) { // glClear(GL.GL_DEPTH_BUFFER_BIT) seems to not work when glDepthMask is false // here s some link on openl board // if depth clear is requested, we enable the depthMask if (context.depthWriteEnabled == false) { gl.glDepthMask(true); context.depthWriteEnabled = true; } bits |= GL.GL_DEPTH_BUFFER_BIT; } if (stencil) { // May need to set glStencilMask(0xFF) here if we ever allow users // to change the stencil mask. bits |= GL.GL_STENCIL_BUFFER_BIT; } if (bits != 0) { gl.glClear(bits); } } @Override public void setBackgroundColor(ColorRGBA color) { if (!context.clearColor.equals(color)) { gl.glClearColor(color.r, color.g, color.b, color.a); context.clearColor.set(color); } } @Override public void setDefaultAnisotropicFilter(int level) { if (level < 1) { throw new IllegalArgumentException("level cannot be less than 1"); } this.defaultAnisotropicFilter = level; } @Override public void setAlphaToCoverage(boolean value) { if (caps.contains(Caps.Multisample)) { if (value) { gl.glEnable(GLExt.GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); } else { gl.glDisable(GLExt.GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); } } } @Override public void applyRenderState(RenderState state) { if (gl2 != null) { if (state.isWireframe() && !context.wireframe) { gl2.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2.GL_LINE); context.wireframe = true; } else if (!state.isWireframe() && context.wireframe) { gl2.glPolygonMode(GL.GL_FRONT_AND_BACK, GL2.GL_FILL); context.wireframe = false; } } if (state.isDepthTest() && !context.depthTestEnabled) { gl.glEnable(GL.GL_DEPTH_TEST); context.depthTestEnabled = true; } else if (!state.isDepthTest() && context.depthTestEnabled) { gl.glDisable(GL.GL_DEPTH_TEST); context.depthTestEnabled = false; } if (state.isDepthTest() && state.getDepthFunc() != context.depthFunc) { gl.glDepthFunc(convertTestFunction(state.getDepthFunc())); context.depthFunc = state.getDepthFunc(); } if (state.isDepthWrite() && !context.depthWriteEnabled) { gl.glDepthMask(true); context.depthWriteEnabled = true; } else if (!state.isDepthWrite() && context.depthWriteEnabled) { gl.glDepthMask(false); context.depthWriteEnabled = false; } if (state.isColorWrite() && !context.colorWriteEnabled) { gl.glColorMask(true, true, true, true); context.colorWriteEnabled = true; } else if (!state.isColorWrite() && context.colorWriteEnabled) { gl.glColorMask(false, false, false, false); context.colorWriteEnabled = false; } if (state.isPolyOffset()) { if (!context.polyOffsetEnabled) { gl.glEnable(GL.GL_POLYGON_OFFSET_FILL); gl.glPolygonOffset(state.getPolyOffsetFactor(), state.getPolyOffsetUnits()); context.polyOffsetEnabled = true; context.polyOffsetFactor = state.getPolyOffsetFactor(); context.polyOffsetUnits = state.getPolyOffsetUnits(); } else { if (state.getPolyOffsetFactor() != context.polyOffsetFactor || state.getPolyOffsetUnits() != context.polyOffsetUnits) { gl.glPolygonOffset(state.getPolyOffsetFactor(), state.getPolyOffsetUnits()); context.polyOffsetFactor = state.getPolyOffsetFactor(); context.polyOffsetUnits = state.getPolyOffsetUnits(); } } } else { if (context.polyOffsetEnabled) { gl.glDisable(GL.GL_POLYGON_OFFSET_FILL); context.polyOffsetEnabled = false; context.polyOffsetFactor = 0; context.polyOffsetUnits = 0; } } if (state.getFaceCullMode() != context.cullMode) { if (state.getFaceCullMode() == RenderState.FaceCullMode.Off) { gl.glDisable(GL.GL_CULL_FACE); } else { gl.glEnable(GL.GL_CULL_FACE); } switch (state.getFaceCullMode()) { case Off: break; case Back: gl.glCullFace(GL.GL_BACK); break; case Front: gl.glCullFace(GL.GL_FRONT); break; case FrontAndBack: gl.glCullFace(GL.GL_FRONT_AND_BACK); break; default: throw new UnsupportedOperationException("Unrecognized face cull mode: " + state.getFaceCullMode()); } context.cullMode = state.getFaceCullMode(); } // Always update the blend equations and factors when using custom blend mode. if (state.getBlendMode() == BlendMode.Custom) { changeBlendMode(BlendMode.Custom); blendFuncSeparate( state.getCustomSfactorRGB(), state.getCustomDfactorRGB(), state.getCustomSfactorAlpha(), state.getCustomDfactorAlpha()); blendEquationSeparate(state.getBlendEquation(), state.getBlendEquationAlpha()); // Update the blend equations and factors only on a mode change for all the other (common) blend modes. } else if (state.getBlendMode() != context.blendMode) { changeBlendMode(state.getBlendMode()); switch (state.getBlendMode()) { case Off: break; case Additive: blendFunc(RenderState.BlendFunc.One, RenderState.BlendFunc.One); break; case AlphaAdditive: blendFunc(RenderState.BlendFunc.Src_Alpha, RenderState.BlendFunc.One); break; case Alpha: blendFunc(RenderState.BlendFunc.Src_Alpha, RenderState.BlendFunc.One_Minus_Src_Alpha); break; case AlphaSumA: blendFuncSeparate( RenderState.BlendFunc.Src_Alpha, RenderState.BlendFunc.One_Minus_Src_Alpha, RenderState.BlendFunc.One, RenderState.BlendFunc.One ); break; case PremultAlpha: blendFunc(RenderState.BlendFunc.One, RenderState.BlendFunc.One_Minus_Src_Alpha); break; case Modulate: blendFunc(RenderState.BlendFunc.Dst_Color, RenderState.BlendFunc.Zero); break; case ModulateX2: blendFunc(RenderState.BlendFunc.Dst_Color, RenderState.BlendFunc.Src_Color); break; case Color: case Screen: blendFunc(RenderState.BlendFunc.One, RenderState.BlendFunc.One_Minus_Src_Color); break; case Exclusion: blendFunc(RenderState.BlendFunc.One_Minus_Dst_Color, RenderState.BlendFunc.One_Minus_Src_Color); break; default: throw new UnsupportedOperationException("Unrecognized blend mode: " + state.getBlendMode()); } // All of the common modes requires the ADD equation. // (This might change in the future?) blendEquationSeparate(RenderState.BlendEquation.Add, RenderState.BlendEquationAlpha.InheritColor); } if (context.stencilTest != state.isStencilTest() || context.frontStencilStencilFailOperation != state.getFrontStencilStencilFailOperation() || context.frontStencilDepthFailOperation != state.getFrontStencilDepthFailOperation() || context.frontStencilDepthPassOperation != state.getFrontStencilDepthPassOperation() || context.backStencilStencilFailOperation != state.getBackStencilStencilFailOperation() || context.backStencilDepthFailOperation != state.getBackStencilDepthFailOperation() || context.backStencilDepthPassOperation != state.getBackStencilDepthPassOperation() || context.frontStencilFunction != state.getFrontStencilFunction() || context.backStencilFunction != state.getBackStencilFunction()) { context.frontStencilStencilFailOperation = state.getFrontStencilStencilFailOperation(); //terrible looking, I know context.frontStencilDepthFailOperation = state.getFrontStencilDepthFailOperation(); context.frontStencilDepthPassOperation = state.getFrontStencilDepthPassOperation(); context.backStencilStencilFailOperation = state.getBackStencilStencilFailOperation(); context.backStencilDepthFailOperation = state.getBackStencilDepthFailOperation(); context.backStencilDepthPassOperation = state.getBackStencilDepthPassOperation(); context.frontStencilFunction = state.getFrontStencilFunction(); context.backStencilFunction = state.getBackStencilFunction(); if (state.isStencilTest()) { gl.glEnable(GL.GL_STENCIL_TEST); gl.glStencilOpSeparate(GL.GL_FRONT, convertStencilOperation(state.getFrontStencilStencilFailOperation()), convertStencilOperation(state.getFrontStencilDepthFailOperation()), convertStencilOperation(state.getFrontStencilDepthPassOperation())); gl.glStencilOpSeparate(GL.GL_BACK, convertStencilOperation(state.getBackStencilStencilFailOperation()), convertStencilOperation(state.getBackStencilDepthFailOperation()), convertStencilOperation(state.getBackStencilDepthPassOperation())); gl.glStencilFuncSeparate(GL.GL_FRONT, convertTestFunction(state.getFrontStencilFunction()), 0, Integer.MAX_VALUE); gl.glStencilFuncSeparate(GL.GL_BACK, convertTestFunction(state.getBackStencilFunction()), 0, Integer.MAX_VALUE); } else { gl.glDisable(GL.GL_STENCIL_TEST); } } if (context.lineWidth != state.getLineWidth()) { gl.glLineWidth(state.getLineWidth()); context.lineWidth = state.getLineWidth(); } } private void changeBlendMode(RenderState.BlendMode blendMode) { if (blendMode != context.blendMode) { if (blendMode == RenderState.BlendMode.Off) { gl.glDisable(GL.GL_BLEND); } else if (context.blendMode == RenderState.BlendMode.Off) { gl.glEnable(GL.GL_BLEND); } context.blendMode = blendMode; } } private void blendEquationSeparate(RenderState.BlendEquation blendEquation, RenderState.BlendEquationAlpha blendEquationAlpha) { if (blendEquation != context.blendEquation || blendEquationAlpha != context.blendEquationAlpha) { int glBlendEquation = convertBlendEquation(blendEquation); int glBlendEquationAlpha = blendEquationAlpha == RenderState.BlendEquationAlpha.InheritColor ? glBlendEquation : convertBlendEquationAlpha(blendEquationAlpha); gl.glBlendEquationSeparate(glBlendEquation, glBlendEquationAlpha); context.blendEquation = blendEquation; context.blendEquationAlpha = blendEquationAlpha; } } private void blendFunc(RenderState.BlendFunc sfactor, RenderState.BlendFunc dfactor) { if (sfactor != context.sfactorRGB || dfactor != context.dfactorRGB || sfactor != context.sfactorAlpha || dfactor != context.dfactorAlpha) { gl.glBlendFunc( convertBlendFunc(sfactor), convertBlendFunc(dfactor)); context.sfactorRGB = sfactor; context.dfactorRGB = dfactor; context.sfactorAlpha = sfactor; context.dfactorAlpha = dfactor; } } private void blendFuncSeparate(RenderState.BlendFunc sfactorRGB, RenderState.BlendFunc dfactorRGB, RenderState.BlendFunc sfactorAlpha, RenderState.BlendFunc dfactorAlpha) { if (sfactorRGB != context.sfactorRGB || dfactorRGB != context.dfactorRGB || sfactorAlpha != context.sfactorAlpha || dfactorAlpha != context.dfactorAlpha) { gl.glBlendFuncSeparate( convertBlendFunc(sfactorRGB), convertBlendFunc(dfactorRGB), convertBlendFunc(sfactorAlpha), convertBlendFunc(dfactorAlpha)); context.sfactorRGB = sfactorRGB; context.dfactorRGB = dfactorRGB; context.sfactorAlpha = sfactorAlpha; context.dfactorAlpha = dfactorAlpha; } } private int convertBlendEquation(RenderState.BlendEquation blendEquation) { switch (blendEquation) { case Add: return GL2.GL_FUNC_ADD; case Subtract: return GL2.GL_FUNC_SUBTRACT; case ReverseSubtract: return GL2.GL_FUNC_REVERSE_SUBTRACT; case Min: return GL2.GL_MIN; case Max: return GL2.GL_MAX; default: throw new UnsupportedOperationException("Unrecognized blend operation: " + blendEquation); } } private int convertBlendEquationAlpha(RenderState.BlendEquationAlpha blendEquationAlpha) { //Note: InheritColor mode should already be handled, that is why it does not belong the switch case. switch (blendEquationAlpha) { case Add: return GL2.GL_FUNC_ADD; case Subtract: return GL2.GL_FUNC_SUBTRACT; case ReverseSubtract: return GL2.GL_FUNC_REVERSE_SUBTRACT; case Min: return GL2.GL_MIN; case Max: return GL2.GL_MAX; default: throw new UnsupportedOperationException("Unrecognized alpha blend operation: " + blendEquationAlpha); } } private int convertBlendFunc(BlendFunc blendFunc) { switch (blendFunc) { case Zero: return GL.GL_ZERO; case One: return GL.GL_ONE; case Src_Color: return GL.GL_SRC_COLOR; case One_Minus_Src_Color: return GL.GL_ONE_MINUS_SRC_COLOR; case Dst_Color: return GL.GL_DST_COLOR; case One_Minus_Dst_Color: return GL.GL_ONE_MINUS_DST_COLOR; case Src_Alpha: return GL.GL_SRC_ALPHA; case One_Minus_Src_Alpha: return GL.GL_ONE_MINUS_SRC_ALPHA; case Dst_Alpha: return GL.GL_DST_ALPHA; case One_Minus_Dst_Alpha: return GL.GL_ONE_MINUS_DST_ALPHA; case Src_Alpha_Saturate: return GL.GL_SRC_ALPHA_SATURATE; default: throw new UnsupportedOperationException("Unrecognized blend function operation: " + blendFunc); } } private int convertStencilOperation(StencilOperation stencilOp) { switch (stencilOp) { case Keep: return GL.GL_KEEP; case Zero: return GL.GL_ZERO; case Replace: return GL.GL_REPLACE; case Increment: return GL.GL_INCR; case IncrementWrap: return GL.GL_INCR_WRAP; case Decrement: return GL.GL_DECR; case DecrementWrap: return GL.GL_DECR_WRAP; case Invert: return GL.GL_INVERT; default: throw new UnsupportedOperationException("Unrecognized stencil operation: " + stencilOp); } } private int convertTestFunction(TestFunction testFunc) { switch (testFunc) { case Never: return GL.GL_NEVER; case Less: return GL.GL_LESS; case LessOrEqual: return GL.GL_LEQUAL; case Greater: return GL.GL_GREATER; case GreaterOrEqual: return GL.GL_GEQUAL; case Equal: return GL.GL_EQUAL; case NotEqual: return GL.GL_NOTEQUAL; case Always: return GL.GL_ALWAYS; default: throw new UnsupportedOperationException("Unrecognized test function: " + testFunc); } } @Override public void setViewPort(int x, int y, int w, int h) { if (x != vpX || vpY != y || vpW != w || vpH != h) { gl.glViewport(x, y, w, h); vpX = x; vpY = y; vpW = w; vpH = h; } } @Override public void setClipRect(int x, int y, int width, int height) { if (!context.clipRectEnabled) { gl.glEnable(GL.GL_SCISSOR_TEST); context.clipRectEnabled = true; } if (clipX != x || clipY != y || clipW != width || clipH != height) { gl.glScissor(x, y, width, height); clipX = x; clipY = y; clipW = width; clipH = height; } } @Override public void clearClipRect() { if (context.clipRectEnabled) { gl.glDisable(GL.GL_SCISSOR_TEST); context.clipRectEnabled = false; clipX = 0; clipY = 0; clipW = 0; clipH = 0; } } @Override public void postFrame() { objManager.deleteUnused(this); OpenCLObjectManager.getInstance().deleteUnusedObjects(); gl.resetStats(); } protected void bindProgram(Shader shader) { int shaderId = shader.getId(); if (context.boundShaderProgram != shaderId) { gl.glUseProgram(shaderId); statistics.onShaderUse(shader, true); context.boundShader = shader; context.boundShaderProgram = shaderId; } else { statistics.onShaderUse(shader, false); } } protected void updateUniformLocation(Shader shader, Uniform uniform) { int loc = gl.glGetUniformLocation(shader.getId(), uniform.getName()); if (loc < 0) { uniform.setLocation(-1); // uniform is not declared in shader logger.log(Level.FINE, "Uniform {0} is not declared in shader {1}.", new Object[]{uniform.getName(), shader.getSources()}); } else { uniform.setLocation(loc); } } protected void updateUniform(Shader shader, Uniform uniform) { int shaderId = shader.getId(); assert uniform.getName() != null; assert shader.getId() > 0; bindProgram(shader); int loc = uniform.getLocation(); if (loc == -1) { return; } if (loc == -2) { // get uniform location updateUniformLocation(shader, uniform); if (uniform.getLocation() == -1) { // not declared, ignore uniform.clearUpdateNeeded(); return; } loc = uniform.getLocation(); } if (uniform.getVarType() == null) { return; // value not set yet.. } statistics.onUniformSet(); uniform.clearUpdateNeeded(); FloatBuffer fb; IntBuffer ib; switch (uniform.getVarType()) { case Float: Float f = (Float) uniform.getValue(); gl.glUniform1f(loc, f.floatValue()); break; case Vector2: Vector2f v2 = (Vector2f) uniform.getValue(); gl.glUniform2f(loc, v2.getX(), v2.getY()); break; case Vector3: Vector3f v3 = (Vector3f) uniform.getValue(); gl.glUniform3f(loc, v3.getX(), v3.getY(), v3.getZ()); break; case Vector4: Object val = uniform.getValue(); if (val instanceof ColorRGBA) { ColorRGBA c = (ColorRGBA) val; gl.glUniform4f(loc, c.r, c.g, c.b, c.a); } else if (val instanceof Vector4f) { Vector4f c = (Vector4f) val; gl.glUniform4f(loc, c.x, c.y, c.z, c.w); } else { Quaternion c = (Quaternion) uniform.getValue(); gl.glUniform4f(loc, c.getX(), c.getY(), c.getZ(), c.getW()); } break; case Boolean: Boolean b = (Boolean) uniform.getValue(); gl.glUniform1i(loc, b.booleanValue() ? GL.GL_TRUE : GL.GL_FALSE); break; case Matrix3: fb = uniform.getMultiData(); assert fb.remaining() == 9; gl.glUniformMatrix3(loc, false, fb); break; case Matrix4: fb = uniform.getMultiData(); assert fb.remaining() == 16; gl.glUniformMatrix4(loc, false, fb); break; case IntArray: ib = (IntBuffer) uniform.getValue(); gl.glUniform1(loc, ib); break; case FloatArray: fb = uniform.getMultiData(); gl.glUniform1(loc, fb); break; case Vector2Array: fb = uniform.getMultiData(); gl.glUniform2(loc, fb); break; case Vector3Array: fb = uniform.getMultiData(); gl.glUniform3(loc, fb); break; case Vector4Array: fb = uniform.getMultiData(); gl.glUniform4(loc, fb); break; case Matrix4Array: fb = uniform.getMultiData(); gl.glUniformMatrix4(loc, false, fb); break; case Int: Integer i = (Integer) uniform.getValue(); gl.glUniform1i(loc, i.intValue()); break; default: throw new UnsupportedOperationException("Unsupported uniform type: " + uniform.getVarType()); } } /** * Updates the buffer block for the shader. * * @param shader the shader. * @param bufferBlock the storage block. */ protected void updateShaderBufferBlock(final Shader shader, final ShaderBufferBlock bufferBlock) { assert bufferBlock.getName() != null; assert shader.getId() > 0; final BufferObject bufferObject = bufferBlock.getBufferObject(); if (bufferObject.getUniqueId() == -1 || bufferObject.isUpdateNeeded()) { updateBufferData(bufferObject); } if (!bufferBlock.isUpdateNeeded()) { return; } bindProgram(shader); final int shaderId = shader.getId(); final BufferObject.BufferType bufferType = bufferObject.getBufferType(); bindBuffer(bufferBlock, bufferObject, shaderId, bufferType); bufferBlock.clearUpdateNeeded(); } private void bindBuffer(final ShaderBufferBlock bufferBlock, final BufferObject bufferObject, final int shaderId, final BufferObject.BufferType bufferType) { switch (bufferType) { case UniformBufferObject: { final int blockIndex = gl3.glGetUniformBlockIndex(shaderId, bufferBlock.getName()); gl3.glBindBufferBase(GL3.GL_UNIFORM_BUFFER, bufferObject.getBinding(), bufferObject.getId()); gl3.glUniformBlockBinding(GL3.GL_UNIFORM_BUFFER, blockIndex, bufferObject.getBinding()); break; } case ShaderStorageBufferObject: { final int blockIndex = gl4.glGetProgramResourceIndex(shaderId, GL4.GL_SHADER_STORAGE_BLOCK, bufferBlock.getName()); gl4.glShaderStorageBlockBinding(shaderId, blockIndex, bufferObject.getBinding()); gl4.glBindBufferBase(GL4.GL_SHADER_STORAGE_BUFFER, bufferObject.getBinding(), bufferObject.getId()); break; } default: { throw new IllegalArgumentException("Doesn't support binding of " + bufferType); } } } protected void updateShaderUniforms(Shader shader) { ListMap<String, Uniform> uniforms = shader.getUniformMap(); for (int i = 0; i < uniforms.size(); i++) { Uniform uniform = uniforms.getValue(i); if (uniform.isUpdateNeeded()) { updateUniform(shader, uniform); } } } /** * Updates all shader's buffer blocks. * * @param shader the shader. */ protected void updateShaderBufferBlocks(final Shader shader) { final ListMap<String, ShaderBufferBlock> bufferBlocks = shader.getBufferBlockMap(); for (int i = 0; i < bufferBlocks.size(); i++) { updateShaderBufferBlock(shader, bufferBlocks.getValue(i)); } } protected void resetUniformLocations(Shader shader) { ListMap<String, Uniform> uniforms = shader.getUniformMap(); for (int i = 0; i < uniforms.size(); i++) { Uniform uniform = uniforms.getValue(i); uniform.reset(); // e.g check location again } } public int convertShaderType(ShaderType type) { switch (type) { case Fragment: return GL.GL_FRAGMENT_SHADER; case Vertex: return GL.GL_VERTEX_SHADER; case Geometry: return GL3.GL_GEOMETRY_SHADER; case TessellationControl: return GL4.GL_TESS_CONTROL_SHADER; case TessellationEvaluation: return GL4.GL_TESS_EVALUATION_SHADER; default: throw new UnsupportedOperationException("Unrecognized shader type."); } } public void updateShaderSourceData(ShaderSource source) { int id = source.getId(); if (id == -1) { // Create id id = gl.glCreateShader(convertShaderType(source.getType())); if (id <= 0) { throw new RendererException("Invalid ID received when trying to create shader."); } source.setId(id); } else { throw new RendererException("Cannot recompile shader source"); } boolean gles3 = caps.contains(Caps.OpenGLES30); boolean gles2 = caps.contains(Caps.OpenGLES20); String language = source.getLanguage(); if (!gles3 && gles2 && !language.equals("GLSL100")) { //avoid this check for gles3 throw new RendererException("This shader cannot run in OpenGL ES 2. " + "Only GLSL 1.00 shaders are supported."); } boolean insertPrecision = false; // Upload shader source. // Merge the defines and source code. stringBuf.setLength(0); int version = Integer.parseInt(language.substring(4)); if (language.startsWith("GLSL")) { if (version > 100) { stringBuf.append("#version "); stringBuf.append(language.substring(4)); if (version >= 150) { if(gles3) { stringBuf.append(" es"); } else { stringBuf.append(" core"); } } stringBuf.append("\n"); } else { if (gles2 || gles3) { // request GLSL ES (1.00) when compiling under GLES2. stringBuf.append("#version 100\n"); } else { // version 100 does not exist in desktop GLSL. // put version 110 in that case to enable strict checking // (Only enabled for desktop GL) stringBuf.append("#version 110\n"); } } if (gles2 || gles3) { //Inserting precision only to fragment shaders creates some link failures because of different precision between shaders //But adding the precision to all shaders generates rendering glitches in some devices if not set to highp if (source.getType() == ShaderType.Fragment) { // GLES requires precision qualifier. insertPrecision = true; } } } if (linearizeSrgbImages) { stringBuf.append("#define SRGB 1\n"); } stringBuf.append("#define ").append(source.getType().name().toUpperCase()).append("_SHADER 1\n"); stringBuf.append(source.getDefines()); stringBuf.append(source.getSource()); if(insertPrecision){ // default precision could be defined in GLSLCompat.glsllib so final users can use custom defined precision instead // precision token is not a preprocessor dirrective therefore it must be placed after #extension tokens to avoid // Error P0001: Extension directive must occur before any non-preprocessor tokens int idx = stringBuf.lastIndexOf("#extension"); idx = stringBuf.indexOf("\n", idx); if(version>=310) { stringBuf.insert(idx + 1, "precision highp sampler2DMS;\n"); } if(version>=300) { stringBuf.insert(idx + 1, "precision highp sampler2DArray;\n"); stringBuf.insert(idx + 1, "precision highp sampler2DShadow;\n"); stringBuf.insert(idx + 1, "precision highp sampler3D;\n"); stringBuf.insert(idx + 1, "precision highp sampler2D;\n"); } stringBuf.insert(idx + 1, "precision highp float;\n"); } intBuf1.clear(); intBuf1.put(0, stringBuf.length()); gl.glShaderSource(id, new String[]{ stringBuf.toString() }, intBuf1); gl.glCompileShader(id); gl.glGetShader(id, GL.GL_COMPILE_STATUS, intBuf1); boolean compiledOK = intBuf1.get(0) == GL.GL_TRUE; String infoLog = null; if (VALIDATE_SHADER || !compiledOK) { // even if compile succeeded, check // log for warnings gl.glGetShader(id, GL.GL_INFO_LOG_LENGTH, intBuf1); int length = intBuf1.get(0); if (length > 3) { // get infos infoLog = gl.glGetShaderInfoLog(id, length); } } if (compiledOK) { if (infoLog != null) { logger.log(Level.WARNING, "{0} compiled successfully, compiler warnings: \n{1}", new Object[]{source.getName(), infoLog}); } else { logger.log(Level.FINE, "{0} compiled successfully.", source.getName()); } source.clearUpdateNeeded(); } else { logger.log(Level.WARNING, "Bad compile of:\n{0}", new Object[]{ShaderDebug.formatShaderSource(stringBuf.toString())}); if (infoLog != null) { throw new RendererException("compile error in: " + source + "\n" + infoLog); } else { throw new RendererException("compile error in: " + source + "\nerror: <not provided>"); } } } public void updateShaderData(Shader shader) { int id = shader.getId(); boolean needRegister = false; if (id == -1) { // create program id = gl.glCreateProgram(); if (id == 0) { throw new RendererException("Invalid ID (" + id + ") received when trying to create shader program."); } shader.setId(id); needRegister = true; } // If using GLSL 1.5, we bind the outputs for the user // For versions 3.3 and up, user should use layout qualifiers instead. boolean bindFragDataRequired = false; for (ShaderSource source : shader.getSources()) { if (source.isUpdateNeeded()) { updateShaderSourceData(source); } if (source.getType() == ShaderType.Fragment && source.getLanguage().equals("GLSL150")) { bindFragDataRequired = true; } gl.glAttachShader(id, source.getId()); } if (bindFragDataRequired) { // Check if GLSL version is 1.5 for shader gl3.glBindFragDataLocation(id, 0, "outFragColor"); // For MRT for (int i = 0; i < limits.get(Limits.FrameBufferMrtAttachments); i++) { gl3.glBindFragDataLocation(id, i, "outFragData[" + i + "]"); } } // Link shaders to program gl.glLinkProgram(id); // Check link status gl.glGetProgram(id, GL.GL_LINK_STATUS, intBuf1); boolean linkOK = intBuf1.get(0) == GL.GL_TRUE; String infoLog = null; if (VALIDATE_SHADER || !linkOK) { gl.glGetProgram(id, GL.GL_INFO_LOG_LENGTH, intBuf1); int length = intBuf1.get(0); if (length > 3) { // get infos infoLog = gl.glGetProgramInfoLog(id, length); } } if (linkOK) { if (infoLog != null) { logger.log(Level.WARNING, "Shader linked successfully. Linker warnings: \n{0}", infoLog); } else { logger.fine("Shader linked successfully."); } shader.clearUpdateNeeded(); if (needRegister) { // Register shader for clean up if it was created in this method. objManager.registerObject(shader); statistics.onNewShader(); } else { // OpenGL spec: uniform locations may change after re-link resetUniformLocations(shader); } } else { if (infoLog != null) { throw new RendererException("Shader failed to link, shader:" + shader + "\n" + infoLog); } else { throw new RendererException("Shader failed to link, shader:" + shader + "\ninfo: <not provided>"); } } } @Override public void setShader(Shader shader) { if (shader == null) { throw new IllegalArgumentException("Shader cannot be null"); } else { if (shader.isUpdateNeeded()) { updateShaderData(shader); } // NOTE: might want to check if any of the // sources need an update? assert shader.getId() > 0; updateShaderUniforms(shader); updateShaderBufferBlocks(shader); bindProgram(shader); } } @Override public void deleteShaderSource(ShaderSource source) { if (source.getId() < 0) { logger.warning("Shader source is not uploaded to GPU, cannot delete."); return; } source.clearUpdateNeeded(); gl.glDeleteShader(source.getId()); source.resetObject(); } @Override public void deleteShader(Shader shader) { if (shader.getId() == -1) { logger.warning("Shader is not uploaded to GPU, cannot delete."); return; } for (ShaderSource source : shader.getSources()) { if (source.getId() != -1) { gl.glDetachShader(shader.getId(), source.getId()); deleteShaderSource(source); } } gl.glDeleteProgram(shader.getId()); statistics.onDeleteShader(); shader.resetObject(); } public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst) { copyFrameBuffer(src, dst, true, true); } @Override public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyDepth) { copyFrameBuffer(src, dst, true, copyDepth); } @Override public void copyFrameBuffer(FrameBuffer src, FrameBuffer dst, boolean copyColor,boolean copyDepth) { if (caps.contains(Caps.FrameBufferBlit)) { int srcX0 = 0; int srcY0 = 0; int srcX1; int srcY1; int dstX0 = 0; int dstY0 = 0; int dstX1; int dstY1; int prevFBO = context.boundFBO; if (mainFbOverride != null) { if (src == null) { src = mainFbOverride; } if (dst == null) { dst = mainFbOverride; } } if (src != null && src.isUpdateNeeded()) { updateFrameBuffer(src); } if (dst != null && dst.isUpdateNeeded()) { updateFrameBuffer(dst); } if (src == null) { glfbo.glBindFramebufferEXT(GLFbo.GL_READ_FRAMEBUFFER_EXT, 0); srcX0 = vpX; srcY0 = vpY; srcX1 = vpX + vpW; srcY1 = vpY + vpH; } else { glfbo.glBindFramebufferEXT(GLFbo.GL_READ_FRAMEBUFFER_EXT, src.getId()); srcX1 = src.getWidth(); srcY1 = src.getHeight(); } if (dst == null) { glfbo.glBindFramebufferEXT(GLFbo.GL_DRAW_FRAMEBUFFER_EXT, 0); dstX0 = vpX; dstY0 = vpY; dstX1 = vpX + vpW; dstY1 = vpY + vpH; } else { glfbo.glBindFramebufferEXT(GLFbo.GL_DRAW_FRAMEBUFFER_EXT, dst.getId()); dstX1 = dst.getWidth(); dstY1 = dst.getHeight(); } int mask = 0; if(copyColor){ mask|=GL.GL_COLOR_BUFFER_BIT; } if (copyDepth) { mask |= GL.GL_DEPTH_BUFFER_BIT; } glfbo.glBlitFramebufferEXT(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, GL.GL_NEAREST); glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, prevFBO); } else { throw new RendererException("Framebuffer blitting not supported by the video hardware"); } } private void checkFrameBufferError() { int status = glfbo.glCheckFramebufferStatusEXT(GLFbo.GL_FRAMEBUFFER_EXT); switch (status) { case GLFbo.GL_FRAMEBUFFER_COMPLETE_EXT: break; case GLFbo.GL_FRAMEBUFFER_UNSUPPORTED_EXT: //Choose different formats throw new IllegalStateException("Framebuffer object format is " + "unsupported by the video hardware."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: throw new IllegalStateException("Framebuffer has erronous attachment."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: throw new IllegalStateException("Framebuffer doesn't have any renderbuffers attached."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: throw new IllegalStateException("Framebuffer attachments must have same dimensions."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: throw new IllegalStateException("Framebuffer attachments must have same formats."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: throw new IllegalStateException("Incomplete draw buffer."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: throw new IllegalStateException("Incomplete read buffer."); case GLFbo.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT: throw new IllegalStateException("Incomplete multisample buffer."); default: //Programming error; will fail on all hardware throw new IllegalStateException("Some video driver error " + "or programming error occurred. " + "Framebuffer object status is invalid. "); } } private void updateRenderBuffer(FrameBuffer fb, RenderBuffer rb) { int id = rb.getId(); if (id == -1) { glfbo.glGenRenderbuffersEXT(intBuf1); id = intBuf1.get(0); rb.setId(id); } if (context.boundRB != id) { glfbo.glBindRenderbufferEXT(GLFbo.GL_RENDERBUFFER_EXT, id); context.boundRB = id; } int rbSize = limits.get(Limits.RenderBufferSize); if (fb.getWidth() > rbSize || fb.getHeight() > rbSize) { throw new RendererException("Resolution " + fb.getWidth() + ":" + fb.getHeight() + " is not supported."); } GLImageFormat glFmt = texUtil.getImageFormatWithError(rb.getFormat(), fb.isSrgb()); if (fb.getSamples() > 1 && caps.contains(Caps.FrameBufferMultisample)) { int samples = fb.getSamples(); int maxSamples = limits.get(Limits.FrameBufferSamples); if (maxSamples < samples) { samples = maxSamples; } glfbo.glRenderbufferStorageMultisampleEXT(GLFbo.GL_RENDERBUFFER_EXT, samples, glFmt.internalFormat, fb.getWidth(), fb.getHeight()); } else { glfbo.glRenderbufferStorageEXT(GLFbo.GL_RENDERBUFFER_EXT, glFmt.internalFormat, fb.getWidth(), fb.getHeight()); } } private int convertAttachmentSlot(int attachmentSlot) { // can also add support for stencil here if (attachmentSlot == FrameBuffer.SLOT_DEPTH) { return GLFbo.GL_DEPTH_ATTACHMENT_EXT; } else if (attachmentSlot == FrameBuffer.SLOT_DEPTH_STENCIL) { // NOTE: Using depth stencil format requires GL3, this is already // checked via render caps. return GL3.GL_DEPTH_STENCIL_ATTACHMENT; } else if (attachmentSlot < 0 || attachmentSlot >= 16) { throw new UnsupportedOperationException("Invalid FBO attachment slot: " + attachmentSlot); } return GLFbo.GL_COLOR_ATTACHMENT0_EXT + attachmentSlot; } public void updateRenderTexture(FrameBuffer fb, RenderBuffer rb) { Texture tex = rb.getTexture(); Image image = tex.getImage(); if (image.isUpdateNeeded()) { // Check NPOT requirements checkNonPowerOfTwo(tex); updateTexImageData(image, tex.getType(), 0, false); // NOTE: For depth textures, sets nearest/no-mips mode // Required to fix "framebuffer unsupported" // for old NVIDIA drivers! setupTextureParams(0, tex); } if (rb.getLayer() < 0){ glfbo.glFramebufferTexture2DEXT(GLFbo.GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), convertTextureType(tex.getType(), image.getMultiSamples(), rb.getFace()), image.getId(), rb.getLevel()); } else { glfbo.glFramebufferTextureLayerEXT(GLFbo.GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), image.getId(), rb.getLevel(), rb.getLayer()); } } public void updateFrameBufferAttachment(FrameBuffer fb, RenderBuffer rb) { boolean needAttach; if (rb.getTexture() == null) { // if it hasn't been created yet, then attach is required. needAttach = rb.getId() == -1; updateRenderBuffer(fb, rb); } else { needAttach = false; updateRenderTexture(fb, rb); } if (needAttach) { glfbo.glFramebufferRenderbufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, convertAttachmentSlot(rb.getSlot()), GLFbo.GL_RENDERBUFFER_EXT, rb.getId()); } } private void bindFrameBuffer(FrameBuffer fb) { if (fb == null) { if (context.boundFBO != 0) { glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, 0); statistics.onFrameBufferUse(null, true); context.boundFBO = 0; context.boundFB = null; } } else { assert fb.getId() != -1 && fb.getId() != 0; if (context.boundFBO != fb.getId()) { glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, fb.getId()); context.boundFBO = fb.getId(); context.boundFB = fb; statistics.onFrameBufferUse(fb, true); } else { statistics.onFrameBufferUse(fb, false); } } } public void updateFrameBuffer(FrameBuffer fb) { if (fb.getNumColorBuffers() == 0 && fb.getDepthBuffer() == null) { throw new IllegalArgumentException("The framebuffer: " + fb + "\nDoesn't have any color/depth buffers"); } int id = fb.getId(); if (id == -1) { glfbo.glGenFramebuffersEXT(intBuf1); id = intBuf1.get(0); fb.setId(id); objManager.registerObject(fb); statistics.onNewFrameBuffer(); } bindFrameBuffer(fb); FrameBuffer.RenderBuffer depthBuf = fb.getDepthBuffer(); if (depthBuf != null) { updateFrameBufferAttachment(fb, depthBuf); } for (int i = 0; i < fb.getNumColorBuffers(); i++) { FrameBuffer.RenderBuffer colorBuf = fb.getColorBuffer(i); updateFrameBufferAttachment(fb, colorBuf); } setReadDrawBuffers(fb); checkFrameBufferError(); fb.clearUpdateNeeded(); } public Vector2f[] getFrameBufferSamplePositions(FrameBuffer fb) { if (fb.getSamples() <= 1) { throw new IllegalArgumentException("Framebuffer must be multisampled"); } if (!caps.contains(Caps.TextureMultisample)) { throw new RendererException("Multisampled textures are not supported"); } setFrameBuffer(fb); Vector2f[] samplePositions = new Vector2f[fb.getSamples()]; FloatBuffer samplePos = BufferUtils.createFloatBuffer(2); for (int i = 0; i < samplePositions.length; i++) { glext.glGetMultisample(GLExt.GL_SAMPLE_POSITION, i, samplePos); samplePos.clear(); samplePositions[i] = new Vector2f(samplePos.get(0) - 0.5f, samplePos.get(1) - 0.5f); } return samplePositions; } @Override public void setMainFrameBufferOverride(FrameBuffer fb) { mainFbOverride = null; if (context.boundFBO == 0) { // Main FB is now set to fb, make sure its bound setFrameBuffer(fb); } mainFbOverride = fb; } public void setReadDrawBuffers(FrameBuffer fb) { if (gl2 == null || gl instanceof GLES_30) { return; } final int NONE = -2; final int INITIAL = -1; final int MRT_OFF = 100; if (fb == null) { // Set Read/Draw buffers to initial value. if (context.boundDrawBuf != INITIAL) { gl2.glDrawBuffer(context.initialDrawBuf); context.boundDrawBuf = INITIAL; } if (context.boundReadBuf != INITIAL) { gl2.glReadBuffer(context.initialReadBuf); context.boundReadBuf = INITIAL; } } else { if (fb.getNumColorBuffers() == 0) { // make sure to select NONE as draw buf // no color buffer attached. if (context.boundDrawBuf != NONE) { gl2.glDrawBuffer(GL.GL_NONE); context.boundDrawBuf = NONE; } if (context.boundReadBuf != NONE) { gl2.glReadBuffer(GL.GL_NONE); context.boundReadBuf = NONE; } } else { if (fb.getNumColorBuffers() > limits.get(Limits.FrameBufferAttachments)) { throw new RendererException("Framebuffer has more color " + "attachments than are supported" + " by the video hardware!"); } if (fb.isMultiTarget()) { if (!caps.contains(Caps.FrameBufferMRT)) { throw new RendererException("Multiple render targets " + " are not supported by the video hardware"); } if (fb.getNumColorBuffers() > limits.get(Limits.FrameBufferMrtAttachments)) { throw new RendererException("Framebuffer has more" + " multi targets than are supported" + " by the video hardware!"); } intBuf16.clear(); for (int i = 0; i < fb.getNumColorBuffers(); i++) { intBuf16.put(GLFbo.GL_COLOR_ATTACHMENT0_EXT + i); } intBuf16.flip(); glext.glDrawBuffers(intBuf16); context.boundDrawBuf = MRT_OFF + fb.getNumColorBuffers(); } else { RenderBuffer rb = fb.getColorBuffer(fb.getTargetIndex()); // select this draw buffer if (context.boundDrawBuf != rb.getSlot()) { gl2.glDrawBuffer(GLFbo.GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); context.boundDrawBuf = rb.getSlot(); } } } } } @Override public void setFrameBuffer(FrameBuffer fb) { if (fb == null && mainFbOverride != null) { fb = mainFbOverride; } if (context.boundFB == fb) { if (fb == null || !fb.isUpdateNeeded()) { return; } } if (!caps.contains(Caps.FrameBuffer)) { throw new RendererException("Framebuffer objects are not supported" + " by the video hardware"); } // generate mipmaps for last FB if needed if (context.boundFB != null) { for (int i = 0; i < context.boundFB.getNumColorBuffers(); i++) { RenderBuffer rb = context.boundFB.getColorBuffer(i); Texture tex = rb.getTexture(); if (tex != null && tex.getMinFilter().usesMipMapLevels()) { setTexture(0, rb.getTexture()); if (tex.getType() == Texture.Type.CubeMap) { glfbo.glGenerateMipmapEXT(GL.GL_TEXTURE_CUBE_MAP); } else { int textureType = convertTextureType(tex.getType(), tex.getImage().getMultiSamples(), rb.getFace()); glfbo.glGenerateMipmapEXT(textureType); } } } } if (fb == null) { bindFrameBuffer(null); setReadDrawBuffers(null); } else { if (fb.isUpdateNeeded()) { updateFrameBuffer(fb); } else { bindFrameBuffer(fb); setReadDrawBuffers(fb); } // update viewport to reflect framebuffer's resolution setViewPort(0, 0, fb.getWidth(), fb.getHeight()); assert fb.getId() > 0; assert context.boundFBO == fb.getId(); context.boundFB = fb; } } @Override public void readFrameBuffer(FrameBuffer fb, ByteBuffer byteBuf) { readFrameBufferWithGLFormat(fb, byteBuf, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE); } private void readFrameBufferWithGLFormat(FrameBuffer fb, ByteBuffer byteBuf, int glFormat, int dataType) { if (fb != null) { RenderBuffer rb = fb.getColorBuffer(); if (rb == null) { throw new IllegalArgumentException("Specified framebuffer" + " does not have a colorbuffer"); } setFrameBuffer(fb); if (gl2 != null) { if (context.boundReadBuf != rb.getSlot()) { gl2.glReadBuffer(GLFbo.GL_COLOR_ATTACHMENT0_EXT + rb.getSlot()); context.boundReadBuf = rb.getSlot(); } } } else { setFrameBuffer(null); } gl.glReadPixels(vpX, vpY, vpW, vpH, glFormat, dataType, byteBuf); } @Override public void readFrameBufferWithFormat(FrameBuffer fb, ByteBuffer byteBuf, Image.Format format) { GLImageFormat glFormat = texUtil.getImageFormatWithError(format, false); readFrameBufferWithGLFormat(fb, byteBuf, glFormat.format, glFormat.dataType); } private void deleteRenderBuffer(FrameBuffer fb, RenderBuffer rb) { intBuf1.put(0, rb.getId()); glfbo.glDeleteRenderbuffersEXT(intBuf1); } @Override public void deleteFrameBuffer(FrameBuffer fb) { if (fb.getId() != -1) { if (context.boundFBO == fb.getId()) { glfbo.glBindFramebufferEXT(GLFbo.GL_FRAMEBUFFER_EXT, 0); context.boundFBO = 0; } if (fb.getDepthBuffer() != null) { deleteRenderBuffer(fb, fb.getDepthBuffer()); } if (fb.getColorBuffer() != null) { deleteRenderBuffer(fb, fb.getColorBuffer()); } intBuf1.put(0, fb.getId()); glfbo.glDeleteFramebuffersEXT(intBuf1); fb.resetObject(); statistics.onDeleteFrameBuffer(); } } private int convertTextureType(Texture.Type type, int samples, int face) { if (samples > 1 && !caps.contains(Caps.TextureMultisample)) { throw new RendererException("Multisample textures are not supported" + " by the video hardware."); } switch (type) { case TwoDimensional: if (samples > 1) { return GLExt.GL_TEXTURE_2D_MULTISAMPLE; } else { return GL.GL_TEXTURE_2D; } case TwoDimensionalArray: if (!caps.contains(Caps.TextureArray)) { throw new RendererException("Array textures are not supported" + " by the video hardware."); } if (samples > 1) { return GLExt.GL_TEXTURE_2D_MULTISAMPLE_ARRAY; } else { return GLExt.GL_TEXTURE_2D_ARRAY_EXT; } case ThreeDimensional: if (!caps.contains(Caps.OpenGL20) && !caps.contains(Caps.OpenGLES30)) { throw new RendererException("3D textures are not supported" + " by the video hardware."); } return GL2.GL_TEXTURE_3D; case CubeMap: if (face < 0) { return GL.GL_TEXTURE_CUBE_MAP; } else if (face < 6) { return GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X + face; } else { throw new UnsupportedOperationException("Invalid cube map face index: " + face); } default: throw new UnsupportedOperationException("Unknown texture type: " + type); } } private int convertMagFilter(Texture.MagFilter filter) { switch (filter) { case Bilinear: return GL.GL_LINEAR; case Nearest: return GL.GL_NEAREST; default: throw new UnsupportedOperationException("Unknown mag filter: " + filter); } } private int convertMinFilter(Texture.MinFilter filter, boolean haveMips) { if (haveMips){ switch (filter) { case Trilinear: return GL.GL_LINEAR_MIPMAP_LINEAR; case BilinearNearestMipMap: return GL.GL_LINEAR_MIPMAP_NEAREST; case NearestLinearMipMap: return GL.GL_NEAREST_MIPMAP_LINEAR; case NearestNearestMipMap: return GL.GL_NEAREST_MIPMAP_NEAREST; case BilinearNoMipMaps: return GL.GL_LINEAR; case NearestNoMipMaps: return GL.GL_NEAREST; default: throw new UnsupportedOperationException("Unknown min filter: " + filter); } } else { switch (filter) { case Trilinear: case BilinearNearestMipMap: case BilinearNoMipMaps: return GL.GL_LINEAR; case NearestLinearMipMap: case NearestNearestMipMap: case NearestNoMipMaps: return GL.GL_NEAREST; default: throw new UnsupportedOperationException("Unknown min filter: " + filter); } } } private int convertWrapMode(Texture.WrapMode mode) { switch (mode) { case BorderClamp: case Clamp: case EdgeClamp: // Falldown intentional. return GL.GL_CLAMP_TO_EDGE; case Repeat: return GL.GL_REPEAT; case MirroredRepeat: return GL.GL_MIRRORED_REPEAT; default: throw new UnsupportedOperationException("Unknown wrap mode: " + mode); } } @SuppressWarnings("fallthrough") private void setupTextureParams(int unit, Texture tex) { Image image = tex.getImage(); int samples = image != null ? image.getMultiSamples() : 1; int target = convertTextureType(tex.getType(), samples, -1); if (samples > 1) { bindTextureOnly(target, image, unit); return; } boolean haveMips = true; if (image != null) { haveMips = image.isGeneratedMipmapsRequired() || image.hasMipmaps(); } LastTextureState curState = image.getLastTextureState(); if (curState.magFilter != tex.getMagFilter()) { bindTextureAndUnit(target, image, unit); gl.glTexParameteri(target, GL.GL_TEXTURE_MAG_FILTER, convertMagFilter(tex.getMagFilter())); curState.magFilter = tex.getMagFilter(); } if (curState.minFilter != tex.getMinFilter()) { bindTextureAndUnit(target, image, unit); gl.glTexParameteri(target, GL.GL_TEXTURE_MIN_FILTER, convertMinFilter(tex.getMinFilter(), haveMips)); curState.minFilter = tex.getMinFilter(); } int desiredAnisoFilter = tex.getAnisotropicFilter() == 0 ? defaultAnisotropicFilter : tex.getAnisotropicFilter(); if (caps.contains(Caps.TextureFilterAnisotropic) && curState.anisoFilter != desiredAnisoFilter) { bindTextureAndUnit(target, image, unit); gl.glTexParameterf(target, GLExt.GL_TEXTURE_MAX_ANISOTROPY_EXT, desiredAnisoFilter); curState.anisoFilter = desiredAnisoFilter; } switch (tex.getType()) { case ThreeDimensional: case CubeMap: // cubemaps use 3D coords if (gl2 != null && (caps.contains(Caps.OpenGL20) || caps.contains(Caps.OpenGLES30)) && curState.rWrap != tex.getWrap(WrapAxis.R)) { bindTextureAndUnit(target, image, unit); gl.glTexParameteri(target, GL2.GL_TEXTURE_WRAP_R, convertWrapMode(tex.getWrap(WrapAxis.R))); curState.rWrap = tex.getWrap(WrapAxis.R); } //There is no break statement on purpose here case TwoDimensional: case TwoDimensionalArray: if (curState.tWrap != tex.getWrap(WrapAxis.T)) { bindTextureAndUnit(target, image, unit); gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_T, convertWrapMode(tex.getWrap(WrapAxis.T))); image.getLastTextureState().tWrap = tex.getWrap(WrapAxis.T); } if (curState.sWrap != tex.getWrap(WrapAxis.S)) { bindTextureAndUnit(target, image, unit); gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_S, convertWrapMode(tex.getWrap(WrapAxis.S))); curState.sWrap = tex.getWrap(WrapAxis.S); } break; default: throw new UnsupportedOperationException("Unknown texture type: " + tex.getType()); } ShadowCompareMode texCompareMode = tex.getShadowCompareMode(); if ( (gl2 != null || caps.contains(Caps.OpenGLES30)) && curState.shadowCompareMode != texCompareMode) { bindTextureAndUnit(target, image, unit); if (texCompareMode != ShadowCompareMode.Off) { gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL2.GL_COMPARE_REF_TO_TEXTURE); if (texCompareMode == ShadowCompareMode.GreaterOrEqual) { gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_FUNC, GL.GL_GEQUAL); } else { gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_FUNC, GL.GL_LEQUAL); } } else { gl.glTexParameteri(target, GL2.GL_TEXTURE_COMPARE_MODE, GL.GL_NONE); } curState.shadowCompareMode = texCompareMode; } // If at this point we didn't bind the texture, bind it now bindTextureOnly(target, image, unit); } /** * Validates if a potentially NPOT texture is supported by the hardware. * <p> * Textures with power-of-2 dimensions are supported on all hardware, however * non-power-of-2 textures may or may not be supported depending on which * texturing features are used. * * @param tex The texture to validate. * @throws RendererException If the texture is not supported by the hardware */ private void checkNonPowerOfTwo(Texture tex) { if (!tex.getImage().isNPOT()) { // Texture is power-of-2, safe to use. return; } if (caps.contains(Caps.NonPowerOfTwoTextures)) { // Texture is NPOT but it is supported by video hardware. return; } // Maybe we have some / partial support for NPOT? if (!caps.contains(Caps.PartialNonPowerOfTwoTextures)) { // Cannot use any type of NPOT texture (uncommon) throw new RendererException("non-power-of-2 textures are not " + "supported by the video hardware"); } // Partial NPOT supported.. if (tex.getMinFilter().usesMipMapLevels()) { throw new RendererException("non-power-of-2 textures with mip-maps " + "are not supported by the video hardware"); } switch (tex.getType()) { case CubeMap: case ThreeDimensional: if (tex.getWrap(WrapAxis.R) != Texture.WrapMode.EdgeClamp) { throw new RendererException("repeating non-power-of-2 textures " + "are not supported by the video hardware"); } // fallthrough intentional!!! case TwoDimensionalArray: case TwoDimensional: if (tex.getWrap(WrapAxis.S) != Texture.WrapMode.EdgeClamp || tex.getWrap(WrapAxis.T) != Texture.WrapMode.EdgeClamp) { throw new RendererException("repeating non-power-of-2 textures " + "are not supported by the video hardware"); } break; default: throw new UnsupportedOperationException("unrecongized texture type"); } } private void bindTextureAndUnit(int target, Image img, int unit) { if (context.boundTextureUnit != unit) { gl.glActiveTexture(GL.GL_TEXTURE0 + unit); context.boundTextureUnit = unit; } if (context.boundTextures[unit] != img) { gl.glBindTexture(target, img.getId()); context.boundTextures[unit] = img; statistics.onTextureUse(img, true); } else { statistics.onTextureUse(img, false); } } private void bindTextureOnly(int target, Image img, int unit) { if (context.boundTextures[unit] != img) { if (context.boundTextureUnit != unit) { gl.glActiveTexture(GL.GL_TEXTURE0 + unit); context.boundTextureUnit = unit; } gl.glBindTexture(target, img.getId()); context.boundTextures[unit] = img; statistics.onTextureUse(img, true); } else { statistics.onTextureUse(img, false); } } /** * Uploads the given image to the GL driver. * * @param img The image to upload * @param type How the data in the image argument should be interpreted. * @param unit The texture slot to be used to upload the image, not important * @param scaleToPot If true, the image will be scaled to power-of-2 dimensions * before being uploaded. */ public void updateTexImageData(Image img, Texture.Type type, int unit, boolean scaleToPot) { int texId = img.getId(); if (texId == -1) { // create texture gl.glGenTextures(intBuf1); texId = intBuf1.get(0); img.setId(texId); objManager.registerObject(img); statistics.onNewTexture(); } // bind texture int target = convertTextureType(type, img.getMultiSamples(), -1); bindTextureAndUnit(target, img, unit); int imageSamples = img.getMultiSamples(); if (imageSamples <= 1) { if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired()) { // Image does not have mipmaps, but they are required. // Generate from base level. if (!caps.contains(Caps.FrameBuffer) && gl2 != null) { gl2.glTexParameteri(target, GL2.GL_GENERATE_MIPMAP, GL.GL_TRUE); img.setMipmapsGenerated(true); } else { // For OpenGL3 and up. // We'll generate mipmaps via glGenerateMipmapEXT (see below) } } else if (caps.contains(Caps.OpenGL20) || caps.contains(Caps.OpenGLES30)) { if (img.hasMipmaps()) { // Image already has mipmaps, set the max level based on the // number of mipmaps we have. gl.glTexParameteri(target, GL2.GL_TEXTURE_MAX_LEVEL, img.getMipMapSizes().length - 1); } else { // Image does not have mipmaps and they are not required. // Specify that that the texture has no mipmaps. gl.glTexParameteri(target, GL2.GL_TEXTURE_MAX_LEVEL, 0); } } } else { // Check if graphics card doesn't support multisample textures if (!caps.contains(Caps.TextureMultisample)) { throw new RendererException("Multisample textures are not supported by the video hardware"); } if (img.isGeneratedMipmapsRequired() || img.hasMipmaps()) { throw new RendererException("Multisample textures do not support mipmaps"); } if (img.getFormat().isDepthFormat()) { img.setMultiSamples(Math.min(limits.get(Limits.DepthTextureSamples), imageSamples)); } else { img.setMultiSamples(Math.min(limits.get(Limits.ColorTextureSamples), imageSamples)); } scaleToPot = false; } // Check if graphics card doesn't support depth textures if (img.getFormat().isDepthFormat() && !caps.contains(Caps.DepthTexture)) { throw new RendererException("Depth textures are not supported by the video hardware"); } if (target == GL.GL_TEXTURE_CUBE_MAP) { // Check max texture size before upload int cubeSize = limits.get(Limits.CubemapSize); if (img.getWidth() > cubeSize || img.getHeight() > cubeSize) { throw new RendererException("Cannot upload cubemap " + img + ". The maximum supported cubemap resolution is " + cubeSize); } if (img.getWidth() != img.getHeight()) { throw new RendererException("Cubemaps must have square dimensions"); } } else { int texSize = limits.get(Limits.TextureSize); if (img.getWidth() > texSize || img.getHeight() > texSize) { throw new RendererException("Cannot upload texture " + img + ". The maximum supported texture resolution is " + texSize); } } Image imageForUpload; if (scaleToPot) { imageForUpload = MipMapGenerator.resizeToPowerOf2(img); } else { imageForUpload = img; } if (target == GL.GL_TEXTURE_CUBE_MAP) { List<ByteBuffer> data = imageForUpload.getData(); if (data.size() != 6) { logger.log(Level.WARNING, "Invalid texture: {0}\n" + "Cubemap textures must contain 6 data units.", img); return; } for (int i = 0; i < 6; i++) { texUtil.uploadTexture(imageForUpload, GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, i, linearizeSrgbImages); } } else if (target == GLExt.GL_TEXTURE_2D_ARRAY_EXT) { if (!caps.contains(Caps.TextureArray)) { throw new RendererException("Texture arrays not supported by graphics hardware"); } List<ByteBuffer> data = imageForUpload.getData(); // -1 index specifies prepare data for 2D Array texUtil.uploadTexture(imageForUpload, target, -1, linearizeSrgbImages); for (int i = 0; i < data.size(); i++) { // upload each slice of 2D array in turn // this time with the appropriate index texUtil.uploadTexture(imageForUpload, target, i, linearizeSrgbImages); } } else { texUtil.uploadTexture(imageForUpload, target, 0, linearizeSrgbImages); } if (img.getMultiSamples() != imageSamples) { img.setMultiSamples(imageSamples); } if (caps.contains(Caps.FrameBuffer) || gl2 == null) { if (!img.hasMipmaps() && img.isGeneratedMipmapsRequired() && img.getData(0) != null) { glfbo.glGenerateMipmapEXT(target); img.setMipmapsGenerated(true); } } img.clearUpdateNeeded(); } @Override public void setTexture(int unit, Texture tex) { Image image = tex.getImage(); if (image.isUpdateNeeded() || (image.isGeneratedMipmapsRequired() && !image.isMipmapsGenerated())) { // Check NPOT requirements boolean scaleToPot = false; try { checkNonPowerOfTwo(tex); } catch (RendererException ex) { if (logger.isLoggable(Level.WARNING)) { int nextWidth = FastMath.nearestPowerOfTwo(tex.getImage().getWidth()); int nextHeight = FastMath.nearestPowerOfTwo(tex.getImage().getHeight()); logger.log(Level.WARNING, "Non-power-of-2 textures are not supported! Scaling texture '" + tex.getName() + "' of size " + tex.getImage().getWidth() + "x" + tex.getImage().getHeight() + " to " + nextWidth + "x" + nextHeight); } scaleToPot = true; } updateTexImageData(image, tex.getType(), unit, scaleToPot); } int texId = image.getId(); assert texId != -1; setupTextureParams(unit, tex); } /** * @deprecated Use modifyTexture(Texture2D dest, Image src, int destX, int destY, int srcX, int srcY, int areaW, int areaH) */ @Deprecated @Override public void modifyTexture(Texture tex, Image pixels, int x, int y) { setTexture(0, tex); if(caps.contains(Caps.OpenGLES20) && pixels.getFormat()!=tex.getImage().getFormat() ) { logger.log(Level.WARNING, "Incompatible texture subimage"); } int target = convertTextureType(tex.getType(), pixels.getMultiSamples(), -1); texUtil.uploadSubTexture(target,pixels, 0, x, y,0,0,pixels.getWidth(),pixels.getHeight(), linearizeSrgbImages); } /** * Copy a part of an image to a texture 2d. * @param dest The destination image, where the source will be copied * @param src The source image that contains the data to copy * @param destX First pixel of the destination image from where the src image will be drawn (x component) * @param destY First pixel of the destination image from where the src image will be drawn (y component) * @param srcX First pixel to copy (x component) * @param srcY First pixel to copy (y component) * @param areaW Width of the area to copy * @param areaH Height of the area to copy */ public void modifyTexture(Texture2D dest, Image src, int destX, int destY, int srcX, int srcY, int areaW, int areaH) { setTexture(0, dest); if(caps.contains(Caps.OpenGLES20) && src.getFormat()!=dest.getImage().getFormat() ) { logger.log(Level.WARNING, "Incompatible texture subimage"); } int target = convertTextureType(dest.getType(), src.getMultiSamples(), -1); texUtil.uploadSubTexture(target, src, 0, destX, destY, srcX, srcY, areaW, areaH, linearizeSrgbImages); } @Override public void deleteImage(Image image) { int texId = image.getId(); if (texId != -1) { intBuf1.put(0, texId); intBuf1.position(0).limit(1); gl.glDeleteTextures(intBuf1); image.resetObject(); statistics.onDeleteTexture(); } } private int convertUsage(Usage usage) { switch (usage) { case Static: return GL.GL_STATIC_DRAW; case Dynamic: return GL.GL_DYNAMIC_DRAW; case Stream: return GL.GL_STREAM_DRAW; default: throw new UnsupportedOperationException("Unknown usage type."); } } private int convertFormat(Format format) { switch (format) { case Byte: return GL.GL_BYTE; case UnsignedByte: return GL.GL_UNSIGNED_BYTE; case Short: return GL.GL_SHORT; case UnsignedShort: return GL.GL_UNSIGNED_SHORT; case Int: return GL.GL_INT; case UnsignedInt: return GL.GL_UNSIGNED_INT; case Float: return GL.GL_FLOAT; case Double: return GL.GL_DOUBLE; default: throw new UnsupportedOperationException("Unknown buffer format."); } } @Override public void updateBufferData(VertexBuffer vb) { int bufId = vb.getId(); boolean created = false; if (bufId == -1) { // create buffer gl.glGenBuffers(intBuf1); bufId = intBuf1.get(0); vb.setId(bufId); objManager.registerObject(vb); //statistics.onNewVertexBuffer(); created = true; } // bind buffer int target; if (vb.getBufferType() == VertexBuffer.Type.Index) { target = GL.GL_ELEMENT_ARRAY_BUFFER; if (context.boundElementArrayVBO != bufId) { gl.glBindBuffer(target, bufId); context.boundElementArrayVBO = bufId; //statistics.onVertexBufferUse(vb, true); } else { //statistics.onVertexBufferUse(vb, false); } } else { target = GL.GL_ARRAY_BUFFER; if (context.boundArrayVBO != bufId) { gl.glBindBuffer(target, bufId); context.boundArrayVBO = bufId; //statistics.onVertexBufferUse(vb, true); } else { //statistics.onVertexBufferUse(vb, false); } } int usage = convertUsage(vb.getUsage()); vb.getData().rewind(); switch (vb.getFormat()) { case Byte: case UnsignedByte: gl.glBufferData(target, (ByteBuffer) vb.getData(), usage); break; case Short: case UnsignedShort: gl.glBufferData(target, (ShortBuffer) vb.getData(), usage); break; case Int: case UnsignedInt: glext.glBufferData(target, (IntBuffer) vb.getData(), usage); break; case Float: gl.glBufferData(target, (FloatBuffer) vb.getData(), usage); break; default: throw new UnsupportedOperationException("Unknown buffer format."); } vb.clearUpdateNeeded(); } @Override public void updateBufferData(final BufferObject bo) { int maxSize = Integer.MAX_VALUE; final BufferObject.BufferType bufferType = bo.getBufferType(); if (!caps.contains(bufferType.getRequiredCaps())) { throw new IllegalArgumentException("The current video hardware doesn't support " + bufferType); } final ByteBuffer data = bo.computeData(maxSize); if (data == null) { throw new IllegalArgumentException("Can't upload BO without data."); } int bufferId = bo.getId(); if (bufferId == -1) { // create buffer intBuf1.clear(); gl.glGenBuffers(intBuf1); bufferId = intBuf1.get(0); bo.setId(bufferId); objManager.registerObject(bo); } data.rewind(); switch (bufferType) { case UniformBufferObject: { gl3.glBindBuffer(GL3.GL_UNIFORM_BUFFER, bufferId); gl3.glBufferData(GL4.GL_UNIFORM_BUFFER, data, GL3.GL_DYNAMIC_DRAW); gl3.glBindBuffer(GL4.GL_UNIFORM_BUFFER, 0); break; } case ShaderStorageBufferObject: { gl4.glBindBuffer(GL4.GL_SHADER_STORAGE_BUFFER, bufferId); gl4.glBufferData(GL4.GL_SHADER_STORAGE_BUFFER, data, GL4.GL_DYNAMIC_COPY); gl4.glBindBuffer(GL4.GL_SHADER_STORAGE_BUFFER, 0); break; } default: { throw new IllegalArgumentException("Doesn't support binding of " + bufferType); } } bo.clearUpdateNeeded(); } @Override public void deleteBuffer(VertexBuffer vb) { int bufId = vb.getId(); if (bufId != -1) { // delete buffer intBuf1.put(0, bufId); intBuf1.position(0).limit(1); gl.glDeleteBuffers(intBuf1); vb.resetObject(); //statistics.onDeleteVertexBuffer(); } } @Override public void deleteBuffer(final BufferObject bo) { int bufferId = bo.getId(); if (bufferId == -1) { return; } intBuf1.clear(); intBuf1.put(bufferId); intBuf1.flip(); gl.glDeleteBuffers(intBuf1); bo.resetObject(); } public void clearVertexAttribs() { IDList attribList = context.attribIndexList; for (int i = 0; i < attribList.oldLen; i++) { int idx = attribList.oldList[i]; gl.glDisableVertexAttribArray(idx); if (context.boundAttribs[idx].isInstanced()) { glext.glVertexAttribDivisorARB(idx, 0); } context.boundAttribs[idx] = null; } context.attribIndexList.copyNewToOld(); } public void setVertexAttrib(VertexBuffer vb, VertexBuffer idb) { if (vb.getBufferType() == VertexBuffer.Type.Index) { throw new IllegalArgumentException("Index buffers not allowed to be set to vertex attrib"); } if (context.boundShaderProgram <= 0) { throw new IllegalStateException("Cannot render mesh without shader bound"); } Attribute attrib = context.boundShader.getAttribute(vb.getBufferType()); int loc = attrib.getLocation(); if (loc == -1) { return; // not defined } if (loc == -2) { loc = gl.glGetAttribLocation(context.boundShaderProgram, "in" + vb.getBufferType().name()); // not really the name of it in the shader (inPosition) but // the internal name of the enum (Position). if (loc < 0) { attrib.setLocation(-1); return; // not available in shader. } else { attrib.setLocation(loc); } } if (vb.isInstanced()) { if (!caps.contains(Caps.MeshInstancing)) { throw new RendererException("Instancing is required, " + "but not supported by the " + "graphics hardware"); } } int slotsRequired = 1; if (vb.getNumComponents() > 4) { if (vb.getNumComponents() % 4 != 0) { throw new RendererException("Number of components in multi-slot " + "buffers must be divisible by 4"); } slotsRequired = vb.getNumComponents() / 4; } if (vb.isUpdateNeeded() && idb == null) { updateBufferData(vb); } VertexBuffer[] attribs = context.boundAttribs; for (int i = 0; i < slotsRequired; i++) { if (!context.attribIndexList.moveToNew(loc + i)) { gl.glEnableVertexAttribArray(loc + i); } } if (attribs[loc] != vb) { // NOTE: Use id from interleaved buffer if specified int bufId = idb != null ? idb.getId() : vb.getId(); assert bufId != -1; if (context.boundArrayVBO != bufId) { gl.glBindBuffer(GL.GL_ARRAY_BUFFER, bufId); context.boundArrayVBO = bufId; //statistics.onVertexBufferUse(vb, true); } else { //statistics.onVertexBufferUse(vb, false); } if (slotsRequired == 1) { gl.glVertexAttribPointer(loc, vb.getNumComponents(), convertFormat(vb.getFormat()), vb.isNormalized(), vb.getStride(), vb.getOffset()); } else { for (int i = 0; i < slotsRequired; i++) { // The pointer maps the next 4 floats in the slot. // stride = 4 bytes in float * 4 floats in slot * num slots // offset = 4 bytes in float * 4 floats in slot * slot index gl.glVertexAttribPointer(loc + i, 4, convertFormat(vb.getFormat()), vb.isNormalized(), 4 * 4 * slotsRequired, 4 * 4 * i); } } for (int i = 0; i < slotsRequired; i++) { int slot = loc + i; if (vb.isInstanced() && (attribs[slot] == null || !attribs[slot].isInstanced())) { // non-instanced -> instanced glext.glVertexAttribDivisorARB(slot, vb.getInstanceSpan()); } else if (!vb.isInstanced() && attribs[slot] != null && attribs[slot].isInstanced()) { // instanced -> non-instanced glext.glVertexAttribDivisorARB(slot, 0); } attribs[slot] = vb; } } } public void setVertexAttrib(VertexBuffer vb) { setVertexAttrib(vb, null); } public void drawTriangleArray(Mesh.Mode mode, int count, int vertCount) { boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); if (useInstancing) { glext.glDrawArraysInstancedARB(convertElementMode(mode), 0, vertCount, count); } else { gl.glDrawArrays(convertElementMode(mode), 0, vertCount); } } public void drawTriangleList(VertexBuffer indexBuf, Mesh mesh, int count) { if (indexBuf.getBufferType() != VertexBuffer.Type.Index) { throw new IllegalArgumentException("Only index buffers are allowed as triangle lists."); } switch (indexBuf.getFormat()) { case UnsignedByte: case UnsignedShort: // OK: Works on all platforms. break; case UnsignedInt: // Requires extension on OpenGL ES 2. if (!caps.contains(Caps.IntegerIndexBuffer)) { throw new RendererException("32-bit index buffers are not supported by the video hardware"); } break; default: // What is this? throw new RendererException("Unexpected format for index buffer: " + indexBuf.getFormat()); } if (indexBuf.isUpdateNeeded()) { updateBufferData(indexBuf); } int bufId = indexBuf.getId(); assert bufId != -1; if (context.boundElementArrayVBO != bufId) { gl.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, bufId); context.boundElementArrayVBO = bufId; //statistics.onVertexBufferUse(indexBuf, true); } else { //statistics.onVertexBufferUse(indexBuf, true); } int vertCount = mesh.getVertexCount(); boolean useInstancing = count > 1 && caps.contains(Caps.MeshInstancing); if (mesh.getMode() == Mode.Hybrid) { int[] modeStart = mesh.getModeStart(); int[] elementLengths = mesh.getElementLengths(); int elMode = convertElementMode(Mode.Triangles); int fmt = convertFormat(indexBuf.getFormat()); int elSize = indexBuf.getFormat().getComponentSize(); int listStart = modeStart[0]; int stripStart = modeStart[1]; int fanStart = modeStart[2]; int curOffset = 0; for (int i = 0; i < elementLengths.length; i++) { if (i == stripStart) { elMode = convertElementMode(Mode.TriangleStrip); } else if (i == fanStart) { elMode = convertElementMode(Mode.TriangleFan); } int elementLength = elementLengths[i]; if (useInstancing) { glext.glDrawElementsInstancedARB(elMode, elementLength, fmt, curOffset, count); } else { gl.glDrawRangeElements(elMode, 0, vertCount, elementLength, fmt, curOffset); } curOffset += elementLength * elSize; } } else { if (useInstancing) { glext.glDrawElementsInstancedARB(convertElementMode(mesh.getMode()), indexBuf.getData().limit(), convertFormat(indexBuf.getFormat()), 0, count); } else { gl.glDrawRangeElements(convertElementMode(mesh.getMode()), 0, vertCount, indexBuf.getData().limit(), convertFormat(indexBuf.getFormat()), 0); } } } public int convertElementMode(Mesh.Mode mode) { switch (mode) { case Points: return GL.GL_POINTS; case Lines: return GL.GL_LINES; case LineLoop: return GL.GL_LINE_LOOP; case LineStrip: return GL.GL_LINE_STRIP; case Triangles: return GL.GL_TRIANGLES; case TriangleFan: return GL.GL_TRIANGLE_FAN; case TriangleStrip: return GL.GL_TRIANGLE_STRIP; case Patch: return GL4.GL_PATCHES; default: throw new UnsupportedOperationException("Unrecognized mesh mode: " + mode); } } public void updateVertexArray(Mesh mesh, VertexBuffer instanceData) { int id = mesh.getId(); if (id == -1) { IntBuffer temp = intBuf1; gl3.glGenVertexArrays(temp); id = temp.get(0); mesh.setId(id); } if (context.boundVertexArray != id) { gl3.glBindVertexArray(id); context.boundVertexArray = id; } VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); if (interleavedData != null && interleavedData.isUpdateNeeded()) { updateBufferData(interleavedData); } if (instanceData != null) { setVertexAttrib(instanceData, null); } for (VertexBuffer vb : mesh.getBufferList().getArray()) { if (vb.getBufferType() == Type.InterleavedData || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers || vb.getBufferType() == Type.Index) { continue; } if (vb.getStride() == 0) { // not interleaved setVertexAttrib(vb); } else { // interleaved setVertexAttrib(vb, interleavedData); } } } private void renderMeshVertexArray(Mesh mesh, int lod, int count, VertexBuffer instanceData) { if (mesh.getId() == -1) { updateVertexArray(mesh, instanceData); } else { // TODO: Check if it was updated } if (context.boundVertexArray != mesh.getId()) { gl3.glBindVertexArray(mesh.getId()); context.boundVertexArray = mesh.getId(); } // IntMap<VertexBuffer> buffers = mesh.getBuffers(); VertexBuffer indices; if (mesh.getNumLodLevels() > 0) { indices = mesh.getLodLevel(lod); } else { indices = mesh.getBuffer(Type.Index); } if (indices != null) { drawTriangleList(indices, mesh, count); } else { drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount()); } clearVertexAttribs(); } private void renderMeshDefault(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { // Here while count is still passed in. Can be removed when/if // the method is collapsed again. -pspeed count = Math.max(mesh.getInstanceCount(), count); VertexBuffer interleavedData = mesh.getBuffer(Type.InterleavedData); if (interleavedData != null && interleavedData.isUpdateNeeded()) { updateBufferData(interleavedData); } VertexBuffer indices; if (mesh.getNumLodLevels() > 0) { indices = mesh.getLodLevel(lod); } else { indices = mesh.getBuffer(Type.Index); } if (instanceData != null) { for (VertexBuffer vb : instanceData) { setVertexAttrib(vb, null); } } for (VertexBuffer vb : mesh.getBufferList().getArray()) { if (vb.getBufferType() == Type.InterleavedData || vb.getUsage() == Usage.CpuOnly // ignore cpu-only buffers || vb.getBufferType() == Type.Index) { continue; } if (vb.getStride() == 0) { // not interleaved setVertexAttrib(vb); } else { // interleaved setVertexAttrib(vb, interleavedData); } } clearVertexAttribs(); if (indices != null) { drawTriangleList(indices, mesh, count); } else { drawTriangleArray(mesh.getMode(), count, mesh.getVertexCount()); } } @Override public void renderMesh(Mesh mesh, int lod, int count, VertexBuffer[] instanceData) { if (mesh.getVertexCount() == 0 || mesh.getTriangleCount() == 0 || count == 0) { return; } if (count > 1 && !caps.contains(Caps.MeshInstancing)) { throw new RendererException("Mesh instancing is not supported by the video hardware"); } if (mesh.getLineWidth() != 1f && context.lineWidth != mesh.getLineWidth()) { gl.glLineWidth(mesh.getLineWidth()); context.lineWidth = mesh.getLineWidth(); } if (gl4 != null && mesh.getMode().equals(Mode.Patch)) { gl4.glPatchParameter(mesh.getPatchVertexCount()); } statistics.onMeshDrawn(mesh, lod, count); // if (ctxCaps.GL_ARB_vertex_array_object){ // renderMeshVertexArray(mesh, lod, count); // }else{ renderMeshDefault(mesh, lod, count, instanceData); } @Override public void setMainFrameBufferSrgb(boolean enableSrgb) { // Gamma correction if (!caps.contains(Caps.Srgb) && enableSrgb) { // Not supported, sorry. logger.warning("sRGB framebuffer is not supported " + "by video hardware, but was requested."); return; } setFrameBuffer(null); if (enableSrgb) { if (!getBoolean(GLExt.GL_FRAMEBUFFER_SRGB_CAPABLE_EXT)) { logger.warning("Driver claims that default framebuffer " + "is not sRGB capable. Enabling anyway."); } gl.glEnable(GLExt.GL_FRAMEBUFFER_SRGB_EXT); logger.log(Level.FINER, "SRGB FrameBuffer enabled (Gamma Correction)"); } else { gl.glDisable(GLExt.GL_FRAMEBUFFER_SRGB_EXT); } } @Override public void setLinearizeSrgbImages(boolean linearize) { if (caps.contains(Caps.Srgb)) { linearizeSrgbImages = linearize; } } @Override public int[] generateProfilingTasks(int numTasks) { IntBuffer ids = BufferUtils.createIntBuffer(numTasks); gl.glGenQueries(numTasks, ids); return BufferUtils.getIntArray(ids); } @Override public void startProfiling(int taskId) { gl.glBeginQuery(GL.GL_TIME_ELAPSED, taskId); } @Override public void stopProfiling() { gl.glEndQuery(GL.GL_TIME_ELAPSED); } @Override public long getProfilingTime(int taskId) { return gl.glGetQueryObjectui64(taskId, GL.GL_QUERY_RESULT); } @Override public boolean isTaskResultAvailable(int taskId) { return gl.glGetQueryObjectiv(taskId, GL.GL_QUERY_RESULT_AVAILABLE) == 1; } @Override public boolean getAlphaToCoverage() { if (caps.contains(Caps.Multisample)) { return gl.glIsEnabled(GLExt.GL_SAMPLE_ALPHA_TO_COVERAGE_ARB); } return false; } @Override public int getDefaultAnisotropicFilter() { return this.defaultAnisotropicFilter; } }
package org.uma.jmetal.util; import org.uma.jmetal.solution.DoubleSolution; import org.uma.jmetal.solution.Solution; import org.uma.jmetal.util.pseudorandom.JMetalRandom; import org.uma.jmetal.util.pseudorandom.RandomGenerator; import java.util.Comparator; import java.util.List; import java.util.function.BinaryOperator; public class SolutionUtils { /** * Return the best solution between those passed as arguments. If they are equal or incomparable * one of them is chosen randomly. * @param solution1 * @param solution2 * @return The best solution */ public static <S extends Solution<?>> S getBestSolution(S solution1, S solution2, Comparator<S> comparator) { return getBestSolution(solution1, solution2, comparator, () -> JMetalRandom.getInstance().nextDouble()); } /** * Return the best solution between those passed as arguments. If they are equal or incomparable * one of them is chosen randomly. * @param solution1 * @param solution2 * @param randomGenerator {@link RandomGenerator} for the equality case * @return The best solution */ public static <S extends Solution<?>> S getBestSolution(S solution1, S solution2, Comparator<S> comparator, RandomGenerator<Double> randomGenerator) { return getBestSolution(solution1, solution2, comparator, (a, b) -> randomGenerator.getRandomValue() < 0.5 ? a : b); } /** * Return the best solution between those passed as arguments. If they are equal or incomparable * one of them is chosen based on the given policy. * @param solution1 * @param solution2 * @param equalityPolicy * @return The best solution */ public static <S extends Solution<?>> S getBestSolution(S solution1, S solution2, Comparator<S> comparator, BinaryOperator<S> equalityPolicy) { S result ; int flag = comparator.compare(solution1, solution2); if (flag == -1) { result = solution1; } else if (flag == 1) { result = solution2; } else { result = equalityPolicy.apply(solution1, solution2); } return result ; } /** * Returns the euclidean distance between a pair of solutions in the objective space * @param firstSolution * @param secondSolution * @return */ static <S extends Solution<?>> double distanceBetweenObjectives(S firstSolution, S secondSolution) { double diff; double distance = 0.0; //euclidean distance for (int nObj = 0; nObj < firstSolution.getNumberOfObjectives();nObj++){ diff = firstSolution.getObjective(nObj) - secondSolution.getObjective(nObj); distance += Math.pow(diff,2.0); } // for return Math.sqrt(distance); } /** Returns the minimum distance from a <code>Solution</code> to a * <code>SolutionSet according to the encodings.variable values</code>. * @param solution The <code>Solution</code>. * @param solutionList The <code>List<Solution></></code>. * @return The minimum distance between solution and the set. */ public static double distanceToSolutionListInSolutionSpace(DoubleSolution solution, List<DoubleSolution> solutionList){ //At start point the distance is the max double distance = Double.MAX_VALUE; // found the min distance respect to population for (int i = 0; i < solutionList.size();i++){ double aux = distanceBetweenSolutions(solution,solutionList.get(i)); if (aux < distance) distance = aux; } // for //->Return the best distance return distance; } // distanceToSolutionSetInSolutionSpace /** Returns the distance between two solutions in the search space. * @param solutionI The first <code>Solution</code>. * @param solutionJ The second <code>Solution</code>. * @return the distance between solutions. */ public static double distanceBetweenSolutions(DoubleSolution solutionI, DoubleSolution solutionJ) { double distance = 0.0; double diff; //Auxiliar var //-> Calculate the Euclidean distance for (int i = 0; i < solutionI.getNumberOfVariables() ; i++){ diff = solutionI.getVariableValue(i) - solutionJ.getVariableValue(i); distance += Math.pow(diff,2.0); } // for //-> Return the euclidean distance return Math.sqrt(distance); } // distanceBetweenSolutions }
package jsprit.core.problem.io; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.VehicleRoutingProblem.Builder; import jsprit.core.problem.io.VrpXMLReader; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.solution.route.activity.DeliverShipment; import jsprit.core.problem.solution.route.activity.PickupService; import jsprit.core.problem.solution.route.activity.PickupShipment; import jsprit.core.problem.solution.route.activity.TourActivity; import org.junit.Test; public class ReaderTest { @Test public void testRead_ifReaderIsCalled_itReadsSuccessfully(){ new VrpXMLReader(VehicleRoutingProblem.Builder.newInstance(), new ArrayList<VehicleRoutingProblemSolution>()).read("src/test/resources/lui-shen-solution.xml"); } @Test public void testRead_ifReaderIsCalled_itReadsSuccessfullyV2(){ Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); ArrayList<VehicleRoutingProblemSolution> solutions = new ArrayList<VehicleRoutingProblemSolution>(); new VrpXMLReader(vrpBuilder, solutions).read("src/test/resources/finiteVrpWithShipmentsAndSolution.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); assertEquals(3,vrp.getJobs().size()); assertEquals(1,solutions.size()); assertEquals(1,solutions.get(0).getRoutes().size()); List<TourActivity> activities = solutions.get(0).getRoutes().iterator().next().getTourActivities().getActivities(); assertEquals(4,activities.size()); assertTrue(activities.get(0) instanceof PickupService); assertTrue(activities.get(1) instanceof PickupService); assertTrue(activities.get(2) instanceof PickupShipment); assertTrue(activities.get(3) instanceof DeliverShipment); } }
package net.md_5.bungee; /** * Class to rewrite integers within packets. */ public class EntityMap { public final static int[][] entityIds = new int[ 256 ][]; static { entityIds[0x05] = new int[] { 1 }; entityIds[0x07] = new int[] { 1, 5 }; entityIds[0x11] = new int[] { 1 }; entityIds[0x12] = new int[] { 1 }; entityIds[0x13] = new int[] { 1 }; entityIds[0x14] = new int[] { 1 }; entityIds[0x16] = new int[] { 1, 5 }; entityIds[0x17] = new int[] { 1 }; entityIds[0x18] = new int[] { 1 }; entityIds[0x19] = new int[] { 1 }; entityIds[0x1A] = new int[] { 1 }; entityIds[0x1C] = new int[] { 1 }; entityIds[0x1E] = new int[] { 1 }; entityIds[0x1F] = new int[] { 1 }; entityIds[0x20] = new int[] { 1 }; entityIds[0x21] = new int[] { 1 }; entityIds[0x22] = new int[] { 1 }; entityIds[0x23] = new int[] { 1 }; entityIds[0x26] = new int[] { 1 }; entityIds[0x27] = new int[] { 1, 5 }; entityIds[0x28] = new int[] { 1 }; entityIds[0x29] = new int[] { 1 }; entityIds[0x2A] = new int[] { 1 }; entityIds[0x37] = new int[] { 1 }; entityIds[0x47] = new int[] { 1 }; } public static void rewrite(byte[] packet, int oldId, int newId) { int packetId = packet[0] & 0xFF; if ( packetId == 0x1D ) { // bulk entity for ( int pos = 2; pos < packet.length; pos += 4 ) { int readId = readInt( packet, pos ); if ( readId == oldId ) { setInt( packet, pos, newId ); } else if ( readId == newId ) { setInt( packet, pos, oldId ); } } } else { int[] idArray = entityIds[packetId]; if ( idArray != null ) { for ( int pos : idArray ) { int readId = readInt( packet, pos ); if ( readId == oldId ) { setInt( packet, pos, newId ); } else if ( readId == newId ) { setInt( packet, pos, oldId ); } } } } if ( packetId == 0x17 ) { int type = packet[5] & 0xFF; if ( type == 60 || type == 90 ) { if ( readInt( packet, 20 ) == oldId ) { setInt( packet, 20, newId ); } } } } private static void setInt(byte[] buf, int pos, int i) { buf[pos] = (byte) ( i >> 24 ); buf[pos + 1] = (byte) ( i >> 16 ); buf[pos + 2] = (byte) ( i >> 8 ); buf[pos + 3] = (byte) i; } private static int readInt(byte[] buf, int pos) { return ( ( ( buf[pos] & 0xFF ) << 24 ) | ( ( buf[pos + 1] & 0xFF ) << 16 ) | ( ( buf[pos + 2] & 0xFF ) << 8 ) | buf[pos + 3] & 0xFF ); } }
package org.vosao.search.impl; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vosao.business.Business; import org.vosao.business.mq.message.IndexMessage; import org.vosao.common.VosaoContext; import org.vosao.dao.Dao; import org.vosao.entity.LanguageEntity; import org.vosao.search.Hit; import org.vosao.search.SearchEngine; import org.vosao.search.SearchIndex; import org.vosao.search.SearchResult; import org.vosao.search.SearchResultFilter; import org.vosao.utils.ListUtil; import org.vosao.utils.StreamUtil; /** * * @author Alexander Oleynik * */ public class SearchEngineImpl implements SearchEngine { private static final Log logger = LogFactory.getLog( SearchEngineImpl.class); private Map<String, SearchIndex> indexes; private SearchIndex getSearchIndex(String language) { if (indexes == null) { indexes = new HashMap<String, SearchIndex>(); } if (!indexes.containsKey(language)) { indexes.put(language, new SearchIndexImpl(language)); } return indexes.get(language); } @Override public void reindex() { for (LanguageEntity language : getDao().getLanguageDao().select()) { getSearchIndex(language.getCode()).clear(); try { getSearchIndex(language.getCode()).saveIndex(); } catch (IOException e) { logger.error(StreamUtil.getStackTrace(e)); } } getBusiness().getMessageQueue().publish(new IndexMessage()); } @Override public SearchResult search(SearchResultFilter filter, String query, int start, int count, String language, int textSize) { // Search in language index first for all results logger.info("into engine.search : language = " + language); List<Hit> hits = getSearchIndex(language).search(filter, query, textSize); // Search in all other languages for all results for (LanguageEntity lang : getDao().getLanguageDao().select()) { if (!lang.getCode().equals(language)) { logger.info("Searching in " + lang.getCode()); hits.addAll(getSearchIndex(lang.getCode()).search(filter, query, textSize)); } } // paginate result and return SearchResult result = new SearchResult(); logger.info("Number of hits = " + hits.size()); result.setCount(hits.size()); int startIndex = start < hits.size() ? start : hits.size(); int endIndex = startIndex + count; if (count == -1) { endIndex = hits.size(); } if (endIndex > hits.size()) { endIndex = hits.size(); } result.setHits(ListUtil.slice(hits, startIndex, count)); logger.info("out of engine.search"); return result; } @Override public void updateIndex(Long pageId) throws IOException { for (LanguageEntity language : getDao().getLanguageDao().select()) { getSearchIndex(language.getCode()).updateIndex(pageId); } } @Override public void removeFromIndex(Long pageId) { for (LanguageEntity language : getDao().getLanguageDao().select()) { getSearchIndex(language.getCode()).removeFromIndex(pageId); } } @Override public void saveIndex() throws IOException { for (LanguageEntity language : getDao().getLanguageDao().select()) { getSearchIndex(language.getCode()).saveIndex(); } } private Business getBusiness() { return VosaoContext.getInstance().getBusiness(); } private Dao getDao() { return getBusiness().getDao(); } }
package hex.tree.drf; import hex.genmodel.GenModel; import hex.tree.SharedTreeModel; import water.Key; import water.fvec.Chunk; import water.util.MathUtils; import water.util.SB; public class DRFModel extends SharedTreeModel<DRFModel,DRFModel.DRFParameters,DRFModel.DRFOutput> { public static class DRFParameters extends SharedTreeModel.SharedTreeParameters { int _mtries = -1; float _sample_rate = 0.632f; public boolean _build_tree_one_node = false; public DRFParameters() { super(); // Set DRF-specific defaults (can differ from SharedTreeModel's defaults) _ntrees = 50; _max_depth = 20; _min_rows = 10; } } public static class DRFOutput extends SharedTreeModel.SharedTreeOutput { public DRFOutput( DRF b, double mse_train, double mse_valid ) { super(b,mse_train,mse_valid); } } public DRFModel(Key selfKey, DRFParameters parms, DRFOutput output ) { super(selfKey,parms,output); } /** Bulk scoring API for one row. Chunks are all compatible with the model, * and expect the last Chunks are for the final distribution and prediction. * Default method is to just load the data into the tmp array, then call * subclass scoring logic. */ @Override public double[] score0( Chunk chks[], int row_in_chunk, double[] tmp, double[] preds ) { assert chks.length>=tmp.length; for( int i=0; i<tmp.length; i++ ) tmp[i] = chks[i].atd(row_in_chunk); return score0(tmp,preds); } @Override protected double[] score0(double data[], double preds[]) { super.score0(data, preds); int N = _parms._ntrees; if (_output.nclasses() == 1) { // regression - compute avg over all trees preds[0] /= N; return preds; } else { // classification if (_output.nclasses() == 2) { preds[1] /= N; //average probability preds[2] = 1. - preds[1]; } else { double sum = MathUtils.sum(preds); if (sum > 0) MathUtils.div(preds, sum); } if (_parms._balance_classes) GenModel.correctProbabilities(preds, _output._priorClassDist, _output._modelClassDist); preds[0] = hex.genmodel.GenModel.getPrediction(preds, data, defaultThreshold()); } return preds; } @Override protected void toJavaUnifyPreds(SB body, SB file) { if (_output.nclasses() == 1) { // Regression body.ip("preds[0] /= " + _output._ntrees + ";").nl(); } else { // Classification if( _output.nclasses()==2 ) { // Kept the initial prediction for binomial body.ip("preds[1] /= " + _output._ntrees + ";").nl(); body.ip("preds[2] = 1.0 - preds[1];").nl(); } else { body.ip("double sum = 0;").nl(); body.ip("for(int i=1; i<preds.length; i++) { sum += preds[i]; }").nl(); body.ip("if (sum>0) for(int i=1; i<preds.length; i++) { preds[i] /= sum; }").nl(); } if (_parms._balance_classes) body.ip("hex.genmodel.GenModel.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl(); body.ip("preds[0] = hex.genmodel.GenModel.getPrediction(preds, data, " + defaultThreshold() + " );").nl(); } } }
package com.google.maps.android.quadtree; import com.google.maps.android.geometry.Bounds; import com.google.maps.android.geometry.Point; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class LinearQuadTree<T extends LinearQuadTree.Item> implements QuadTree<T> { private class Node implements Comparable<Node> { public final int base = 4; public int location; public T t; public Node(T item) { location = getLocation(item.getPoint()); this.t = item; } private int getLocation(Point p) { int location = 0; Bounds currBounds = mBounds; for (int currPrecision = mPrecision-1; currPrecision >= 0; currPrecision if (p.y < currBounds.midY) { // top if (p.x < currBounds.midX) { // left = 0 currBounds = new Bounds(currBounds.minX, currBounds.midX, currBounds.minY, currBounds.midY); } else { // right = 1 location += 1 * base^currPrecision; currBounds = new Bounds(currBounds.midX, currBounds.maxX, currBounds.minY, currBounds.midY); } } else { // bottom if (p.x < currBounds.midX) { // left = 2 location += 2 * base^currPrecision; currBounds = new Bounds(currBounds.minX, currBounds.midX, currBounds.midY, currBounds.maxY); } else { // right = 3 location += 3 * base^currPrecision; currBounds = new Bounds(currBounds.midX, currBounds.maxX, currBounds.midY, currBounds.maxY); } } } return location; } public int compareTo(Node node) { return this.location - node.location; } } /** * The bounds of this quad. */ private final Bounds mBounds; private ArrayList<Node> mPoints; public int mPrecision; /** * Creates a new quad tree with specified bounds. * * @param minX * @param maxX * @param minY * @param maxY */ public LinearQuadTree(double minX, double maxX, double minY, double maxY, int precision) { this(new Bounds(minX, maxX, minY, maxY), precision); } public LinearQuadTree(Bounds bounds, int precision) { if (precision > 25) precision = 25; // arbitrary maximum precision if (precision < 3) precision = 3; // arbitrary minimum precision mPoints = new ArrayList<Node>(); mBounds = bounds; mPrecision = precision; } @Override public void add(T item) { Node node = new Node(item); int index = Collections.binarySearch(mPoints, node); mPoints.add(index, node); } @Override public boolean remove(T item) { Node node = new Node(item); return mPoints.remove(node); } @Override public void clear() { mPoints.clear(); } @Override public Collection<T> search(Bounds searchBounds) { Collection<T> collection = new ArrayList<T>(); // TODO: write the actual search return collection; } }
package com.jme3.gde.core.assets; import com.jme3.asset.AssetKey; import java.io.BufferedOutputStream; import java.io.BufferedInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.cookies.SaveCookie; import org.openide.filesystems.FileAlreadyLockedException; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Exceptions; import org.openide.util.Mutex; import org.openide.util.Mutex.Action; /** * Global object to access actual jME3 data within an AssetDataObject, available * through the Lookup of any AssetDataObject. AssetDataObjects that wish to use * * @author normenhansen */ @SuppressWarnings("unchecked") public class AssetData { private static final Logger logger = Logger.getLogger(AssetData.class.getName()); private final Mutex propsMutex = new Mutex(); private final Properties props = new Properties(); private AssetDataObject file; private String extension = "jmpdata"; private Date lastLoaded; public AssetData(AssetDataObject file) { this.file = file; FileObject primaryFile = file.getPrimaryFile(); if (primaryFile != null) { extension = primaryFile.getExt() + "data"; } } public AssetData(AssetDataObject file, String extension) { this.file = file; this.extension = extension; } public void setExtension(String extension) { this.extension = extension; } public AssetKey<?> getAssetKey() { return file.getAssetKey(); } public void setAssetKey(AssetKey key) { file.setAssetKeyData(key); } public void setModified(boolean modified) { file.setModified(modified); } public void setSaveCookie(SaveCookie cookie) { file.setSaveCookie(cookie); } public Object loadAsset() { return file.loadAsset(); } public void saveAsset() throws IOException { file.saveAsset(); } public void closeAsset() { file.closeAsset(); } public List<FileObject> getAssetList() { return file.getAssetList(); } public List<AssetKey> getAssetKeyList() { return file.getAssetKeyList(); } public List<AssetKey> getFailedList() { return file.getFailedList(); } public synchronized String getProperty(final String key) { readProperties(); return propsMutex.readAccess(new Action<String>() { public String run() { return props.getProperty(key); } }); } public synchronized String getProperty(final String key, final String defaultValue) { readProperties(); return propsMutex.readAccess(new Action<String>() { public String run() { return props.getProperty(key, defaultValue); } }); } public synchronized String setProperty(final String key, final String value) { readProperties(); String ret = propsMutex.writeAccess(new Action<String>() { public String run() { String ret = (String) props.setProperty(key, value); return ret; } }); writeProperties(); return ret; } @Deprecated public void loadProperties() { } @Deprecated public void saveProperties() throws FileAlreadyLockedException, IOException { } private void readProperties() { propsMutex.writeAccess(new Runnable() { public void run() { final FileObject myFile = FileUtil.findBrother(file.getPrimaryFile(), extension); if (myFile == null) { return; } final Date lastMod = myFile.lastModified(); if (!lastMod.equals(lastLoaded)) { props.clear(); lastLoaded = lastMod; InputStream in = null; try { in = new BufferedInputStream(myFile.getInputStream()); try { props.load(in); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } catch (FileNotFoundException ex) { Exceptions.printStackTrace(ex); } finally { try { in.close(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } logger.log(Level.INFO, "Read AssetData properties for {0}", file); } } }); } private void writeProperties() { //writeAccess because we write lastMod date, not because we write to the file //the mutex protects the properties object, not the file propsMutex.writeAccess(new Runnable() { public void run() { OutputStream out = null; FileLock lock = null; try { FileObject pFile = file.getPrimaryFile(); FileObject myFile = FileUtil.findBrother(pFile, extension); if (myFile == null) { myFile = FileUtil.createData(pFile.getParent(), pFile.getName() + "." + extension); } lock = myFile.lock(); out = new BufferedOutputStream(myFile.getOutputStream(lock)); props.store(out, ""); out.flush(); lastLoaded = myFile.lastModified(); logger.log(Level.INFO, "Written AssetData properties for {0}", file); } catch (IOException e) { Exceptions.printStackTrace(e); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } if (lock != null) { lock.releaseLock(); } } } }); } }
package cn.ycoder.android.library; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; import com.alibaba.android.arouter.facade.annotation.Route; import java.util.HashMap; import java.util.Map; import cn.ycoder.android.library.route.RouteUtil; import cn.ycoder.android.library.tool.ClipboardUtils; import cn.ycoder.android.library.tool.ToastUtils; import cn.ycoder.android.library.widget.NumberProgressBar; import cn.ycoder.android.library.widget.ObservableWebView; /** * @author * @created at 2017/5/3 14:28 */ @Route(path = RouteUtil.URI_APP_WEB_BROWSER) public class WebActivity extends ToolbarActivity implements ObservableWebView.OnScrollChangedListener { private static final String TAG = WebActivity.class.getSimpleName(); protected static final String EXTRA_URL = "extra_url"; protected static final String EXTRA_TITLE = "extra_title"; protected static final Map<String, Integer> URL_POSITION_CACHES = new HashMap<>(); NumberProgressBar progressbar; ObservableWebView webView; TextSwitcher textSwitcher; String url, title; int positionHolder; boolean overrideTitleEnabled = true; /** * Using newIntent trick, return WebActivity Intent, to avoid `public static` * constant * variable everywhere * * @return Intent to start WebActivity */ public static Intent newIntent(Context context, String extraTitle, String extraURL) { Intent intent = new Intent(context, WebActivity.class); intent.putExtra(EXTRA_TITLE, extraTitle); intent.putExtra(EXTRA_URL, extraURL); return intent; } @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { overridePendingTransition(0, 0); super.onCreate(savedInstanceState); setContentView(R.layout.yy_library_act_web); progressbar = (NumberProgressBar) findViewById(R.id.progressbar); webView = (ObservableWebView) findViewById(R.id.web_view); textSwitcher = (TextSwitcher) findViewById(R.id.title); url = getIntent().getStringExtra(EXTRA_URL); title = getIntent().getStringExtra(EXTRA_TITLE); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); settings.setLoadWithOverviewMode(true); settings.setAppCacheEnabled(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); settings.setSupportZoom(true); settings.setDomStorageEnabled(true); webView.setWebChromeClient(new ChromeClient()); webView.setWebViewClient(new ReloadableClient()); webView.setOnScrollChangedListener(this); // webView.addJavascriptInterface(new JSInterface(), "JSInterface"); webView.loadUrl(url); textSwitcher.setFactory(new ViewSwitcher.ViewFactory() { @SuppressWarnings("deprecation") @Override public View makeView() { final Context context = WebActivity.this; final TextView textView = new TextView(context); textView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); textView.setTextAppearance(context, R.style.WebTitle); textView.setSingleLine(true); textView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); TypedValue value = new TypedValue(); if (context.getTheme().resolveAttribute(R.attr.toolbarTitleSize, value, true)) { int titleSize = TypedValue .complexToDimensionPixelSize(value.data, context.getResources().getDisplayMetrics()); textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, titleSize); } if (context.getTheme().resolveAttribute(R.attr.titleTextColor, value, true)) { textView.setTextColor(ContextCompat.getColor(getBaseContext(), value.resourceId)); } textView.setEllipsize(TextUtils.TruncateAt.MARQUEE); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { v.setSelected(!v.isSelected()); } }); return textView; } }); textSwitcher.setInAnimation(this, android.R.anim.fade_in); textSwitcher.setOutAnimation(this, android.R.anim.fade_out); if (title != null) { setTitle(title); } } public void setOverrideTitleEnabled(boolean enabled) { this.overrideTitleEnabled = enabled; } @Override public void setTitle(CharSequence title) { super.setTitle(title); textSwitcher.setText(title); } private void refresh() { webView.reload(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (webView.canGoBack()) { webView.goBack(); } else { finish(); } return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_web, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_refresh) { refresh(); return true; } else if (id == R.id.action_copy_url) { ClipboardUtils.copyText(webView.getUrl()); ToastUtils.showShort(R.string.tip_web_copy_done); return true; } else if (id == R.id.action_open_url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { ToastUtils.showLong(R.string.tip_web_open_fail); } return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("deprecation") @Override protected void onDestroy() { final String url = webView.getUrl(); int bottom = (int) Math.floor(webView.getContentHeight() * webView.getScale() * 0.8f); if (positionHolder >= bottom) { URL_POSITION_CACHES.remove(url); } else { URL_POSITION_CACHES.put(url, positionHolder); } super.onDestroy(); if (webView != null) { webView.destroy(); } } @Override public void finish() { super.finish(); overridePendingTransition(0, 0); } @Override public void onScrollChanged(WebView v, int x, int y, int oldX, int oldY) { positionHolder = y; } private class ChromeClient extends WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); progressbar.setProgress(newProgress); if (newProgress == 100) { progressbar.setVisibility(View.INVISIBLE); } else { progressbar.setVisibility(View.VISIBLE); } } @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (overrideTitleEnabled) { setTitle(title); } } } private class ReloadableClient extends WebViewClient { @SuppressWarnings("deprecation") public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null) { view.loadUrl(url); } return true; } @Override public void onPageCommitVisible(WebView view, String url) { super.onPageCommitVisible(view, url); Integer _position = URL_POSITION_CACHES.get(url); int position = _position == null ? 0 : _position; view.scrollTo(0, position); } } @Override public boolean canBack() { return true; } }
package jsettlers.main; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import jsettlers.ai.highlevel.AiExecutor; import jsettlers.common.CommonConstants; import jsettlers.common.map.IGraphicsGrid; import jsettlers.common.map.MapLoadException; import jsettlers.common.resources.ResourceManager; import jsettlers.common.statistics.IStatisticable; import jsettlers.graphics.map.IMapInterfaceConnector; import jsettlers.graphics.map.draw.ImageProvider; import jsettlers.graphics.progress.EProgressState; import jsettlers.graphics.startscreen.interfaces.EGameError; import jsettlers.graphics.startscreen.interfaces.IGameExitListener; import jsettlers.graphics.startscreen.interfaces.IStartedGame; import jsettlers.graphics.startscreen.interfaces.IStartingGame; import jsettlers.graphics.startscreen.interfaces.IStartingGameListener; import jsettlers.input.GuiInterface; import jsettlers.input.IGameStoppable; import jsettlers.input.PlayerState; import jsettlers.logic.buildings.Building; import jsettlers.logic.constants.MatchConstants; import jsettlers.logic.map.grid.MainGrid; import jsettlers.logic.map.save.IGameCreator; import jsettlers.logic.map.save.IGameCreator.MainGridWithUiSettings; import jsettlers.logic.map.save.MapList; import jsettlers.logic.map.save.loader.MapLoader; import jsettlers.logic.movable.Movable; import jsettlers.logic.player.PlayerSetting; import jsettlers.logic.statistics.GameStatistics; import jsettlers.logic.timer.RescheduleTimer; import jsettlers.network.client.OfflineNetworkConnector; import jsettlers.network.client.interfaces.IGameClock; import jsettlers.network.client.interfaces.INetworkConnector; import jsettlers.network.synchronic.random.RandomSingleton; /** * This class can start a Thread that loads and sets up a game and wait's for its termination. * * @author Andreas Eberle */ public class JSettlersGame { private static final SimpleDateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); private final Object stopMutex = new Object(); private final IGameCreator mapCreator; private final long randomSeed; private final byte playerId; private final PlayerSetting[] playerSettings; private final INetworkConnector networkConnector; private final boolean multiplayer; private final DataInputStream replayFileInputStream; private final GameRunner gameRunner; private boolean stopped = false; private boolean started = false; private PrintStream systemErrorStream; private PrintStream systemOutStream; private JSettlersGame(IGameCreator mapCreator, long randomSeed, INetworkConnector networkConnector, byte playerId, PlayerSetting[] playerSettings, boolean controlAll, boolean multiplayer, DataInputStream replayFileInputStream) { configureLogging(mapCreator); System.out.println("JsettlersGame(): seed: " + randomSeed + " playerId: " + playerId + " availablePlayers: " + Arrays.toString(playerSettings) + " multiplayer: " + multiplayer + " mapCreator: " + mapCreator); this.mapCreator = mapCreator; this.randomSeed = randomSeed; this.networkConnector = networkConnector; this.playerId = playerId; this.playerSettings = playerSettings; this.multiplayer = multiplayer; this.replayFileInputStream = replayFileInputStream; MatchConstants.ENABLE_ALL_PLAYER_FOG_OF_WAR = controlAll; MatchConstants.ENABLE_ALL_PLAYER_SELECTION = controlAll; MatchConstants.ENABLE_FOG_OF_WAR_DISABLING = controlAll; this.gameRunner = new GameRunner(); } /** * * @param mapCreator * @param randomSeed * @param networkConnector * @param playerId */ public JSettlersGame(IGameCreator mapCreator, long randomSeed, INetworkConnector networkConnector, byte playerId, PlayerSetting[] playerSettings) { this(mapCreator, randomSeed, networkConnector, playerId, playerSettings, CommonConstants.CONTROL_ALL, true, null); } /** * Creates a new {@link JSettlersGame} object with an {@link OfflineNetworkConnector}. * * @param mapCreator * @param randomSeed * @param playerId */ public JSettlersGame(IGameCreator mapCreator, long randomSeed, byte playerId, PlayerSetting[] playerSettings) { this(mapCreator, randomSeed, new OfflineNetworkConnector(), playerId, playerSettings, true, false, null); } public static JSettlersGame loadFromReplayFile(File loadableReplayFile, INetworkConnector networkConnector, ReplayStartInformation replayStartInformation) throws IOException { DataInputStream replayFileInputStream = new DataInputStream(new FileInputStream(loadableReplayFile)); replayStartInformation.deserialize(replayFileInputStream); MapLoader mapCreator = MapList.getDefaultList().getMapById(replayStartInformation.getMapId()); return new JSettlersGame(mapCreator, replayStartInformation.getRandomSeed(), networkConnector, (byte) replayStartInformation.getPlayerId(), replayStartInformation.getPlayerSettings(), true, false, replayFileInputStream); } /** * Starts the game in a new thread. Returns immediately. * * @return */ public synchronized IStartingGame start() { if (!started) { started = true; new Thread(null, gameRunner, "GameThread", 128 * 1024).start(); } return gameRunner; } public void stop() { synchronized (stopMutex) { stopped = true; stopMutex.notifyAll(); } } public class GameRunner implements Runnable, IStartingGame, IStartedGame, IGameStoppable { private IStartingGameListener startingGameListener; private MainGrid mainGrid; private GameStatistics statistics; private EProgressState progressState; private float progress; private IGameExitListener exitListener; private boolean gameRunning; @Override public void run() { try { updateProgressListener(EProgressState.LOADING, 0.1f); DataOutputStream replayFileStream = createReplayFileStream(); IGameClock gameClock = MatchConstants.clock = networkConnector.getGameClock(); gameClock.setReplayLogStream(replayFileStream); RandomSingleton.load(randomSeed); Movable.resetState(); updateProgressListener(EProgressState.LOADING_MAP, 0.3f); Thread imagePreloader = ImageProvider.getInstance().startPreloading(); MainGridWithUiSettings gridWithUiState = mapCreator.loadMainGrid(playerSettings); mainGrid = gridWithUiState.getMainGrid(); PlayerState playerState = gridWithUiState.getPlayerState(playerId); RescheduleTimer.schedule(gameClock); // schedule timer updateProgressListener(EProgressState.LOADING_IMAGES, 0.7f); statistics = new GameStatistics(gameClock); mainGrid.initForPlayer(playerId, playerState.getFogOfWar()); mainGrid.startThreads(); if (imagePreloader != null) imagePreloader.join(); // Wait for ImageProvider to finish loading the images waitForStartingGameListener(); updateProgressListener(EProgressState.WAITING_FOR_OTHER_PLAYERS, 0.98f); if (replayFileInputStream != null) { gameClock.loadReplayLogFromStream(replayFileInputStream); } networkConnector.setStartFinished(true); waitForAllPlayersStartFinished(networkConnector); final IMapInterfaceConnector connector = startingGameListener.preLoadFinished(this); GuiInterface guiInterface = new GuiInterface(connector, gameClock, networkConnector.getTaskScheduler(), mainGrid.getGuiInputGrid(), this, playerId, multiplayer); // This is required after the GuiInterface instantiation so that ConstructionMarksThread has it's mapArea variable initialized via the // EActionType.SCREEN_CHANGE event. connector.loadUIState(playerState.getUiState()); gameClock.startExecution(); gameRunning = true; startingGameListener.startFinished(); AiExecutor aiExecutor = new AiExecutor(playerSettings, mainGrid, networkConnector.getTaskScheduler()); networkConnector.getGameClock().schedule(aiExecutor, (short) 10000); synchronized (stopMutex) { while (!stopped) { try { stopMutex.wait(); } catch (InterruptedException e) { } } } networkConnector.shutdown(); gameClock.stopExecution(); connector.shutdown(); mainGrid.stopThreads(); guiInterface.stop(); RescheduleTimer.stop(); Movable.resetState(); Building.dropAllBuildings(); System.setErr(systemErrorStream); System.setOut(systemOutStream); } catch (MapLoadException e) { e.printStackTrace(); reportFail(EGameError.MAPLOADING_ERROR, e); } catch (Exception e) { e.printStackTrace(); reportFail(EGameError.UNKNOWN_ERROR, e); } finally { if (exitListener != null) { exitListener.gameExited(this); } } } private DataOutputStream createReplayFileStream() throws IOException { final String replayFilename = getLogFile(mapCreator, "_replay.log"); DataOutputStream replayFileStream = new DataOutputStream(ResourceManager.writeFile(replayFilename)); ReplayStartInformation replayInfo = new ReplayStartInformation(randomSeed, mapCreator.getMapName(), mapCreator.getMapId(), playerId, playerSettings); replayInfo.serialize(replayFileStream); replayFileStream.flush(); return replayFileStream; } /** * Waits until the {@link #startingGameListener} has been set. */ private void waitForStartingGameListener() { while (startingGameListener == null) { try { Thread.sleep(5); } catch (InterruptedException e) { } } } private void waitForAllPlayersStartFinished(INetworkConnector networkConnector) { while (!networkConnector.haveAllPlayersStartFinished()) { try { Thread.sleep(5); } catch (InterruptedException e) { } } } private void updateProgressListener(EProgressState progressState, float progress) { this.progressState = progressState; this.progress = progress; if (startingGameListener != null) startingGameListener.startProgressChanged(progressState, progress); } private void reportFail(EGameError gameError, Exception e) { if (startingGameListener != null) startingGameListener.startFailed(gameError, e); } // METHODS of IStartingGame @Override public void setListener(IStartingGameListener startingGameListener) { this.startingGameListener = startingGameListener; if (startingGameListener != null) startingGameListener.startProgressChanged(progressState, progress); } @Override public void abort() { stop(); } // METHODS of IStartedGame @Override public IGraphicsGrid getMap() { return mainGrid.getGraphicsGrid(); } @Override public IStatisticable getPlayerStatistics() { return statistics; } @Override public void stopGame() { stop(); } @Override public void setGameExitListener(IGameExitListener exitListener) { this.exitListener = exitListener; } @Override public boolean isStartupFinished() { return gameRunning; } public MainGrid getMainGrid() { return mainGrid; } } private void configureLogging(final IGameCreator mapcreator) { try { systemErrorStream = System.err; systemOutStream = System.out; if (!CommonConstants.ENABLE_CONSOLE_LOGGING) { PrintStream outLogStream = new PrintStream(ResourceManager.writeFile(getLogFile(mapcreator, "_out.log"))); System.setOut(outLogStream); System.setErr(outLogStream); } } catch (IOException ex) { throw new RuntimeException("Error setting up logging.", ex); } } private static String getLogFile(IGameCreator mapcreator, String suffix) { final String dateAndMap = logDateFormat.format(new Date()) + "_" + mapcreator.getMapName().replace(" ", "_"); final String logFolder = "logs/" + dateAndMap + "/"; final String replayFilename = logFolder + dateAndMap + suffix; return replayFilename; } }
package com.jetbrains.python; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiNamedElement; import com.intellij.psi.PsiReference; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Alexei Orischenko */ public abstract class BaseReference implements PsiReference, PyUserInitiatedResolvableReference { protected final PsiElement myElement; protected BaseReference(@NotNull PsiElement element) { myElement = element; } @Override @NotNull public PsiElement getElement() { return myElement; } @Override @NotNull public TextRange getRangeInElement() { return new TextRange(0, myElement.getTextLength()); } @Override @NotNull public String getCanonicalText() { return myElement.getText(); } @Override public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException { if (myElement instanceof PsiNamedElement) { return ((PsiNamedElement)myElement).setName(newElementName); } throw new IncorrectOperationException(); } @Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { return null; } @Override public boolean isReferenceTo(@NotNull PsiElement element) { return resolve() == element; } @Override public boolean isSoft() { return false; } @Nullable @Override public PsiElement userInitiatedResolve() { // Override this method if your reference may benefit from this knowledge return resolve(); } }
package com.yahoo.messagebus; import com.yahoo.log.LogLevel; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; /** * <p>This class implements a single thread that is able to process arbitrary * tasks. Tasks are enqueued using the synchronized {@link #enqueue(Task)} * method, and are run in the order they were enqueued.</p> * * @author Simon Thoresen Hult */ public class Messenger implements Runnable { private static final Logger log = Logger.getLogger(Messenger.class.getName()); private final AtomicBoolean destroyed = new AtomicBoolean(false); private final List<Task> children = new ArrayList<>(); private final Queue<Task> queue = new ArrayDeque<>(); private final Thread thread = new Thread(this, "Messenger"); public Messenger() { thread.setDaemon(true); } /** * <p>Adds a recurrent task to this that is to be run for every iteration of * the main loop. This task must be very light-weight as to not block the * messenger. Note that this method is NOT thread-safe, so it should NOT be * used after calling {@link #start()}.</p> * * @param task The task to add. */ void addRecurrentTask(final Task task) { children.add(task); } /** * <p>Starts the internal thread. This must be done AFTER all recurrent * tasks have been added.</p> * * @see #addRecurrentTask(Task) */ public void start() { thread.start(); } /** * <p>Convenience method to post a {@link Task} that delivers a {@link * Message} to a {@link MessageHandler} to the queue of tasks to be * executed.</p> * * @param msg The message to send. * @param handler The handler to send to. */ public void deliverMessage(final Message msg, final MessageHandler handler) { if (destroyed.get()) { msg.discard(); } else { handler.handleMessage(msg); } } /** * <p>Convenience method to post a {@link Task} that delivers a {@link * Reply} to a {@link ReplyHandler} to the queue of tasks to be * executed.</p> * * @param reply The reply to return. * @param handler The handler to return to. */ public void deliverReply(final Reply reply, final ReplyHandler handler) { if (destroyed.get()) { reply.discard(); } else { handler.handleReply(reply); } } /** * <p>Enqueues the given task in the list of tasks that this worker is to * process. If this thread has been destroyed previously, this method * invokes {@link Messenger.Task#destroy()}.</p> * * @param task The task to enqueue. */ public void enqueue(final Task task) { if (destroyed.get()) { task.destroy(); return; } synchronized (this) { queue.offer(task); if (queue.size() == 1) { notify(); } } } /** * <p>Handshakes with the internal thread. If this method is called using * the messenger thread, this will deadlock.</p> */ public void sync() { if (Thread.currentThread() == thread) { return; // no need to wait for self } final SyncTask task = new SyncTask(); enqueue(task); task.await(); } /** * <p>Sets the destroyed flag to true. The very first time this method is * called, it cleans up all its dependencies. Even if you retain a * reference to this object, all of its content is allowed to be garbage * collected.</p> * * @return True if content existed and was destroyed. */ public boolean destroy() { boolean done = false; enqueue(Terminate.INSTANCE); if (!destroyed.getAndSet(true)) { try { synchronized (this) { while (!queue.isEmpty()) { wait(); } } thread.join(); } catch (final InterruptedException e) { // ignore } done = true; } return done; } @Override public void run() { while (true) { Task task = null; synchronized (this) { if (queue.isEmpty()) { try { wait(10); } catch (final InterruptedException e) { continue; } } if (queue.size() > 0) { task = queue.poll(); } } if (task == Terminate.INSTANCE) { break; } if (task != null) { try { task.run(); } catch (final Exception e) { log.log(LogLevel.ERROR, "An exception was thrown while running " + task.getClass().getName(), e); } try { task.destroy(); } catch (final Exception e) { log.warning("An exception was thrown while destroying " + task.getClass().getName() + ": " + e.toString()); log.warning("Someone, somewhere might have to wait indefinetly for something."); } } for (final Task child : children) { child.run(); } } for (final Task child : children) { child.destroy(); } synchronized (this) { while (!queue.isEmpty()) { final Task task = queue.poll(); task.destroy(); } notify(); } } /** * <p>Defines the required interface for tasks to be posted to this * worker.</p> */ public interface Task { /** * <p>This method is called when being executed.</p> */ void run(); /** * <p>This method is called for all tasks, even if {@link #run()} was * never called.</p> */ void destroy(); } private static class SyncTask implements Task { final CountDownLatch latch = new CountDownLatch(1); @Override public void run() { // empty } @Override public void destroy() { latch.countDown(); } public void await() { try { latch.await(); } catch (final InterruptedException e) { // ignore } } } private static class Terminate implements Task { static final Terminate INSTANCE = new Terminate(); @Override public void run() { // empty } @Override public void destroy() { // empty } } }
package ru.stqa.pft.rest; public class Issue { private int id; private String subject; private String description; private String state_name; public String getStateName() { return state_name; } public Issue withStateName(String stateName) { this.state_name = stateName; return this; } public int getId() { return id; } public Issue withId(int id) { this.id = id; return this; } public String getSubject() { return subject; } public Issue withSubject(String subject) { this.subject = subject; return this; } public String getDescription() { return description; } public Issue withDescription(String description) { this.description = description; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Issue issue = (Issue) o; if (id != issue.id) return false; if (subject != null ? !subject.equals(issue.subject) : issue.subject != null) return false; return description != null ? description.equals(issue.description) : issue.description == null; } @Override public int hashCode() { int result = id; result = 31 * result + (subject != null ? subject.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); return result; } }
package org.reactfx; import static org.reactfx.EventStreams.*; import static org.reactfx.util.Tuples.*; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import javafx.application.Platform; import javafx.beans.binding.Binding; import javafx.beans.value.ObservableValue; import javafx.beans.value.WritableValue; import javafx.concurrent.Task; import javafx.scene.Node; import javafx.scene.Scene; import javafx.stage.Window; import org.reactfx.util.AccumulatorSize; import org.reactfx.util.Either; import org.reactfx.util.Experimental; import org.reactfx.util.FxTimer; import org.reactfx.util.NotificationAccumulator; import org.reactfx.util.Timer; import org.reactfx.util.Tuple2; import org.reactfx.value.Val; /** * Stream of values (events). * * @param <T> type of values emitted by this stream. */ public interface EventStream<T> extends Observable<Consumer<? super T>> { /** * Get notified every time this event stream emits a value. * @param subscriber handles emitted events. * @return subscription that can be used to stop observing this event * stream. */ default Subscription subscribe(Consumer<? super T> subscriber) { return observe(subscriber); } /** * Subscribes to this event stream for at most {@code n} events. * The subscriber is automatically removed after handling {@code n} events. * @param n limit on how many events may be handled by {@code subscriber}. * Must be positive. * @param subscriber handles emitted events. * @return {@linkplain Subscription} that may be used to unsubscribe before * reaching {@code n} events handled by {@code subscriber}. */ default Subscription subscribeFor(int n, Consumer<? super T> subscriber) { return new LimitedInvocationSubscriber<>(n, subscriber).subscribeTo(this); } /** * Shorthand for {@code subscribeFor(1, subscriber)}. */ default Subscription subscribeForOne(Consumer<? super T> subscriber) { return subscribeFor(1, subscriber); } /** * Starts pushing all events emitted by this stream to the given event sink. * <p>{@code stream.feedTo(sink)} is equivalent to * {@code sink.feedFrom(stream)} * @param sink event sink to which this event stream's events will be pushed * @return subscription that can be used to stop delivering this stream's * events to {@code sink}. * @see EventSink#feedFrom(EventStream) */ default Subscription feedTo(EventSink<? super T> sink) { return subscribe(sink::push); } /** * Starts setting all events emitted by this stream as the value of the * given writable value. This is a shortcut for * {@code subscribe(dest::setValue)}. */ default Subscription feedTo(WritableValue<? super T> dest) { return subscribe(dest::setValue); } /** * If this stream is a compound stream lazily subscribed to its inputs, * that is, subscribed to inputs only when it itself has some subscribers, * {@code pin}ning this stream causes it to stay subscribed until the * pinning is revoked by calling {@code unsubscribe()} on the returned * subscription. * * <p>Equivalent to {@code subscribe(x -> {})}. * @return subscription used to cancel the pinning */ default Subscription pin() { return subscribe(x -> {}); } /** * Returns an event stream that immediately emits its event when something * subscribes to it. If the stream has no event to emit, it defaults to * emitting the default event. Once this stream emits an event, the returned * stream will emit this stream's most recent event. Useful when one doesn't * know whether an EventStream will emit its event immediately but needs it * to emit an event immediately. Such a case can arise as shown in the * following example: * <pre> * {@code * EventStream<Boolean> controlPresses = EventStreams * .eventsOf(scene, KeyEvent.KEY_PRESSED) * .filter(key -> key.getCode().is(KeyCode.CONTROL)) * .map(key -> key.isControlDown()); * * EventSource<?> other; * EventStream<Tuple2<Boolean, ?>> combo = EventStreams.combine(controlPresses, other); * * // This will not run until user presses the control key at least once. * combo.subscribe(tuple2 -> System.out.println("Combo emitted an event.")); * * EventStream<Boolean> controlDown = controlPresses.withDefaultEvent(false); * EventStream<Tuple2<Boolean, ?>> betterCombo = EventStreams.combine(controlDown, other); * betterCombo.subscribe(tuple2 -> System.out.println("Better Combo emitted an event immediately upon program start.")); * } * </pre> * * @param defaultEvent the event this event stream will emit if something subscribes to this stream and this stream does not have an event. */ default EventStream<T> withDefaultEvent(T defaultEvent) { return new DefaultEventStream<>(this, defaultEvent); } default EventStream<T> hook(Consumer<? super T> sideEffect) { return new HookStream<>(this, sideEffect); } /** * Returns a new event stream that emits events emitted from this stream * that satisfy the given predicate. */ default EventStream<T> filter(Predicate<? super T> predicate) { return new FilterStream<>(this, predicate); } /** * Filters this event stream by the runtime type of the values. * {@code filter(SomeClass.class)} is equivalent to * {@code filter(x -> x instanceof SomeClass).map(x -> (SomeClass) x)}. */ default <U extends T> EventStream<U> filter(Class<U> subtype) { return filterMap(subtype::isInstance, subtype::cast); } default EventStream<T> distinct() { return new DistinctStream<>(this); } default <U> EventStream<U> supply(U value) { return map(x -> value); } /** * Returns an event stream that emits a value obtained from the given * supplier every time this event stream emits a value. */ default <U> EventStream<U> supply(Supplier<? extends U> f) { return map(x -> f.get()); } /** * Similar to {@link #supply(Supplier)}, but the returned stream is a * {@link CompletionStageStream}, which can be used to await the results * of asynchronous computation. */ default <U> CompletionStageStream<U> supplyCompletionStage(Supplier<CompletionStage<U>> f) { return mapToCompletionStage(x -> f.get()); } /** * Similar to {@link #supply(Supplier)}, but the returned stream is a * {@link CompletionStageStream}, which can be used to await the results * of asynchronous computation. */ default <U> TaskStream<U> supplyTask(Supplier<Task<U>> f) { return mapToTask(x -> f.get()); } default <U> EventStream<U> map(Function<? super T, ? extends U> f) { return new MappedStream<>(this, f); } /** * Returns a new event stream that emits events emitted by this stream * cast to the given type. * {@code cast(SomeClass.class)} is equivalent to * {@code map(x -> (SomeClass) x)}. */ default <U extends T> EventStream<U> cast(Class<U> subtype) { return map(subtype::cast); } /** * Returns a new event stream that, for event {@code e} emitted from this * stream, emits {@code left(e)} if {@code e} passes the given test, and * emits {@code right(e)} if {@code e} does not pass the test. */ default EventStream<Either<T, T>> splitBy(Predicate<? super T> test) { return map(t -> test.test(t) ? Either.left(t) : Either.right(t)); } /** * Returns two event streams, the first one emitting events of this stream * that satisfy the given {@code test} and the second one emitting events * of this stream that do not satisfy the test. */ default Tuple2<EventStream<T>, EventStream<T>> fork(Predicate<? super T> test) { return t(filter(test), filter(test.negate())); } /** * Similar to {@link #map(Function)}, but the returned stream is a * {@link CompletionStageStream}, which can be used to await the results * of asynchronous computation. */ default <U> CompletionStageStream<U> mapToCompletionStage(Function<? super T, CompletionStage<U>> f) { return new MappedToCompletionStageStream<>(this, f); } /** * Similar to {@link #map(Function)}, but the returned stream is a * {@link TaskStream}, which can be used to await the results of * asynchronous computation. */ default <U> TaskStream<U> mapToTask(Function<? super T, Task<U>> f) { return new MappedToTaskStream<>(this, f); } /** * A more efficient equivalent to * {@code filter(predicate).map(f)}. */ default <U> EventStream<U> filterMap( Predicate<? super T> predicate, Function<? super T, ? extends U> f) { return new FilterMapStream<>(this, predicate, f); } /** * Equivalent to * <pre> * {@code * map(f) * .filter(Optional::isPresent) * .map(Optional::get) * } * </pre> * with more efficient implementation. */ default <U> EventStream<U> filterMap(Function<? super T, Optional<U>> f) { return new FlatMapOptStream<T, U>(this, f); } default <U> EventStream<U> flatMap(Function<? super T, ? extends EventStream<U>> f) { return new FlatMapStream<>(this, f); } /** * Returns a new {@linkplain EventStream} that only observes this * {@linkplain EventStream} when {@code condition} is {@code true}. * More precisely, the returned {@linkplain EventStream} observes * {@code condition} whenever it itself has at least one subscriber and * observes {@code this} {@linkplain EventStream} whenever it itself has * at least one subscriber <em>and</em> the value of {@code condition} is * {@code true}. When {@code condition} is {@code true}, the returned * {@linkplain EventStream} emits the same events as this * {@linkplain EventStream}. When {@code condition} is {@code false}, the * returned {@linkplain EventStream} emits no events. */ default EventStream<T> conditionOn(ObservableValue<Boolean> condition) { return valuesOf(condition).flatMap(c -> c ? this : never()); } /** * Equivalent to {@link #conditionOn(ObservableValue)} where the condition * is that {@code node} is <em>showing</em>: it is part of a scene graph * ({@link Node#sceneProperty()} is not {@code null}), its scene is part of * a window ({@link Scene#windowProperty()} is not {@code null}) and the * window is showing ({@link Window#showingProperty()} is {@code true}). */ default EventStream<T> conditionOnShowing(Node node) { return conditionOn(Val.showingProperty(node)); } /** * Returns an event stream that emits all the events emitted from either * this stream or the {@code right} stream. An event <i>t</i> emitted from * this stream is emitted as {@code Either.left(t)}. An event <i>u</i> * emitted from the {@code right} stream is emitted as * {@code Either.right(u)}. * * @see EventStreams#merge(EventStream...) */ default <U> EventStream<Either<T, U>> or(EventStream<? extends U> right) { EventStream<T> left = this; return new EventStreamBase<Either<T, U>>() { @Override protected Subscription observeInputs() { return Subscription.multi( left.subscribe(l -> emit(Either.<T, U>left(l))), right.subscribe(r -> emit(Either.<T, U>right(r)))); } }; } default EventStream<List<T>> latestN(int n) { return new LatestNStream<>(this, n); } default EventStream<T> emitOn(EventStream<?> impulse) { return new EmitOnStream<>(this, impulse); } default EventStream<T> emitOnEach(EventStream<?> impulse) { return new EmitOnEachStream<>(this, impulse); } default <I> EventStream<Tuple2<T, I>> emitBothOnEach(EventStream<I> impulse) { return new EmitBothOnEachStream<>(this, impulse); } default EventStream<T> repeatOn(EventStream<?> impulse) { return new RepeatOnStream<>(this, impulse); } /** * Returns a suspendable event stream that, when suspended, suppresses * any events emitted by this event stream. */ default SuspendableEventStream<T> suppressible() { return new SuppressibleEventStream<>(this); } /** * Shortcut for {@code suppressible().suspendWhen(condition)}. */ default EventStream<T> suppressWhen(ObservableValue<Boolean> condition) { return suppressible().suspendWhen(condition); } default SuspendableEventStream<T> pausable() { return new PausableEventStream<>(this); } /** * Shortcut for {@code pausable().suspendWhen(condition)}. */ default EventStream<T> pauseWhen(ObservableValue<Boolean> condition) { return pausable().suspendWhen(condition); } default SuspendableEventStream<T> forgetful() { return new ForgetfulEventStream<>(this); } /** * Shortcut for {@code forgetful().suspendWhen(condition)}. */ default EventStream<T> retainLatestWhen(ObservableValue<Boolean> condition) { return forgetful().suspendWhen(condition); } default SuspendableEventStream<T> reducible(BinaryOperator<T> reduction) { return new ReducibleEventStream<>(this, reduction); } /** * Shortcut for {@code reducible(reduction).suspendWhen(condition)}. */ default EventStream<T> reduceWhen( ObservableValue<Boolean> condition, BinaryOperator<T> reduction) { return reducible(reduction).suspendWhen(condition); } /** * Returns a suspendable event stream that, when suspended, accumulates * incoming events to a cumulative value of type {@code A}. When the * returned stream is resumed, the accumulated value is deconstructed into * a sequence of events that are emitted from the returned stream. * * <p>Note that {@link #suppressible()} is equivalent to * <pre> * {@code * accumulative( * t -> (Void) null, // use null as accumulator * (a, t) -> a, // keep null as accumulator * a -> AccumulatorSize.ZERO, // no events to be emitted from accumulator * a -> throw new NoSuchElementException(), // head is never called on empty accumulator * a -> throw new NoSuchElementException()) // tail is never called on empty accumulator * } * </pre> * * <p>Note that {@code reducible(reduction)} is equivalent to * <pre> * {@code * accumulative( * t -> t, // the event itself is the accumulator * reduction, * t -> AccumulatorSize.ONE, // one event to be emitted * t -> t, // head of a single value is the value itself * t -> throw new NoSuchElementException) // tail is never called on accumulator of size one * } * </pre> * * @param initialTransformation Used to convert the first event after * suspension to the cumulative value. * @param accumulation Used to accumulate further incoming events to the * cumulative value. * @param size determines how many events can be emitted from the current * cumulative value. * @param head produces the first event off the cumulative value. * @param tail returns a cumulative value that produces the same events * as the given cumulative value, except the event returned by {@code head}. * May be destructive for the given cumulative value. * @param <A> type of the cumulative value */ default <A> SuspendableEventStream<T> accumulative( Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, AccumulatorSize> size, Function<? super A, ? extends T> head, Function<? super A, ? extends A> tail) { return new AccumulativeEventStream<>( this, initialTransformation, accumulation, size, head, tail); } /** * Shortcut for * <pre> * {@code * accumulative(initialTransformation, accumulation, size, head, tail) * .suspendWhen(condition)} * </pre> */ default <A> EventStream<T> accumulateWhen( ObservableValue<Boolean> condition, Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, AccumulatorSize> size, Function<? super A, ? extends T> head, Function<? super A, ? extends A> tail) { return accumulative(initialTransformation, accumulation, size, head, tail) .suspendWhen(condition); } /** * A variation on * {@link #accumulative(Function, BiFunction, Function, Function, Function)} * to use when it is more convenient to provide a unit element of the * accumulation than to transform the initial event to a cumulative * value. It is equivalent to * {@code accumulative(t -> accumulation.apply(unit.get(), t), accumulation, size, head, tail)}, * i.e. the initial transformation is achieved by accumulating the initial * event to the unit element. * * <p>Note that {@link #pausable()} is equivalent to * <pre> * {@code * accumulative( * LinkedList<T>::new, // the unit element is an empty queue * (q, t) -> { q.addLast(t); return q; }, // accumulation is addition to the queue * q -> AccumulatorSize.fromInt(q.size()), // size is the size of the queue * Deque::getFirst, // head is the first element of the queue * q -> { q.removeFirst(); return q; }) // tail removes the first element from the queue * } * </pre> * * @param unit Function that supplies unit element of the accumulation. * @param accumulation Used to accumulate further incoming events to the * cumulative value. * @param size determines how many events can be emitted from the current * cumulative value. * @param head produces the first event off the cumulative value. * @param tail returns a cumulative value that produces the same events * as the given cumulative value, except the event returned by {@code head}. * May be destructive for the given cumulative value. * @param <A> type of the cumulative value */ default <A> SuspendableEventStream<T> accumulative( Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, AccumulatorSize> size, Function<? super A, ? extends T> head, Function<? super A, ? extends A> tail) { Function<? super T, ? extends A> initialTransformation = t -> accumulation.apply(unit.get(), t); return accumulative( initialTransformation, accumulation, size, head, tail); } /** * Shortcut for * <pre> * {@code * accumulative(unit, accumulation, size, head, tail) * .suspendWhen(condition)} * </pre> */ default <A> EventStream<T> accumulateWhen( ObservableValue<Boolean> condition, Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, AccumulatorSize> size, Function<? super A, ? extends T> head, Function<? super A, ? extends A> tail) { return accumulative(unit, accumulation, size, head, tail) .suspendWhen(condition); } /** * Returns an event stream that, when an event arrives from this stream, * transforms it into a cumulative value using the * {@code initialTransformation} function. Any further events that arrive * from this stream are accumulated to the cumulative value using the * {@code accumulation} function. When an event arrives from the * {@code ticks} stream, the accumulated value is deconstructed into a * sequence of events using the {@code deconstruction} function and the * events are emitted from the returned stream. * * <p>Note that {@code reduceBetween(ticks, reduction)} is equivalent to * {@code accumulateBetween(ticks, t -> t, reduction, Collections::singletonList)}. */ default <A> EventStream<T> accumulateBetween( EventStream<?> ticks, Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, List<T>> deconstruction) { return new AccumulateBetweenStream<>( this, ticks, initialTransformation, accumulation, deconstruction); } /** * A variation on * {@link #accumulateBetween(EventStream, Function, BiFunction, Function)} * to use when it is more convenient to provide a unit element of the * accumulation than to transform the initial event to a cumulative * value. It is equivalent to * {@code accumulateBetween(ticks, t -> accumulation.apply(unit.get(), t), accumulation, deconstruction)}, * i.e. the initial transformation is achieved by accumulating the initial * event to the unit element. * * <p>Note that {@code queueBetween(ticks)} is equivalent to * {@code accumulateBetween(ticks, ArrayList<T>::new, (l, t) -> { l.add(t); return l; }, l -> l)}, * i.e. the unit element is an empty list, accumulation is addition to the * list and deconstruction of the accumulated value is a no-op, since the * accumulated value is already a list of events. */ default <A> EventStream<T> accumulateBetween( EventStream<?> ticks, Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, List<T>> deconstruction) { Function<? super T, ? extends A> initialTransformation = t -> accumulation.apply(unit.get(), t); return accumulateBetween( ticks, initialTransformation, accumulation, deconstruction); } /** * Returns an event stream that, when an event arrives from this stream, * stores it for emission. Any further events that arrive from this stream * are reduced into the stored event using the {@code reduction} function. * The stored event is emitted from the returned stream when a <i>tick</i> * arrives from the {@code ticks} stream. * * <p>Note that {@code retainLatestBetween(ticks)} is equivalent to * {@code reduceBetween(ticks, (a, b) -> b)}. */ default EventStream<T> reduceBetween( EventStream<?> ticks, BinaryOperator<T> reduction) { return accumulateBetween( ticks, Function.<T>identity(), reduction, Collections::singletonList); } /** * Returns an event stream that, when an event arrives from this stream, * enqueues it for emission. Queued events are emitted from the returned * stream when a <i>tick</i> arrives from the {@code ticks} stream. */ default EventStream<T> queueBetween(EventStream<?> ticks) { return accumulateBetween( ticks, (Supplier<List<T>>) ArrayList::new, (l, t) -> { l.add(t); return l; }, Function.identity()); } /** * Equivalent to {@link #emitOn(EventStream)}. */ default EventStream<T> retainLatestBetween(EventStream<?> ticks) { return emitOn(ticks); } /** * Version of {@link #accumulateUntilLater(Function, BiFunction, Function)} * for event streams that don't live on the JavaFX application thread. * @param eventThreadExecutor executor that executes actions on the thread * from which this event stream is accessed. */ default <A> EventStream<T> accumulateUntilLater( Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, List<T>> deconstruction, Executor eventThreadExecutor) { return new AccumulateUntilLaterStream<>( this, initialTransformation, accumulation, deconstruction, eventThreadExecutor); } /** * Returns an event stream that, when an event is emitted from this stream, * transforms the event to a cumulative value using the * {@code initialTransformation} function and schedules emission using * {@link Platform#runLater(Runnable)}, if not already scheduled. Any new * event that arrives from this stream before the scheduled emission is * executed is accumulated to the stored cumulative value using the given * {@code accumulation} function. When the scheduled emission is finally * executed, the accumulated value is deconstructed into a sequence of * events using the {@code deconstruction} function and the events are * emitted from the returned stream. * * <p>Note that {@code reduceUntilLater(reduction)} is equivalent to * {@code accumulateUntilLater(t -> t, reduction, t -> Collections::singletonList)}. * * @param <A> type of the cumulative value (accumulator) */ default <A> EventStream<T> accumulateUntilLater( Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, List<T>> deconstruction) { return accumulateUntilLater( initialTransformation, accumulation, deconstruction, Platform::runLater); } /** * Version of {@link #accumulateUntilLater(Supplier, BiFunction, Function)} * for event streams that don't live on the JavaFX application thread. * @param eventThreadExecutor executor that executes actions on the thread * from which this event stream is accessed. */ default <A> EventStream<T> accumulateUntilLater( Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, List<T>> deconstruction, Executor eventThreadExecutor) { return accumulateUntilLater( t -> accumulation.apply(unit.get(), t), accumulation, deconstruction, eventThreadExecutor); } /** * A variation on * {@link #accumulateUntilLater(Function, BiFunction, Function)} * to use when it is more convenient to provide a unit element of the * accumulation than to transform the initial event to a cumulative * value. It is equivalent to * {@code accumulateUntilLater(t -> accumulation.apply(unit.get(), t), accumulation, deconstruction)}, * i.e. the initial transformation is achieved by accumulating the initial * event to the unit element. * * <p>Note that {@link #queueUntilLater()} is equivalent to * {@code accumulateUntilLater(ArrayList<T>::new, (l, t) -> { l.add(t); return l; }, l -> l)}, * i.e. the unit element is an empty list, accumulation is addition to the * list and deconstruction of the accumulated value is a no-op, since the * accumulated value is already a list of events. * * @param <A> type of the cumulative value (accumulator) */ default <A> EventStream<T> accumulateUntilLater( Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> accumulation, Function<? super A, List<T>> deconstruction) { return accumulateUntilLater( unit, accumulation, deconstruction, Platform::runLater); } /** * Version of {@link #reduceUntilLater(BinaryOperator)} for event streams * that don't live on the JavaFX application thread. * @param eventThreadExecutor executor that executes actions on the thread * from which this event stream is accessed. */ default EventStream<T> reduceUntilLater( BinaryOperator<T> reduction, Executor eventThreadExecutor) { return accumulateUntilLater( Function.<T>identity(), reduction, Collections::singletonList, eventThreadExecutor); } /** * Returns an event stream that, when an event is emitted from this stream, * stores the event for emission and schedules emission using * {@link Platform#runLater(Runnable)}, if not already scheduled. Any new * event that arrives from this stream before the scheduled emission is * executed is accumulated into the stored event using the given * {@code reduction} function. When the scheduled emission is finally * executed, the stored event is emitted from the returned stream. * * <p>Note that {@link #retainLatestUntilLater()} is equivalent to * {@code reduceUntilLater((a, b) -> b)}. */ default EventStream<T> reduceUntilLater(BinaryOperator<T> reduction) { return reduceUntilLater(reduction, Platform::runLater); } /** * Version of {@link #retainLatestUntilLater()} for event streams that * don't live on the JavaFX application thread. * @param eventThreadExecutor executor that executes actions on the thread * from which this event stream is accessed. */ default EventStream<T> retainLatestUntilLater(Executor eventThreadExecutor) { return reduceUntilLater((a, b) -> b, eventThreadExecutor); } /** * Returns an event stream that, when an event is emitted from this stream, * stores the event for emission and schedules emission using * {@link Platform#runLater(Runnable)}, if not already scheduled. If a new * event arrives from this stream before the scheduled emission is executed, * the stored event is overwritten by the new event and only the new event is * emitted when the scheduled emission is finally executed. */ default EventStream<T> retainLatestUntilLater() { return retainLatestUntilLater(Platform::runLater); } /** * Version of {@link #queueUntilLater()} for event streams that don't live * on the JavaFX application thread. * @param eventThreadExecutor executor that executes actions on the thread * from which this event stream is accessed. */ default EventStream<T> queueUntilLater(Executor eventThreadExecutor) { return accumulateUntilLater( (Supplier<List<T>>) ArrayList::new, (l, t) -> { l.add(t); return l; }, l -> l, eventThreadExecutor); } /** * Returns an event stream that, when an event is emitted from this stream, * enqueues the event for emission and schedules emission using * {@link Platform#runLater(Runnable)}, if not already scheduled. Any events * that arrive from this stream before a scheduled emission is executed are * enqueued as well and emitted (in order) when the scheduled emission is * finally executed. */ default EventStream<T> queueUntilLater() { return queueUntilLater(Platform::runLater); } /** * Returns a binding that holds the most recent event emitted from this * stream. The returned binding stays subscribed to this stream until its * {@code dispose()} method is called. * @param initialValue used as the returned binding's value until this * stream emits the first value. * @return binding reflecting the most recently emitted value. */ default Binding<T> toBinding(T initialValue) { return new StreamBinding<>(this, initialValue); } /** * Returns an event stream that accumulates events emitted from this event * stream and emits the accumulated value every time this stream emits a * value. * @param reduction function to reduce two events into one. */ default EventStream<T> accumulate(BinaryOperator<T> reduction) { return accumulate(reduction, Function.identity()); } default <U> EventStream<U> accumulate( U unit, BiFunction<? super U, ? super T, ? extends U> reduction) { return accumulate(reduction, t -> reduction.apply(unit, t)); } default <U> EventStream<U> accumulate( BiFunction<? super U, ? super T, ? extends U> reduction, Function<? super T, ? extends U> initialTransformation) { return new AccumulatingStream<>(this, initialTransformation, reduction); } /** * Returns an event stream that accumulates events emitted from this event * stream in close temporal succession. After an event is emitted from this * stream, the returned stream waits for up to {@code timeout} for the next * event from this stream. If the next event arrives within timeout, it is * accumulated to the current event by the {@code reduction} function and * the timeout is reset. When the timeout expires, the accumulated event is * emitted from the returned stream. * * <p><b>Note:</b> This function can be used only when this stream and * the returned stream are used from the JavaFX application thread. If * you are using the event streams on a different thread, use * {@link #reduceSuccessions(BinaryOperator, Duration, ScheduledExecutorService, Executor)} * instead.</p> * * @param reduction function to reduce two events into one. * @param timeout the maximum time difference between two subsequent * events that can still be accumulated. */ default AwaitingEventStream<T> reduceSuccessions( BinaryOperator<T> reduction, Duration timeout) { return reduceSuccessions(Function.identity(), reduction, timeout); } /** * A more general version of * {@link #reduceSuccessions(BinaryOperator, Duration)} * that allows the accumulated event to be of different type. * * <p><b>Note:</b> This function can be used only when this stream and * the returned stream are used from the JavaFX application thread. If * you are using the event streams on a different thread, use * {@link #reduceSuccessions(Function, BiFunction, Duration, ScheduledExecutorService, Executor)} * instead.</p> * * @param initialTransformation function to transform a single event * from this stream to an event that can be emitted from the returned * stream. * @param reduction function to add an event to the accumulated value. * @param timeout the maximum time difference between two subsequent * events that can still be accumulated. * @param <U> type of events emitted from the returned stream. */ default <U> AwaitingEventStream<U> reduceSuccessions( Function<? super T, ? extends U> initialTransformation, BiFunction<? super U, ? super T, ? extends U> reduction, Duration timeout) { Function<Runnable, Timer> timerFactory = action -> FxTimer.create(timeout, action); return new SuccessionReducingStream<T, U>( this, initialTransformation, reduction, timerFactory); } /** * A convenient method that can be used when it is more convenient to * supply an identity of the type {@code U} than to transform an event * of type {@code T} to an event of type {@code U}. * This method is equivalent to * {@code reduceSuccessions(t -> reduction.apply(identitySupplier.get(), t), reduction, timeout)}. * * <p><b>Note:</b> This function can be used only when this stream and * the returned stream are used from the JavaFX application thread. If * you are using the event streams on a different thread, use * {@link #reduceSuccessions(Supplier, BiFunction, Duration, ScheduledExecutorService, Executor)} * instead.</p> * * @param unitSupplier function that provides the unit element * (i.e. initial value for accumulation) of type {@code U} * @param reduction function to add an event to the accumulated value. * @param timeout the maximum time difference between two subsequent * events that can still be accumulated. * * @see #reduceSuccessions(Function, BiFunction, Duration) */ default <U> AwaitingEventStream<U> reduceSuccessions( Supplier<? extends U> unitSupplier, BiFunction<? super U, ? super T, ? extends U> reduction, Duration timeout) { Function<T, U> map = t -> reduction.apply(unitSupplier.get(), t); return reduceSuccessions(map, reduction, timeout); } /** * An analog to * {@link #reduceSuccessions(BinaryOperator, Duration)} * to use outside of JavaFX application thread. * * @param reduction function to reduce two events into one. * @param timeout the maximum time difference between two subsequent * events that can still be accumulated. * @param scheduler used to schedule timeout expiration * @param eventThreadExecutor executor that executes actions on the * thread on which this stream's events are emitted. The returned stream * will use this executor to emit events. */ default AwaitingEventStream<T> reduceSuccessions( BinaryOperator<T> reduction, Duration timeout, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { return reduceSuccessions( Function.identity(), reduction, timeout, scheduler, eventThreadExecutor); } /** * An analog to * {@link #reduceSuccessions(Function, BiFunction, Duration)} * to use outside of JavaFX application thread. * * @param initialTransformation function to transform a single event * from this stream to an event that can be emitted from the returned * stream. * @param reduction function to accumulate an event to the stored value * @param timeout the maximum time difference between two subsequent * events that can still be accumulated. * @param scheduler used to schedule timeout expiration * @param eventThreadExecutor executor that executes actions on the * thread on which this stream's events are emitted. The returned stream * will use this executor to emit events. */ default <U> AwaitingEventStream<U> reduceSuccessions( Function<? super T, ? extends U> initialTransformation, BiFunction<? super U, ? super T, ? extends U> reduction, Duration timeout, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { Function<Runnable, Timer> timerFactory = action -> ScheduledExecutorServiceTimer.create( timeout, action, scheduler, eventThreadExecutor); return new SuccessionReducingStream<T, U>( this, initialTransformation, reduction, timerFactory); } /** * An analog to * {@link #reduceSuccessions(Supplier, BiFunction, Duration)} * to use outside of JavaFX application thread. * * @param unitSupplier function that provides the unit element * @param reduction function to accumulate an event to the stored value * @param timeout the maximum time difference between two subsequent * events that can still be accumulated. * @param scheduler used to schedule timeout expiration * @param eventThreadExecutor executor that executes actions on the * thread on which this stream's events are emitted. The returned stream * will use this executor to emit events. */ default <U> AwaitingEventStream<U> reduceSuccessions( Supplier<? extends U> unitSupplier, BiFunction<? super U, ? super T, ? extends U> reduction, Duration timeout, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { Function<T, U> map = t -> reduction.apply(unitSupplier.get(), t); return reduceSuccessions( map, reduction, timeout, scheduler, eventThreadExecutor); } /** * Returns an event stream that, when events are emitted from this stream * in close temporal succession, emits only the last event of the * succession. What is considered a <i>close temporal succession</i> is * defined by {@code timeout}: time gap between two successive events must * be at most {@code timeout}. * * <p>This method is a shortcut for * {@code reduceSuccessions((a, b) -> b, timeout)}.</p> * * <p><b>Note:</b> This function can be used only when this stream and * the returned stream are used from the JavaFX application thread. If * you are using the event streams on a different thread, use * {@link #successionEnds(Duration, ScheduledExecutorService, Executor)} * instead.</p> * * @param timeout the maximum time difference between two subsequent events * in a <em>close</em> succession. */ default AwaitingEventStream<T> successionEnds(Duration timeout) { return reduceSuccessions((a, b) -> b, timeout); } /** * An analog to {@link #successionEnds(Duration)} to use outside of JavaFX * application thread. * @param timeout the maximum time difference between two subsequent events * in a <em>close</em> succession. * @param scheduler used to schedule timeout expiration * @param eventThreadExecutor executor that executes actions on the * thread on which this stream's events are emitted. The returned stream * will use this executor to emit events. */ default AwaitingEventStream<T> successionEnds( Duration timeout, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { return reduceSuccessions((a, b) -> b, timeout, scheduler, eventThreadExecutor); } /** * Returns an event stream that emits the first event emitted from this * stream and then, if the next event arrives within the given duration * since the last emitted event, it is converted to an accumulator value * using {@code initialTransformation}. Any further events that still * arrive within {@code duration} are accumulated to the accumulator value * using the given reduction function. After {@code duration} has passed * since the last emitted event, the accumulator value is deconstructed * into a series of events using the given {@code deconstruction} function * and these events are emitted, the accumulator value is cleared and any * events that arrive within {@code duration} are accumulated, and so on. */ default <A> AwaitingEventStream<T> thenAccumulateFor( Duration duration, Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> reduction, Function<? super A, List<T>> deconstruction) { return new ThenAccumulateForStream<>( this, initialTransformation, reduction, deconstruction, action -> FxTimer.create(duration, action)); } default <A> AwaitingEventStream<T> thenAccumulateFor( Duration duration, Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> reduction, Function<? super A, List<T>> deconstruction, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { Function<Runnable, Timer> timerFactory = action -> ScheduledExecutorServiceTimer.create( duration, action, scheduler, eventThreadExecutor); return new ThenAccumulateForStream<>( this, initialTransformation, reduction, deconstruction, timerFactory); } /** * A variant of * {@link #thenAccumulateFor(Duration, Function, BiFunction, Function)} * for cases when it is more convenient to provide a unit element for * accumulation than the initial transformation. */ default <A> AwaitingEventStream<T> thenAccumulateFor( Duration duration, Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> reduction, Function<? super A, List<T>> deconstruction) { Function<? super T, ? extends A> initialTransformation = t -> reduction.apply(unit.get(), t); return thenAccumulateFor( duration, initialTransformation, reduction, deconstruction); } default <A> AwaitingEventStream<T> thenAccumulateFor( Duration duration, Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> reduction, Function<? super A, List<T>> deconstruction, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { Function<? super T, ? extends A> initialTransformation = t -> reduction.apply(unit.get(), t); return thenAccumulateFor( duration, initialTransformation, reduction, deconstruction, scheduler, eventThreadExecutor); } /** * Returns an event stream that emits the first event emitted from this * stream and then reduces all following events that arrive within the * given duration into a single event using the given reduction function. * The resulting event, if any, is emitted after {@code duration} has * passed. Then again, any events that arrive within {@code duration} are * reduced into a single event, that is emitted after {@code duration} has * passed, and so on. */ default AwaitingEventStream<T> thenReduceFor( Duration duration, BinaryOperator<T> reduction) { return thenAccumulateFor( duration, Function.identity(), reduction, Collections::singletonList); } default AwaitingEventStream<T> thenReduceFor( Duration duration, BinaryOperator<T> reduction, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { return thenAccumulateFor( duration, Function.identity(), reduction, Collections::singletonList, scheduler, eventThreadExecutor); } /** * Returns an event stream that emits the first event emitted from this * stream and then remembers, but does not emit, the latest event emitted * from this stream. The remembered event is emitted after the given * duration from the last emitted event. This repeats after each emitted * event. */ default AwaitingEventStream<T> thenRetainLatestFor(Duration duration) { return thenReduceFor(duration, (a, b) -> b); } default AwaitingEventStream<T> thenRetainLatestFor( Duration duration, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { return thenReduceFor( duration, (a, b) -> b, scheduler, eventThreadExecutor); } /** * Returns an event stream that emits the first event emitted from this * stream and then ignores the following events for the given duration. * The first event that arrives after the given duration is emitted and * following events are ignored for the given duration again, and so on. */ default AwaitingEventStream<T> thenIgnoreFor(Duration duration) { return thenAccumulateFor( duration, t -> Collections.<T>emptyList(), (l, t) -> l, Function.<List<T>>identity()); } default AwaitingEventStream<T> thenIgnoreFor( Duration duration, ScheduledExecutorService scheduler, Executor eventThreadExecutor) { return thenAccumulateFor( duration, t -> Collections.<T>emptyList(), (l, t) -> l, Function.<List<T>>identity(), scheduler, eventThreadExecutor); } default <A> EventStream<T> onRecurseAccumulate( Function<? super T, ? extends A> initialTransformation, BiFunction<? super A, ? super T, ? extends A> reduction, Function<? super A, AccumulatorSize> size, Function<? super A, ? extends T> head, Function<? super A, ? extends A> tail) { return new RecursiveStream<T>( this, NotificationAccumulator.accumulativeStreamNotifications( size, head, tail, initialTransformation, reduction)); } default <A> EventStream<T> onRecurseAccumulate( Supplier<? extends A> unit, BiFunction<? super A, ? super T, ? extends A> reduction, Function<? super A, AccumulatorSize> size, Function<? super A, ? extends T> head, Function<? super A, ? extends A> tail) { Function<? super T, ? extends A> initialTransformation = t -> reduction.apply(unit.get(), t); return onRecurseAccumulate( initialTransformation, reduction, size, head, tail); } default EventStream<T> onRecurseReduce(BinaryOperator<T> reduction) { return new RecursiveStream<T>( this, NotificationAccumulator.reducingStreamNotifications(reduction)); } default EventStream<T> onRecurseQueue() { return new RecursiveStream<T>( this, NotificationAccumulator.queuingStreamNotifications()); } default EventStream<T> onRecurseRetainLatest() { return new RecursiveStream<T>(this, NotificationAccumulator.retainLatestStreamNotifications()); } /** * Transfers events from one thread to another. * Any event stream can only be accessed from a single thread. * This method allows to transfer events from one thread to another. * Any event emitted by this EventStream will be emitted by the returned * stream on a different thread. * @param sourceThreadExecutor executor that executes tasks on the thread * from which this EventStream is accessed. * @param targetThreadExecutor executor that executes tasks on the thread * from which the returned EventStream will be accessed. * @return Event stream that emits the same events as this EventStream, * but uses {@code targetThreadExecutor} to emit the events. */ default EventStream<T> threadBridge( Executor sourceThreadExecutor, Executor targetThreadExecutor) { return new ThreadBridge<T>(this, sourceThreadExecutor, targetThreadExecutor); } /** * Transfers events from the JavaFX application thread to another thread. * Equivalent to * {@code threadBridge(Platform::runLater, targetThreadExecutor)}. * @param targetThreadExecutor executor that executes tasks on the thread * from which the returned EventStream will be accessed. * @return Event stream that emits the same events as this EventStream, * but uses {@code targetThreadExecutor} to emit the events. * @see #threadBridge(Executor, Executor) */ default EventStream<T> threadBridgeFromFx(Executor targetThreadExecutor) { return threadBridge(Platform::runLater, targetThreadExecutor); } /** * Transfers events to the JavaFX application thread. * Equivalent to * {@code threadBridge(sourceThreadExecutor, Platform::runLater)}. * @param sourceThreadExecutor executor that executes tasks on the thread * from which this EventStream is accessed. * @return Event stream that emits the same events as this EventStream, * but emits them on the JavaFX application thread. * @see #threadBridge(Executor, Executor) */ default EventStream<T> threadBridgeToFx(Executor sourceThreadExecutor) { return threadBridge(sourceThreadExecutor, Platform::runLater); } /** * Returns a clone of this event stream guarded by the given guardians. * The returned event stream emits the same events as this event stream. * In addition to that, the emission of each event is guarded by the given * guardians: before the emission, guards are acquired in the given order; * after the emission, previously acquired guards are released in reverse * order. * @deprecated Use {@link #suspenderOf(Suspendable)} instead. */ @Deprecated default EventStream<T> guardedBy(Guardian... guardians) { return suspenderOf(Guardian.combine(guardians)::guard); } /** * Returns an event stream that emits the same events as this event stream, * but before each emission, suspends the given {@linkplain Suspendable} * and unsuspends it after the emission has completed. * * <p><strong>Experimental.</strong> The method itself is not experimental, * but the return type {@linkplain SuspenderStream} is. You may want to * assign the result to a variable of type {@code EventStream<T>} to remain * source compatible if the experimenal {@linkplain SuspenderStream} is * removed in the future. */ @Experimental default <S extends Suspendable> SuspenderStream<T, S> suspenderOf(S suspendable) { return new SuspenderStreamImpl<>(this, suspendable); } }
package com.macro.mall.bo; import com.macro.mall.model.UmsAdmin; import com.macro.mall.model.UmsResource; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class AdminUserDetails implements UserDetails { private UmsAdmin umsAdmin; private List<UmsResource> resourceList; public AdminUserDetails(UmsAdmin umsAdmin,List<UmsResource> resourceList) { this.umsAdmin = umsAdmin; this.resourceList = resourceList; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return resourceList.stream() .map(role ->new SimpleGrantedAuthority(role.getId()+":"+role.getName())) .collect(Collectors.toList()); } @Override public String getPassword() { return umsAdmin.getPassword(); } @Override public String getUsername() { return umsAdmin.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return umsAdmin.getStatus().equals(1); } }
package org.ktunaxa.referral.client.gui; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.smartgwt.client.data.DataSource; import com.smartgwt.client.data.DataSourceField; import com.smartgwt.client.data.Record; import com.smartgwt.client.data.fields.DataSourceTextField; import com.smartgwt.client.widgets.Window; import com.smartgwt.client.widgets.events.CloseClickHandler; import com.smartgwt.client.widgets.events.CloseClientEvent; import com.smartgwt.client.widgets.form.DynamicForm; import com.smartgwt.client.widgets.form.fields.SelectItem; import com.smartgwt.client.widgets.layout.VLayout; import org.geomajas.gwt.client.command.AbstractCommandCallback; import org.geomajas.gwt.client.command.GwtCommand; import org.geomajas.gwt.client.command.GwtCommandDispatcher; import org.geomajas.gwt.client.util.Html; import org.geomajas.gwt.client.util.HtmlBuilder; import org.geomajas.gwt.client.util.WidgetLayout; import org.geomajas.gwt.client.widget.KeepInScreenWindow; import org.geomajas.layer.feature.Feature; import org.geomajas.plugin.staticsecurity.command.dto.GetUsersRequest; import org.geomajas.plugin.staticsecurity.command.dto.GetUsersResponse; import org.ktunaxa.bpm.KtunaxaBpmConstant; import org.ktunaxa.referral.client.security.UserContext; import org.ktunaxa.referral.client.widget.AbstractCollapsibleListBlock; import org.ktunaxa.referral.server.command.dto.AssignTaskRequest; import org.ktunaxa.referral.server.command.dto.GetReferralResponse; import org.ktunaxa.referral.server.dto.TaskDto; import com.smartgwt.client.types.Cursor; import com.smartgwt.client.types.VerticalAlignment; import com.smartgwt.client.widgets.Button; import com.smartgwt.client.widgets.HTMLFlow; import com.smartgwt.client.widgets.IButton; import com.smartgwt.client.widgets.Img; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.layout.HLayout; import com.smartgwt.client.widgets.layout.LayoutSpacer; /** * Implementation of {@link AbstractCollapsibleListBlock} that handles {@link TaskDto} type objects. Instances of this * class will form the list of tasks on task tabs. Each block can collapse and expand. When collapsed only the * task title is visible. * * @author Pieter De Graef * @author Joachim Van der Auwera */ public class TaskBlock extends AbstractCollapsibleListBlock<TaskDto> { private static final String BLOCK_STYLE = "taskBlock"; private static final String BLOCK_CONTENT_STYLE = "taskBlockContent"; private static final String BLOCK_CONTENT_TABLE_STYLE = "taskBlockContentTable"; private static final String TITLE_STYLE = "taskBlockTitle"; private static final String BLOCK_STYLE_COLLAPSED = "taskBlockCollapsed"; private static final String TITLE_STYLE_COLLAPSED = "taskBlockTitleCollapsed"; private static final String STYLE_VARIABLE_NAME = "text-align:right; width:120px"; private static final String STYLE_VARIABLE_VALUE = "text-align:left"; private static final String IMAGE_MINIMIZE = "[ISOMORPHIC]/skins/ActivitiBlue/images/headerIcons/minimize.gif"; private static final String IMAGE_MAXIMIZE = "[ISOMORPHIC]/skins/ActivitiBlue/images/headerIcons/maximize.gif"; private static final String IMAGE_CLAIM = "[ISOMORPHIC]/images/task/claim.png"; private static final String IMAGE_START = "[ISOMORPHIC]/images/task/start.png"; private static final String IMAGE_ASSIGN = "[ISOMORPHIC]/images/task/assign.png"; private static final String FIELD_LABEL = "label"; private static final String FIELD_VALUE = "value"; private static final int DISABLED_OPACITY = 60; private HLayout title; private HTMLFlow content; private Img titleImage = new Img(IMAGE_MINIMIZE, 16, 16); private IButton startButton = new IButton(); private IButton claimButton = new IButton(); // Constructors: public TaskBlock(TaskDto task) { super(task); buildGui(task); } // CollapsableBlock implementation: /** Expand the task block, displaying everything. */ public void expand() { setStyleName(BLOCK_STYLE); title.setStyleName(TITLE_STYLE); titleImage.setSrc(IMAGE_MINIMIZE); content.setVisible(true); } /** Collapse the task block, leaving only the title visible. */ public void collapse() { setStyleName(BLOCK_STYLE_COLLAPSED); title.setStyleName(TITLE_STYLE_COLLAPSED); titleImage.setSrc(IMAGE_MAXIMIZE); content.setVisible(false); } /** * Search the task for a given text string. This method will search through the title, content, checkedContent * and name of the user. * * @param text * The text to search for * @return Returns true if the text has been found somewhere. */ public boolean containsText(String text) { if (text != null) { String lcText = text.toLowerCase(); String compare; compare = getObject().getName(); if (null != compare && compare.toLowerCase().contains(lcText)) { return true; } compare = getObject().getDescription(); if (null != compare && compare.toLowerCase().contains(lcText)) { return true; } compare = getObject().getAssignee(); if (null != compare && compare.toLowerCase().contains(lcText)) { return true; } for (String test : getObject().getVariables().values()) { if (null != test && test.toLowerCase().contains(lcText)) { return true; } } } return false; } public Button getEditButton() { return null; } @Override public void setDisabled(boolean disabled) { super.setDisabled(disabled); if (disabled) { this.setOpacity(DISABLED_OPACITY); this.content.setOpacity(DISABLED_OPACITY); } } // Private methods: private void buildGui(final TaskDto task) { Map<String, String> variables = task.getVariables(); setStyleName(BLOCK_STYLE); title = new HLayout(LayoutConstant.MARGIN_LARGE); title.setSize(LayoutConstant.BLOCK_TITLE_WIDTH, LayoutConstant.BLOCK_TITLE_HEIGHT); title.setLayoutLeftMargin(LayoutConstant.MARGIN_LARGE); title.setStyleName(TITLE_STYLE); title.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { if (content.isVisible()) { collapse(); } else { expand(); } } }); title.setCursor(Cursor.HAND); titleImage.setLayoutAlign(VerticalAlignment.CENTER); title.addMember(titleImage); String titlePrefix; if (task.isHistory()) { titlePrefix = ""; } else { titlePrefix = variables.get(KtunaxaBpmConstant.VAR_REFERRAL_ID) + ": "; } HTMLFlow titleText = new HTMLFlow("<div class='taskBlockTitleText'>" + titlePrefix + HtmlBuilder.htmlEncode(task.getName()) + "</div>"); titleText.setSize(LayoutConstant.BLOCK_TITLE_WIDTH, LayoutConstant.BLOCK_TITLE_HEIGHT); title.addMember(titleText); addMember(title); HLayout infoLayout = new HLayout(LayoutConstant.MARGIN_SMALL); infoLayout.setLayoutRightMargin(LayoutConstant.MARGIN_SMALL); infoLayout.setLayoutTopMargin(LayoutConstant.MARGIN_SMALL); HTMLFlow info = new HTMLFlow( HtmlBuilder.divClassHtmlContent("taskBlockInfo", HtmlBuilder.htmlEncode(task.getDescription()) + "<br />Referral: " + HtmlBuilder.tagClass(Html.Tag.SPAN, "taskBlockInfoBold", variables.get(KtunaxaBpmConstant.VAR_REFERRAL_NAME)))); info.setSize(LayoutConstant.BLOCK_INFO_WIDTH, LayoutConstant.BLOCK_INFO_HEIGHT); infoLayout.addMember(info); infoLayout.addMember(new LayoutSpacer()); final String me = UserContext.getInstance().getUser(); startButton.setIcon(IMAGE_START); startButton.setShowDisabledIcon(true); startButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH); startButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT); startButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH); startButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT); startButton.setPrompt("Start"); startButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH); startButton.setLayoutAlign(VerticalAlignment.CENTER); startButton.setShowRollOver(false); setStartButtonStatus(task); startButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { assign(getObject(), me, true); } }); infoLayout.addMember(startButton); IButton assignButton = new IButton(); assignButton.setIcon(IMAGE_ASSIGN); assignButton.setShowDisabledIcon(true); assignButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH); assignButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT); assignButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH); assignButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT); assignButton.setPrompt("Assign"); assignButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH); assignButton.setLayoutAlign(VerticalAlignment.CENTER); assignButton.setShowRollOver(false); if (!UserContext.getInstance().isReferralManager() || task.isHistory()) { // disable when no rights to assign or assign is impossible assignButton.setDisabled(true); } assignButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent clickEvent) { GwtCommand command = new GwtCommand(GetUsersRequest.COMMAND); GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetUsersResponse>() { public void execute(GetUsersResponse response) { assignWindow(task, response, clickEvent); } }); } }); infoLayout.addMember(assignButton); claimButton.setIcon(IMAGE_CLAIM); claimButton.setShowDisabledIcon(true); claimButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH); claimButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT); claimButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH); claimButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT); claimButton.setPrompt("Claim"); claimButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH); claimButton.setLayoutAlign(VerticalAlignment.CENTER); claimButton.setShowRollOver(false); claimButton.setDisabled(task.isHistory() | (null != task.getAssignee())); claimButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { assign(getObject(), me, false); } }); infoLayout.addMember(claimButton); addMember(infoLayout); List<String> rows = new ArrayList<String>(); String engagementLevel = variables.get(KtunaxaBpmConstant.VAR_ENGAGEMENT_LEVEL); if (task.isHistory()) { rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Assignee: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getAssignee()))); rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Started: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getStartTime() + ""))); // NOSONAR cfr GWT rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Assignee: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getEndTime() + ""))); // NOSONAR cfr GWT } else { rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Assignee: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getAssignee()))); rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Created: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getCreateTime() + ""))); // NOSONAR cfr GWT rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Completion deadline: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, variables.get(KtunaxaBpmConstant.VAR_COMPLETION_DEADLINE)))); rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "E-mail: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, variables.get(KtunaxaBpmConstant.VAR_EMAIL)))); } if (null != engagementLevel) { String engagementContent = engagementLevel + " (prov " + variables.get(KtunaxaBpmConstant.VAR_PROVINCE_ENGAGEMENT_LEVEL) + ")"; rows.add(HtmlBuilder.trHtmlContent( HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Engagement level: "), HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, engagementContent))); } // Simple 'list to array' code block. Exact array.length unknown until after // the engagementLevel has been checked for null. String[] array = new String[rows.size()]; for (int i = 0; i < array.length; i++) { array[i] = rows.get(i); } String htmlContent = HtmlBuilder.tableClassHtmlContent(BLOCK_CONTENT_TABLE_STYLE, array); content = new HTMLFlow(htmlContent); content.setStyleName(BLOCK_CONTENT_STYLE); content.setWidth100(); addMember(content); } private void assignWindow(TaskDto task, GetUsersResponse response, ClickEvent clickEvent) { final Window assignWindow = new KeepInScreenWindow(); assignWindow.setTitle("Assign task for " + task.getVariables().get(KtunaxaBpmConstant.VAR_REFERRAL_ID)); assignWindow.setAutoSize(true); assignWindow.setCanDragReposition(true); assignWindow.setCanDragResize(false); assignWindow.setShowMinimizeButton(false); assignWindow.setModalMaskOpacity(WidgetLayout.modalMaskOpacity); assignWindow.setShowModalMask(true); assignWindow.setIsModal(true); assignWindow.addCloseClickHandler(new CloseClickHandler() { public void onCloseClick(CloseClientEvent closeClientEvent) { assignWindow.destroy(); } }); assignWindow.setLeft(clickEvent.getX()); assignWindow.setTop(clickEvent.getY()); VLayout layout = new VLayout(WidgetLayout.marginLarge); HTMLFlow label = new HTMLFlow(HtmlBuilder.htmlEncode(task.getName())); label.setWidth100(); layout.addMember(label); // add select box with users final SelectItem users = new SelectItem("User", "User"); users.setDefaultToFirstOption(true); users.setOptionDataSource(getUsersSelectDataSource(response)); users.setDisplayField(FIELD_LABEL); users.setValueField(FIELD_VALUE); DynamicForm usersForm = new DynamicForm(); usersForm.setFields(users); layout.addMember(usersForm); HLayout buttons = new HLayout(WidgetLayout.marginSmall); buttons.setWidth100(); buttons.setHeight(1); LayoutSpacer spacer = new LayoutSpacer(); spacer.setWidth(60); buttons.addMember(spacer); Button assignButton = new Button("Assign"); assignButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { assign(getObject(), users.getValueAsString(), false); assignWindow.destroy(); } }); buttons.addMember(assignButton); Button cancelButton = new Button("Cancel"); cancelButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent clickEvent) { assignWindow.destroy(); } }); buttons.addMember(cancelButton); layout.addMember(buttons); assignWindow.addItem(layout); assignWindow.draw(); } private DataSource getUsersSelectDataSource(GetUsersResponse response) { DataSource dataSource = new DataSource(); dataSource.setClientOnly(true); DataSourceField label = new DataSourceTextField(FIELD_LABEL); DataSourceField regex = new DataSourceTextField(FIELD_VALUE); dataSource.setFields(label, regex); String me = UserContext.getInstance().getUser(); for (String user : response.getUsers()) { if (!me.equals(user)) { Record record = new Record(); record.setAttribute(FIELD_LABEL, user); record.setAttribute(FIELD_VALUE, user); dataSource.addData(record); } } return dataSource; } private void setClaimButtonStatus(TaskDto task) { // disable when history or already assigned claimButton.setDisabled(task.isHistory() | (null != task.getAssignee())); } private void setStartButtonStatus(TaskDto task) { String me = UserContext.getInstance().getUser(); // disable when history or assigned to someone else startButton.setDisabled(task.isHistory() | (null != task.getAssignee() && !me.equals(task.getAssignee()))); } private void assign(final TaskDto task, final String assignee, final boolean start) { AssignTaskRequest request = new AssignTaskRequest(); request.setTaskId(task.getId()); request.setAssignee(assignee); GwtCommand command = new GwtCommand(AssignTaskRequest.COMMAND); command.setCommandRequest(request); GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetReferralResponse>() { public void execute(GetReferralResponse response) { setStartButtonStatus(task); setClaimButtonStatus(task); if (start) { start(task, response.getReferral()); } else { TaskBlock.this.setDisabled(true); } } }); } private void start(TaskDto task, Feature referral) { MapLayout mapLayout = MapLayout.getInstance(); mapLayout.setReferralAndTask(referral, task); } }
package com.illposed.osc; import java.util.Date; /** * Allows to listen to incoming messages that match some selector pattern. * In OSC speak, this is a Method, and it listens to Messages. * * @author Chandrasekhar Ramakrishnan */ public interface OSCListener { /** * Process a matching, incoming OSC Message. * @param time The time this message is to be executed. * <code>null</code> means: process immediately * @param message The message to process. */ public void acceptMessage(Date time, OSCMessage message); }
package main.java.elegit; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.layout.Pane; import javafx.stage.Stage; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URI; /** * The starting point for this JavaFX application. */ public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ System.setProperty("log4j.configurationFile", "src/main/resources/elegit/config/log4j2.xml"); final Logger logger = LogManager.getLogger(); File logConfigFile = new File( "src/main/resources/elegit/config/log4j2.xml" ); try { FileInputStream fis = new FileInputStream( logConfigFile ); XmlConfigurationFactory fc = new XmlConfigurationFactory( ); fc.getConfiguration( new ConfigurationSource( fis ) ); URI configuration = logConfigFile.toURI(); Configurator.initialize("config", null, configuration); org.apache.logging.log4j.core.LoggerContext ctx = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext( true ); ctx.reconfigure(); } catch (FileNotFoundException e) { e.printStackTrace(); } logger.info("Starting up."); Pane root = FXMLLoader.load(getClass().getResource ("/elegit/fxml/MainView.fxml")); primaryStage.setTitle("Elegit"); primaryStage.setOnCloseRequest(event -> logger.info("Closed")); BusyWindow.setParentWindow(primaryStage); Scene scene = new Scene(root, 1200, 650); // width, height // create the menu here MenuBar menuBar = new MenuBar(); Menu menuFile = new Menu("File"); Menu menuEdit = new Menu("Edit"); menuBar.getMenus().addAll(menuFile, menuEdit); ((Pane) scene.getRoot()).getChildren().addAll(menuBar); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
package hex; import hex.DGLM.Family; import hex.DGLM.GLMModel; import hex.DGLM.GLMParams; import hex.DLSM.ADMMSolver; import java.util.*; import jsr166y.CountedCompleter; import water.*; import water.H2O.H2OCountedCompleter; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class GLMGrid extends Job { Key _datakey; // Data to work on transient ValueArray _ary; // Expanded VA bits int _xs[]; // Array of columns to use double[] _lambdas; // Grid search values double[] _ts; // Thresholds double[] _alphas; // Grid search values int _xfold; GLMParams _glmp; public GLMGrid(Key dest, ValueArray va, GLMParams glmp, int[] xs, double[] ls, double[] as, double[] thresholds, int xfold) { super("GLMGrid", dest); _ary = va; // VA is large, and already in a Key so make it transient _datakey = va._key; // ... and use the data key instead when reloading _glmp = glmp; _xs = xs; _lambdas = ls; Arrays.sort(_lambdas); _ts = thresholds; _alphas = as; _xfold = xfold; _glmp.checkResponseCol(_ary._cols[xs[xs.length-1]], new ArrayList<String>()); // ignore warnings here, they will be shown for each mdoel anyways } private class GridTask extends H2OCountedCompleter { final int _aidx; GridTask(int aidx) { _aidx = aidx; } @Override public void compute2() { double [] beta = null; Futures fs = new Futures(); try { for( int l1 = 1; l1 <= _lambdas.length; l1++ ) { if(cancelled()) break; GLMModel m = do_task(beta,_lambdas.length-l1,_aidx); // Do a step; get a model beta = m._normBeta.clone(); update(dest(), m, (_lambdas.length-l1) * _alphas.length + _aidx, System.currentTimeMillis() - _startTime,fs); } fs.blockForPending(); }finally { tryComplete(); } } } @Override public void start() { super.start(); UKV.put(dest(), new GLMModels(_lambdas.length * _alphas.length)); final int N = _alphas.length; H2O.submitTask(new H2OCountedCompleter() { @Override public void compute2() { setPendingCount(N); for( int a = 0; a < _alphas.length; a++ ){ GridTask t = new GridTask(a); t.setCompleter(this); H2O.submitTask(t); } tryComplete(); // This task is done } @Override public void onCompletion(CountedCompleter caller){remove();} }); } // Update dest for a new model. In a static function, to avoid closing // over the 'this' pointer of a GLMGrid and thus serializing it as part // of the atomic update. private static void update(Key dest, GLMModel m, final int idx, final long runTime, Futures fs) { final Model model = m; fs.add(new TAtomic<GLMModels>() { @Override public GLMModels atomic(GLMModels old) { old._ms[idx] = model._selfKey; old._count++; old._runTime = Math.max(runTime,old._runTime); return old; } }.fork(dest)); } // Do a single step (blocking). // In this case, run 1 GLM model. private GLMModel do_task(double [] beta, int l, int alpha) { GLMModel m = DGLM.buildModel(DGLM.getData(_ary, _xs, null, true), new ADMMSolver(_lambdas[l], _alphas[alpha]), _glmp,beta); if( _xfold <= 1 ) m.validateOn(_ary, null, _ts); else m.xvalidate(_ary, _xfold, _ts); return m; } public static class GLMModels extends Iced implements Progress { // The computed GLM models: product of length of lamda1s,lambda2s,rhos,alphas Key[] _ms; int _count; long _runTime = 0; public final long runTime(){return _runTime;} GLMModels(int length) { _ms = new Key[length]; } GLMModels() { } @Override public float progress() { return _count / (float) _ms.length; } public Iterable<GLMModel> sorted() { // NOTE: deserialized object is now kept in KV, so we can not modify it here. // We have to create our own private copy before sort! Key [] ms = _ms.clone(); Arrays.sort(ms, new Comparator<Key>() { @Override public int compare(Key k1, Key k2) { Value v1 = null, v2 = null; if( k1 != null ) v1 = DKV.get(k1); if( k2 != null ) v2 = DKV.get(k2); if( v1 == null && v2 == null ) return 0; if( v1 == null ) return 1; // drive the nulls to the end if( v2 == null ) return -1; GLMModel m1 = v1.get(); GLMModel m2 = v2.get(); if( m1._glmParams._family == Family.binomial ) { double cval1 = m1._vals[0].AUC(), cval2 = m2._vals[0].AUC(); if( cval1 == cval2 ) { if( m1._vals[0].classError() != null ) { double[] cerr1 = m1._vals[0].classError(), cerr2 = m2._vals[0].classError(); assert (cerr2 != null && cerr1.length == cerr2.length); for( int i = 0; i < cerr1.length; ++i ) { cval1 += cerr1[i]; cval2 += cerr2[i]; } } if( cval1 == cval2 ) { cval1 = m1._vals[0].err(); cval2 = m2._vals[0].err(); } } return Double.compare(cval2, cval1); } else return Double.compare(m1._vals[0]._err, m2._vals[0]._err); } }); final Key[] keys = ms; int lastIdx = ms.length; for( int i = 0; i < ms.length; ++i ) { if( keys[i] == null || DKV.get(keys[i]) == null ) { lastIdx = i; break; } } final int N = lastIdx; return new Iterable<GLMModel>() { @Override public Iterator<GLMModel> iterator() { return new Iterator<GLMModel>() { int _idx = 0; @Override public GLMModel next() { return DKV.get(keys[_idx++]).get(); } @Override public boolean hasNext() { return _idx < N; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } // Convert all models to Json (expensive!) public JsonObject toJson() { JsonObject j = new JsonObject(); // sort models according to their performance JsonArray arr = new JsonArray(); for( GLMModel m : sorted() ) arr.add(m.toJson()); j.add("models", arr); return j; } } }
package mjc; import java.io.BufferedWriter; import java.io.IOException; import java.io.PushbackReader; import java.io.FileReader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import mjc.jasmin.JasminGenerator; import mjc.jasmin.JasminHandler; import mjc.lexer.Lexer; import mjc.lexer.LexerException; import mjc.parser.Parser; import mjc.parser.ParserException; import mjc.symbol.SymbolTable; import mjc.node.InvalidToken; import mjc.node.Node; import mjc.analysis.ASTGraphPrinter; import mjc.analysis.ASTPrinter; import mjc.analysis.SymbolTableBuilder; import mjc.analysis.TypeChecker; import mjc.error.MiniJavaError; import static mjc.error.MiniJavaErrorType.LEXER_ERROR; import static mjc.error.MiniJavaErrorType.PARSER_ERROR; public class JVMMain { private final static CommandLineParser commandLineParser = new GnuParser(); private final static HelpFormatter helpFormatter = new HelpFormatter(); private final static Options options = new Options(); private final ASTPrinter astPrinter = new ASTPrinter(); private final ASTGraphPrinter graphPrinter = new ASTGraphPrinter(); public JVMMain() { options.addOption("S", false, "output Jasmin assembly code"); options.addOption("p", false, "print abstract syntax tree"); options.addOption("g", false, "print abstract syntax tree in GraphViz format"); options.addOption("s", false, "print symbol table"); options.addOption("h", false, "show help message"); helpFormatter.setOptionComparator(new OptionComparator<Option>()); } public static void main(String[] args) { JVMMain main = new JVMMain(); try { // Run the compiler. if (!main.run(args)) { System.exit(1); } } catch (ParseException e) { printHelp(); System.exit(1); } } /** * Run compiler with the given command line arguments. * * @param args Command line arguments. * @return true if compilation succeeded, otherwise false. * @throws ParseException if parsing of command line arguments failed. */ private boolean run(String[] args) throws ParseException { final CommandLine commandLine = commandLineParser.parse(options, args); if (commandLine.hasOption("h")) { printHelp(); return true; } if (commandLine.getArgs().length != 1) { printHelp(); return false; } final Node ast; try { final String fileName = commandLine.getArgs()[0]; final PushbackReader reader = new PushbackReader(new FileReader(fileName)); final Parser parser = new Parser(new Lexer(reader)); ast = parser.parse(); } catch (LexerException e) { final InvalidToken token = e.getToken(); final int line = token.getLine(); final int column = token.getPos(); System.err.println(LEXER_ERROR.on(line, column, token.getText())); return false; } catch (ParserException e) { System.err.println(PARSER_ERROR.on(e.getLine(), e.getPos(), e.getError())); return false; } catch (IOException e) { System.err.println(e.getMessage()); return false; } if (commandLine.hasOption("p")) astPrinter.print(ast); if (commandLine.hasOption("g")) graphPrinter.print(ast); // Build symbol table. final SymbolTableBuilder builder = new SymbolTableBuilder(); final SymbolTable symbolTable = builder.build(ast); if (builder.hasErrors()) { for (MiniJavaError error : builder.getErrors()) { System.err.println(error); } } if (commandLine.hasOption("s")) System.out.println(symbolTable); // Run type-check. final TypeChecker typeChecker = new TypeChecker(); if (!typeChecker.check(ast, symbolTable)) { for (MiniJavaError error : typeChecker.getErrors()) { System.err.println(error); } } if (builder.hasErrors() || typeChecker.hasErrors()) { return false; // Abort compilation. } final JasminGenerator generator = new JasminGenerator(new JasminHandler() { public void handle(String className, StringBuilder code) { // Write to .j file. final Path path = Paths.get(className + ".j"); final Charset charset = StandardCharsets.UTF_8; try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) { writer.append(code); } catch (IOException e) { e.printStackTrace(); } if (!commandLine.hasOption("S")) { // Invoke Jasmin to assemble the file. jasmin.Main.main(new String[] { className + ".j" }); } } }); generator.generate(ast, symbolTable, typeChecker.getTypes()); return true; } /** * Prints a help message to standard output. */ private static void printHelp() { helpFormatter.printHelp("mjc <infile> [options]", options); } // Comparator for Options, to get them in the order we want in help output. class OptionComparator<T extends Option> implements Comparator<T> { private static final String ORDER = "Spgsh"; @Override public int compare(T option1, T option2) { return ORDER.indexOf(option1.getOpt()) - ORDER.indexOf(option2.getOpt()); } } }
package mundo; /** * Clase grafo * @author lesanmartin * */ public class Grafo { private int cantidadDeNodos; private int cantidadDeNodosTotal; private Nodo[] nodos; /** * Constructor de la clase * * @param cantidadDeNodosTotal parametros cantidaDeNodosTotal */ public Grafo(final int cantidadDeNodosTotal) { cantidadDeNodos = 0; nodos = new Nodo[cantidadDeNodosTotal]; this.cantidadDeNodosTotal = cantidadDeNodosTotal; } /** * Agrega un nodo * * @param nodo parametros nodo */ public void agregarNodo(final Nodo nodo) { nodos[cantidadDeNodos++] = nodo; } /** * Agrega nodos adyacentes * * @param nodoUno parametros nodoUno * @param nodoDos parametros nodoDos */ public void agregarAdyacentes(final Nodo nodoUno,final Nodo nodoDos) { nodoUno.agregarAdyacente(nodoDos); } /** * Devuelve los nodos * * @return nodos */ public Nodo[] obtenerNodos() { return nodos; } /** * Retorna la cantidad de nodos * * @return cantidadDeNodos */ public int obtenerCantidadDeNodos() { return cantidadDeNodos; } /** * Retorna la cantidad total de nodos * * @return cantidadDeNodosTotal */ public int obtenerCantidadDeNodosTotal() { return cantidadDeNodosTotal; } }
package hudson.remoting; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.Socket; import java.net.URL; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.List; import java.util.Collections; /** * Slave agent engine that proactively connects to Hudson master. * * @author Kohsuke Kawaguchi */ public class Engine extends Thread { /** * Thread pool that sets {@link #CURRENT}. */ private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() { private final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); public Thread newThread(final Runnable r) { return defaultFactory.newThread(new Runnable() { public void run() { CURRENT.set(Engine.this); r.run(); } }); } }); public final EngineListener listener; private List<URL> candidateUrls; private URL hudsonUrl; private final String secretKey; public final String slaveName; /** * See Main#tunnel in the jnlp-agent module for the details. */ private String tunnel; public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String slaveName) { this.listener = listener; this.candidateUrls = hudsonUrls; this.secretKey = secretKey; this.slaveName = slaveName; if(candidateUrls.isEmpty()) throw new IllegalArgumentException("No URLs given"); } public URL getHudsonUrl() { return hudsonUrl; } public void setTunnel(String tunnel) { this.tunnel = tunnel; } public void run() { try { while(true) { listener.status("Locating Server"); Exception firstError=null; String port=null; for (URL url : candidateUrls) { String s = url.toExternalForm(); if(!s.endsWith("/")) s+='/'; URL salURL = new URL(s+"tcpSlaveAgentListener/"); // find out the TCP port HttpURLConnection con = (HttpURLConnection)salURL.openConnection(); con.connect(); port = con.getHeaderField("X-Hudson-JNLP-Port"); if(con.getResponseCode()!=200) { if(firstError==null) firstError = new Exception(salURL+" is invalid: "+con.getResponseCode()+" "+con.getResponseMessage()); continue; } if(port ==null) { if(firstError==null) firstError = new Exception(url+" is not Hudson"); continue; } // this URL works. From now on, only try this URL hudsonUrl = url; candidateUrls = Collections.singletonList(hudsonUrl); break; } if(firstError!=null) { listener.error(firstError); return; } Socket s = connect(port); listener.status("Handshaking"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:JNLP-connect"); dos.writeUTF(secretKey); dos.writeUTF(slaveName); Channel channel = new Channel("channel", executor, new BufferedInputStream(s.getInputStream()), new BufferedOutputStream(s.getOutputStream())); listener.status("Connected"); channel.join(); listener.status("Terminated"); listener.onDisconnect(); // try to connect back to the server every 10 secs. waitForServerToBack(); } } catch (Throwable e) { listener.error(e); } } /** * Connects to TCP slave port, with a few retries. */ private Socket connect(String port) throws IOException, InterruptedException { String host = this.hudsonUrl.getHost(); if(tunnel!=null) { String[] tokens = tunnel.split(":",3); if(tokens.length!=2) throw new IOException("Illegal tunneling parameter: "+tunnel); if(tokens[0].length()>0) host = tokens[0]; if(tokens[1].length()>0) port = tokens[1]; } String msg = "Connecting to " + host + ':' + port; listener.status(msg); int retry = 1; while(true) { try { return new Socket(host, Integer.parseInt(port)); } catch (IOException e) { if(retry++>10) throw e; Thread.sleep(1000*10); listener.status(msg+" (retrying:"+retry+")"); } } } /** * Waits for the server to come back. */ private void waitForServerToBack() throws InterruptedException { while(true) { Thread.sleep(1000*10); try { HttpURLConnection con = (HttpURLConnection)hudsonUrl.openConnection(); con.connect(); if(con.getResponseCode()==200) return; } catch (IOException e) { // retry } } } /** * When invoked from within remoted {@link Callable} (that is, * from the thread that carries out the remote requests), * this method returns the {@link Engine} in which the remote operations * run. */ public static Engine current() { return CURRENT.get(); } private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<Engine>(); }
package SimpleWithButtons; import Gui2D.WizardOfTreldan; import TWoT_A1.*; import static TWoT_A1.EquippableItem.EItem.*; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; import javafx.application.Application; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.ProgressBar; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.effect.DropShadow; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.scene.image.Image; import static javafx.application.Application.launch; /** * * @author Mathias */ public class GUIFX extends Application { private TWoT twot; private TextArea textArea; private TextArea statsArea; private ProgressBar healthbar; private String help; private TextField nameArea; private VBox statsField = new VBox(20); private Label label1; private Group walkButtons = new Group(); private int pos = 120; private Label endScore; private Stage primaryStage; private Scene endMenu; private TableView<InventoryItems> invTable = new TableView(); private final ObservableList<InventoryItems> invData = FXCollections.observableArrayList(); private TableView<EquippedItems> equipTable = new TableView(); private final ObservableList<EquippedItems> equipData = FXCollections.observableArrayList(); private String printHelp() { HashMap<String, String> printHelpMSG = twot.getHelpMessages(); return printHelpMSG.get("helpMessage1") + printHelpMSG.get("helpMessage2") + printHelpMSG.get("helpMessage3"); } public GUIFX () { twot = new TWoT(); } public static void main(String[] args) { launch(args); } @Override public void start (Stage primaryStage) { primaryStage.getIcons().add(new Image("icon.png")); this.primaryStage = primaryStage; this.primaryStage.setTitle("The Wizard of Treldan"); textArea = new TextArea(); statsArea = new TextArea(); /** * Main menu buttons */ Button button_play = new Button("NEW GAME"); Button button_load = new Button("LOAD GAME"); Button button_how = new Button("HOW TO PLAY"); Button button_highscore = new Button("HIGHSCORES"); Button button_exitMenu = new Button("EXIT GAME"); button_play.setMinWidth(180); button_load.setMinWidth(180); button_how.setMinWidth(180); button_exitMenu.setMinWidth(180); button_highscore.setMinWidth(180); button_play.setMinHeight(30); button_load.setMinHeight(30); button_how.setMinHeight(30); button_exitMenu.setMinHeight(30); button_highscore.setMinHeight(30); /** * Name scene visuals */ Label setName = new Label("ENTER YOUR NAME: "); nameArea = new TextField(); /** * Loadscreen buttons and list of loads */ Button button_loadGame = new Button("Load Game"); Button button_exitToMenu = new Button("Exit To Menu"); button_loadGame.setMinWidth(180); button_exitToMenu.setMinWidth(180); button_loadGame.setMinHeight(40); button_exitToMenu.setMinHeight(40); Pane anchorpane = new Pane(); ListView<AnchorPane> list = new ListView(); ObservableList<AnchorPane> loads = FXCollections.observableArrayList (); List<String> loadList = getLoadList(); for(String i: loadList){ //add a new anchorpane with a Text component to the ObservableList AnchorPane t = new AnchorPane(); Text itemName = new Text(i); itemName.relocate(0, 3); t.getChildren().add(itemName); loads.add(t); } //add the ObservableList to the ListView list.setItems(loads); //add the ListView to the pane. list.setPrefWidth(250); list.setPrefHeight(288); anchorpane.getChildren().add(list); /** * scene1 buttons */ Button button_clear = new Button("Clear"); Button button_help = new Button("Help"); Button button_exit = new Button("Exit"); Button button_save = new Button("Save"); Button button_use = new Button("Use Item"); Button button_equip = new Button("Equip Item"); button_help.setMaxWidth(90); button_exit.setMaxWidth(90); button_clear.setMaxWidth(90); button_use.setMaxWidth(90); button_equip.setMaxWidth(90); button_save.setMaxWidth(90); healthbar = new ProgressBar(twot.getPlayerHealth()/100); label1 = new Label("Health "+ twot.getPlayerHealth()); /** * End menu */ Button button_endGameExitGame = new Button("Exit Game"); endScore = new Label(); button_endGameExitGame.setMinWidth(180); button_endGameExitGame.setMinHeight(40); endScore.setLayoutX(110); endScore.setLayoutY(80); button_endGameExitGame.setLayoutX(170); button_endGameExitGame.setLayoutY(150); /** * Inventory list */ invTable.setEditable(true); List<Item> l = twot.getInventoryItems(); for(Item i: l){ if(i instanceof UseableItem){ invData.add(new InventoryItems(i.getItemName(), "Usable Item", i.getItemDescription())); } else if (i instanceof QuestItem) { invData.add(new InventoryItems(i.getItemName(), "Quest Item", i.getItemDescription())); } else if(i instanceof EquippableItem) { invData.add(new InventoryItems(i.getItemName(), "Equippable Item", i.getItemDescription())); } } TableColumn itemName = new TableColumn("Item Name"); itemName.setMinWidth(100); itemName.setCellValueFactory( new PropertyValueFactory<InventoryItems, String>("itemName")); TableColumn itemType = new TableColumn("Item Type"); itemType.setMinWidth(100); itemType.setCellValueFactory( new PropertyValueFactory<InventoryItems, String>("itemType")); TableColumn itemDescription = new TableColumn("Description"); itemDescription.setMinWidth(200); itemDescription.setCellValueFactory( new PropertyValueFactory<InventoryItems, String>("itemDesc")); /** * Nodes */ /** * Layouts for game scene */ HBox invButtons = new HBox(20); invButtons.setLayoutX(770 + pos); invButtons.setLayoutY(420); invButtons.getChildren().addAll(button_use, button_equip); VBox loadMenuButtons = new VBox(20); loadMenuButtons.setLayoutX(295); loadMenuButtons.setLayoutY(70); loadMenuButtons.getChildren().addAll(button_loadGame, button_exitToMenu); VBox gameButtons = new VBox(20); gameButtons.setLayoutX(591 + pos); gameButtons.setLayoutY(10); gameButtons.getChildren().addAll(button_clear, button_help, button_save, button_exit); VBox menuButtons = new VBox(20); menuButtons.setLayoutX(166); menuButtons.setLayoutY(30); menuButtons.getChildren().addAll(button_play, button_load, button_how, button_highscore, button_exitMenu); invTable.setItems(invData); invTable.getColumns().addAll(itemName, itemType, itemDescription); invTable.setLayoutX(652 + pos); healthbar.setStyle("-fx-accent: red;"); healthbar.setPrefSize(256, 26); healthbar.relocate(0 + pos, 265); label1.setTextFill(Color.web("BLACK")); label1.relocate(10 + pos, 269); /** * Buttons for the main menu */ /** * Label * Name area field * Added to VBox */ VBox nameField = new VBox(); nameField.setMaxWidth(300); nameField.setMinWidth(300); nameField.setMaxHeight(50); nameField.setMinHeight(50); nameField.relocate(106, 119); nameField.getChildren().addAll(setName, nameArea); /** * Textarea for the playing scene */ VBox outputField = new VBox(20); textArea.setMaxWidth(572); outputField.setLayoutX(pos); textArea.setMinWidth(572); textArea.setMinHeight(258); textArea.setMaxHeight(258); textArea.setWrapText(true); textArea.setEditable(false); outputField.getChildren().addAll(textArea); /** * Equipped items list */ equipTable.setEditable(false); HashMap<EquippableItem.EItem, EquippableItem> k = twot.getEquippableItems(); for(Map.Entry<EquippableItem.EItem, EquippableItem> entry : k.entrySet()){ if(entry.getKey() == AMULET_SLOT) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Amulet Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (HEAD_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Head slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (WEAPON_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Weapon Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (CHEST_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Chest Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (LEG_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Leg Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (BOOT_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Boot Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (GLOVES_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Glove Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (RING_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Ring Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); } } TableColumn itemNames = new TableColumn("Item Name"); itemNames.setMinWidth(100); itemNames.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemNames")); TableColumn itemSlot = new TableColumn("Item Slot"); itemSlot.setMinWidth(90); itemSlot.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemSlots")); TableColumn itemAttack = new TableColumn("Attack"); itemAttack.setMaxWidth(90); itemAttack.setMinWidth(90); itemAttack.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemAttack")); TableColumn itemDefence = new TableColumn("Defence"); itemDefence.setMaxWidth(90); itemDefence.setMinWidth(90); itemDefence.setCellValueFactory( new PropertyValueFactory<EquippedItems, String>("itemDefence")); equipTable.setItems(equipData); equipTable.getColumns().addAll(itemNames, itemSlot, itemAttack, itemDefence); equipTable.setLayoutX(264 + pos); equipTable.setLayoutY(265); equipTable.setMinWidth(370); equipTable.setMaxWidth(370); equipTable.setMinHeight(235); equipTable.setMaxHeight(235); /** * Statsarea on the playing scene */ NumberFormat df = new DecimalFormat(" statsArea.appendText("****************************\n"); statsArea.appendText("** Player name: " + twot.getPlayerName() + "\n"); statsArea.appendText("** Attack value: " + df.format(twot.getPlayerAtt()) + "\n"); statsArea.appendText("** Defense value: " + df.format(twot.getPlayerDeff()) + "\n"); statsArea.appendText("** Gold: " + twot.getPlayerGold() + "\n"); statsArea.appendText("****************************"); statsField.setMaxWidth(256); statsField.setMaxHeight(110); statsField.relocate(0 + pos, 300); statsField.getChildren().addAll(statsArea); /** * adding buttons to panes */ healthbar = new ProgressBar(twot.getPlayerHealth()/100); healthbar.setStyle("-fx-accent: red;"); healthbar.setPrefSize(256, 26); healthbar.relocate(0 + pos, 265); label1 = new Label("Health "+ twot.getPlayerHealth()); label1.setTextFill(Color.web("BLACK")); label1.relocate(10 + pos, 269); Label setNamePls = new Label("ENTER YOUR NAME: "); //Highscore screen Button button_cancel = new Button("EXIT TO MENU"); ListView<AnchorPane> hList = new ListView(); button_cancel.relocate(0, 220); hList.relocate(0, 0); hList.setPrefWidth(300); hList.setPrefHeight(210); //adding observableList with type AnchorPane ObservableList<AnchorPane> hloads = FXCollections.observableArrayList(); //Getting an arraylist of load files, List<String> loadHList = getHighscoreList(); //Go through each String in the list for (String i : loadHList) { //add a new anchorpane with a Text component to the ObservableList AnchorPane t = new AnchorPane(); Text hItemName = new Text(i); hItemName.relocate(0, 3); t.getChildren().add(hItemName); hloads.add(t); } //add the ObservableList to the ListView hList.setItems(hloads); Pane root = new Pane(equipTable, invButtons, gameButtons, outputField, healthbar, invTable, label1, statsField, walkButtons); Pane root2 = new Pane(menuButtons); Pane root3 = new Pane(nameField); Pane root4 = new Pane(loadMenuButtons, anchorpane); Pane root5 = new Pane(endScore, button_endGameExitGame); Pane root6 = new Pane(hList, button_cancel); Scene game = new Scene(root, 1052 + pos, 512); Scene menu = new Scene(root2, 512, 288); Scene nameScene = new Scene(root3, 512, 288); Scene loadMenu = new Scene(root4, 512, 288); endMenu = new Scene(root5, 512, 288); Scene highscoreMenu = new Scene(root6, 512, 288); /** * Actions events */ DropShadow shade = new DropShadow(); root.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { root.setEffect(shade); }); root.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { root.setEffect(null); }); button_equip.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ if(invTable.getSelectionModel().getSelectedItem() == null){ textArea.appendText("\n\nPlease select an item."); }else{ for(String s: twot.equipItem(new Command(CommandWord.USE, invTable.getSelectionModel().getSelectedItem().getItemName()))){ if(invTable.getSelectionModel().getSelectedItem().getItemType() == "Equippable Item"){ textArea.appendText("\n" + s); updateGUI(); } else { textArea.appendText("\nThis item cannot be equipped."); } } } }); /** * makes an instance of TWoT and equals it with the load, then sets it */ button_loadGame.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ TWoT loadedGame = getLoad((((Text)list.getSelectionModel().getSelectedItem().getChildren().get(0)).getText())); //set the game to the loaded instance setGame(loadedGame); primaryStage.setScene(game); primaryStage.centerOnScreen(); textArea.clear(); textArea.appendText(loadedGame.getCurrentRoomDescription()); updateGUI(); }); button_load.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(loadMenu); }); button_save.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ saveGame(); textArea.appendText("\n\nGame has been saved. It can be loaded from the start menu.\n\n"); }); /** * If a useable item is selected and the button is clicked, the action events takes the commandword USE and the item name */ button_use.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ if(invTable.getSelectionModel().getSelectedItem() == null){ textArea.appendText("\n\nPlease select an item."); }else{ for(String s: twot.useItem(new Command(CommandWord.USE, invTable.getSelectionModel().getSelectedItem().getItemName()))){ if(invTable.getSelectionModel().getSelectedItem().getItemType() == "Usable Item"){ textArea.appendText("\n" + s); updateGUI(); } else { textArea.appendText("\nThis item cannot be used."); } } } }); button_play.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(nameScene); }); button_cancel.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(menu); }); button_highscore.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(highscoreMenu); }); button_help.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ help=printHelp(); textArea.appendText(help); }); button_clear.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ textArea.clear(); }); /** * Takes the text in the inputfield and uses the setPlayerName() method in the twot class */ nameField.setOnKeyPressed(new EventHandler<KeyEvent>(){ @Override public void handle(KeyEvent k){ if(k.getCode().equals(KeyCode.ENTER)){ twot.setPlayerName(nameArea.getText()); primaryStage.setScene(game); primaryStage.centerOnScreen(); updateGUI(); } } }); /** * Calls on the other class 'PopUps' with the parameters given below */ button_how.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent e){ PopUps.display("HOW TO PLAY", "Move around with the 'go [interactable object]' " + "command. \nYou automatically pick up items if the " + "interior have any available.\n" + "You lose score points when you die but you are free to continue the game as if nothing happened."); } }); button_exitToMenu.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ primaryStage.setScene(menu); }); /** * closes the platform */ button_exit.setOnAction(actionEvent -> Platform.exit()); button_exitMenu.setOnAction(actionEvent -> Platform.exit()); button_endGameExitGame.setOnAction(actionEvent -> Platform.exit()); /** * sets and shows the primarystage */ primaryStage.setScene(menu); primaryStage.centerOnScreen(); primaryStage.show(); String welcome = ""; for(HashMap.Entry<Integer, String> entry : twot.getWelcomeMessages().entrySet()){ welcome = welcome + entry.getValue(); } textArea.appendText(welcome); } public List<String> getHighscoreList() { //create empty arraylist. List<String> loadList = new ArrayList(); //try to get each file in the directory "loads" by using Files.walk List<Score> highscores = twot.readHighScore(); for(Score s : highscores){ loadList.add("Name: " + s.getName() + " | Score: " + s.getScore() + " | Time: " + s.getTime()); } //return the List return loadList; } /** * Method that runs methods to update the GUI, hardcoded to update everyting actionevents are called */ public void updateGUI(){ updatePlayer(); updateHealth(); updateInventory(); updateEquipInventory(); updateButtons(); } /** * Method that fetches player stats */ public void updatePlayer(){ statsArea.clear(); NumberFormat df = new DecimalFormat(" statsArea.appendText("****************************\n"); statsArea.appendText("** Player name: " + twot.getPlayerName() + "\n"); statsArea.appendText("** Attack value: " + df.format(twot.getPlayerAtt()) + "\n"); statsArea.appendText("** Defense value: " + df.format(twot.getPlayerDeff()) + "\n"); statsArea.appendText("** Gold: " + twot.getPlayerGold() + "\n"); statsArea.appendText("****************************"); } /** * updates health on the healthbar */ public void updateHealth(){ label1.setText("Health "+ twot.getPlayerHealth()); healthbar.setProgress(twot.getPlayerHealth()/100); if(twot.getPlayerHealth() <= 100 && twot.getPlayerHealth() > 66){ healthbar.setStyle("-fx-accent: green;"); } else if (twot.getPlayerHealth() <= 66 && twot.getPlayerHealth() > 33){ healthbar.setStyle("-fx-accent: yellow;"); } else if (twot.getPlayerHealth() <= 33 && twot.getPlayerHealth() > 0){ healthbar.setStyle("-fx-accent: red;"); } } /** * Removes all instances of items in the list, and adds the ones in the inventory */ public void updateInventory(){ List<Item> l = twot.getInventoryItems(); invData.removeAll(invData); for(Item i: l){ if(i instanceof UseableItem){ invData.add(new InventoryItems(i.getItemName(), "Usable Item", i.getItemDescription())); } else if (i instanceof QuestItem) { invData.add(new InventoryItems(i.getItemName(), "Quest Item", i.getItemDescription())); } else if(i instanceof EquippableItem) { invData.add(new InventoryItems(i.getItemName(), "Equippable Item", i.getItemDescription())); } } } /** * Removes all instances of items in the list, and adds the equippableItems from the inventory */ public void updateEquipInventory(){ HashMap<EquippableItem.EItem, EquippableItem> k = twot.getEquippableItems(); equipData.removeAll(equipData); for(Map.Entry<EquippableItem.EItem, EquippableItem> entry : k.entrySet()){ if(entry.getKey() == AMULET_SLOT) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Amulet Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (HEAD_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Head slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (WEAPON_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Weapon Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (CHEST_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Chest Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (LEG_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Leg Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (BOOT_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Boot Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (GLOVES_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Glove Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); }else if(entry.getKey() == (RING_SLOT)) { equipData.add(new EquippedItems(entry.getValue().getItemName(), "Ring Slot", entry.getValue().getAttackBuff(), entry.getValue().getDefenseBuff())); } } } /** * Runs the switch to check the current room and adds the buttons defined with the methods bellow */ public void updateButtons() { switch (twot.getCurrentRoomId()) { case 1: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(cellarButtons()); break; case 2: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(villageButtons()); break; case 3: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(house1Buttons()); break; case 4: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(house2Buttons()); break; case 5: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(house3Buttons()); break; case 6: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(forestButtons()); break; case 7: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(wizardHouseButtons()); break; case 8: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(caveButtons()); break; case 9: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(lairButtons()); break; case 10: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(clearingButtons()); break; case 11: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(dungeonButtons()); break; case 12: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(libraryButtons()); break; case 13: walkButtons.getChildren().removeAll(walkButtons.getChildren()); walkButtons.getChildren().add(evilWizardsButtons()); break; default: break; } } //WALK BUTTONS CommandWords commandword = new CommandWords(); private Group cellarButtons() { Button button_haystack = new Button("Haystack"); Button button_table = new Button("Table"); Button button_door = new Button("Door"); button_haystack.setPrefSize(110, 10); button_table.setPrefSize(110, 10); button_door.setPrefSize(110, 10); VBox cellarButtons = new VBox(20); cellarButtons.setLayoutX(5); cellarButtons.setLayoutY(10); cellarButtons.getChildren().addAll(button_door, button_table, button_haystack); walkButtons = new Group(cellarButtons); button_haystack.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "haystack"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_table.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "table"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return walkButtons; } private Group villageButtons() { Button button_reborn = new Button("House 1"); Button button_riches = new Button("House 2"); Button button_hOfGuard = new Button("House 3"); Button button_guard = new Button("The Guard"); Button button_axe = new Button("Axe"); Button button_forest = new Button("Forest"); button_reborn.setPrefSize(110, 10); button_riches.setPrefSize(110, 10); button_hOfGuard.setPrefSize(110, 10); button_guard.setPrefSize(110, 10); button_axe.setPrefSize(110, 10); button_forest.setPrefSize(110, 10); button_forest.setDisable(true); VBox villageButtons = new VBox(20); //if guard children not delivered. villageButtons.getChildren().addAll(button_reborn, button_riches, button_hOfGuard, button_guard, button_axe, button_forest); if(twot.checkExisting("forest")){ button_forest.setDisable(false); } if(!twot.checkExisting("axe")){ button_axe.setDisable(true); } walkButtons = new Group(villageButtons); button_reborn.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_riches.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_hOfGuard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house3"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_guard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "guard"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_axe.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "axe"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_forest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "forest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return walkButtons; } private Group house1Buttons() { Button button_man = new Button("Man"); Button button_chest = new Button("Chest"); Button button_door = new Button("Door"); Button button_stranger = new Button("Stranger"); button_man.setPrefSize(110, 10); button_chest.setPrefSize(110, 10); button_door.setPrefSize(110, 10); button_stranger.setPrefSize(110, 10); VBox house1Buttons = new VBox(20); house1Buttons.getChildren().addAll(button_door, button_chest, button_man); Group root = new Group(house1Buttons); if(!twot.checkExisting("man")){ button_man.setDisable(true); } if(twot.checkExisting("stranger")){ house1Buttons.getChildren().add(button_stranger); } button_man.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "man"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_chest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "chest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_stranger.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "stranger"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group house2Buttons() { Button button_door = new Button("Door"); Button button_wardrobe = new Button("Wardrobe"); Button button_bed = new Button("Bed"); Button button_table = new Button("Table"); Button button_stranger = new Button("Stranger"); button_door.setPrefSize(110, 10); button_wardrobe.setPrefSize(110, 10); button_bed.setPrefSize(110, 10); button_table.setPrefSize(110, 10); button_stranger.setPrefSize(110, 10); VBox house2Buttons = new VBox(20); house2Buttons.getChildren().addAll(button_door, button_wardrobe, button_bed, button_table); Group root = new Group(house2Buttons); if(twot.checkExisting("stranger")){ house2Buttons.getChildren().add(button_stranger); } button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_wardrobe.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "wardrobe"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_bed.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "bed"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_table.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "table"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_stranger.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "stranger"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group house3Buttons() { Button button_door = new Button("Door"); Button button_kitchen = new Button("Kitchen"); Button button_woman = new Button("Woman"); Button button_chest = new Button("Chest"); Button button_stranger = new Button("Stranger"); button_door.setPrefSize(110, 10); button_kitchen.setPrefSize(110, 10); button_woman.setPrefSize(110, 10); button_chest.setPrefSize(110, 10); button_stranger.setPrefSize(110, 10); VBox house3Buttons = new VBox(20); house3Buttons.getChildren().addAll(button_door, button_kitchen, button_woman, button_chest); Group root = new Group(house3Buttons); if(twot.checkExisting("stranger")){ house3Buttons.getChildren().add(button_stranger); } if(!twot.checkExisting("woman")){ button_woman.setDisable(true); } button_stranger.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "stranger"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_kitchen.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "kitchen"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_woman.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "woman"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_chest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "chest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group forestButtons() { Button button_mushroom = new Button("Mushroom"); Button button_goblin = new Button("Dead goblin"); Button button_house = new Button("Wiz House"); Button button_cave = new Button("Cave"); Button button_clearing = new Button("Clearing"); Button button_village = new Button("Village"); button_mushroom.setPrefSize(110, 10); button_goblin.setPrefSize(110, 10); button_house.setPrefSize(110, 10); button_cave.setPrefSize(110, 10); button_clearing.setPrefSize(110, 10); button_village.setPrefSize(110, 10); VBox forestButtons = new VBox(20); forestButtons.getChildren().addAll(button_village, button_goblin, button_house, button_mushroom, button_cave, button_clearing); Group root = new Group(forestButtons); button_mushroom.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "mushroom"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_goblin.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "goblin"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_house.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "house"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_cave.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "cave"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_clearing.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "clearing"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_village.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "village"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group wizardHouseButtons() { Button button_upstairs = new Button("Sacks"); Button button_box = new Button("Box"); Button button_lab = new Button("Alchemy Lab"); Button button_wizard = new Button("Wizard"); Button button_door = new Button("Door"); button_upstairs.setPrefSize(110, 10); button_box.setPrefSize(110, 10); button_lab.setPrefSize(110, 10); button_wizard.setPrefSize(110, 10); button_door.setPrefSize(110, 10); VBox wizardHouseButtons = new VBox(20); wizardHouseButtons.getChildren().addAll(button_door, button_box, button_lab, button_wizard, button_upstairs); Group root = new Group(wizardHouseButtons); button_upstairs.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "upstairs"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_box.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "box"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_lab.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "lab"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_wizard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "wizard"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group caveButtons() { Button button_troll1 = new Button("Troll"); Button button_troll2 = new Button("Troll"); Button button_troll3 = new Button("Troll"); Button button_forest = new Button("Forest"); Button button_lair = new Button("Lair"); button_troll1.setPrefSize(110, 10); button_troll2.setPrefSize(110, 10); button_troll3.setPrefSize(110, 10); button_forest.setPrefSize(110, 10); button_lair.setPrefSize(110, 10); VBox caveButtons = new VBox(20); caveButtons.getChildren().addAll(button_forest, button_troll1, button_troll2, button_troll3, button_lair); Group root = new Group(caveButtons); if(!twot.checkExisting("troll1")){ button_troll1.setDisable(true); } if(!twot.checkExisting("troll2")){ button_troll2.setDisable(true); } if(!twot.checkExisting("troll3")){ button_troll3.setDisable(true); } button_troll1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "troll1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_troll2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "troll2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_troll3.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "troll3"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_forest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "forest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_lair.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "lair"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group lairButtons() { Button button_gruul = new Button("Gruul"); Button button_cave = new Button("Cave"); button_gruul.setPrefSize(110, 10); button_cave.setPrefSize(110, 10); VBox lairButtons = new VBox(20); lairButtons.getChildren().addAll(button_cave, button_gruul); Group root = new Group(lairButtons); if(!twot.checkExisting("gruul")){ button_gruul.setDisable(true); } button_gruul.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "gruul"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_cave.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "cave"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group clearingButtons() { Button button_forest = new Button("Forest"); Button button_unicorn = new Button("Unicorn"); Button button_tree = new Button("Tree"); button_forest.setPrefSize(110, 10); button_unicorn.setPrefSize(110, 10); button_tree.setPrefSize(110, 10); VBox clearingButtons = new VBox(20); clearingButtons.getChildren().addAll(button_forest, button_unicorn, button_tree); Group root = new Group(clearingButtons); if(!twot.checkExisting("unicorn")){ button_unicorn.setDisable(true); } button_forest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "forest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_unicorn.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "unicorn"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_tree.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "tree"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group dungeonButtons() { Button button_skeleton1 = new Button("Skeleton"); Button button_skeleton2 = new Button("Skeleton"); Button button_skeleton3 = new Button("Skeleton"); Button button_pathway = new Button("Pathway"); button_skeleton1.setPrefSize(110, 10); button_skeleton2.setPrefSize(110, 10); button_skeleton3.setPrefSize(110, 10); button_pathway.setPrefSize(110, 10); VBox dungeonButtons = new VBox(20); dungeonButtons.getChildren().addAll(button_pathway, button_skeleton1, button_skeleton2, button_skeleton3); Group root = new Group(dungeonButtons); if(!twot.checkExisting("skeleton1")){ button_skeleton1.setDisable(true); } if(!twot.checkExisting("skeleton2")){ button_skeleton2.setDisable(true); } if(!twot.checkExisting("skeleton3")){ button_skeleton3.setDisable(true); } button_skeleton1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "skeleton1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_skeleton2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "skeleton2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_skeleton3.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "skeleton3"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_pathway.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "pathway"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group libraryButtons() { Button button_librarian = new Button("Librarian"); Button button_door = new Button("Door"); Button button_chest = new Button("Chest"); button_librarian.setPrefSize(110, 10); button_door.setPrefSize(110, 10); button_chest.setPrefSize(110, 10); VBox libraryButtons = new VBox(20); libraryButtons.getChildren().addAll(button_door, button_librarian, button_chest); Group root = new Group(libraryButtons); if(!twot.checkExisting("librarian")){ button_librarian.setDisable(true); } button_librarian.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "librarian"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_door.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "door"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_chest.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "chest"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } private Group evilWizardsButtons() { Button button_evilWizard = new Button("Evil Wizard"); Button button_minion1 = new Button("Minion1"); Button button_minion2 = new Button("Minion2"); button_evilWizard.setPrefSize(110, 10); button_minion1.setPrefSize(110, 10); button_minion2.setPrefSize(110, 10); VBox evilWizardsButtons = new VBox(20); evilWizardsButtons.getChildren().addAll(button_evilWizard, button_minion1, button_minion2); Group root = new Group(evilWizardsButtons); if(!twot.checkExisting("minion2")){ button_minion2.setDisable(true); } if(!twot.checkExisting("minion1")){ button_minion1.setDisable(true); } button_evilWizard.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "wizard"); if(!twot.checkExisting("minion1") && !twot.checkExisting("minion2")){ for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } }else{ textArea.appendText("\n\nFoolish mortal! You have to defeat my minions before you prove yourself worthy to fight me."); } if(twot.endGame() == true){ endScore.setText("Congratulations! You have beaten The Wizard of Treldan!\n" + " Your final score is: " + twot.getHighscore() + "\n It took you " + ((long)(System.currentTimeMillis() / 1000L) - twot.getStartTime()) + " seconds to finish the game."); twot.writeHighScore(); primaryStage.setScene(endMenu); } updateGUI(); }); button_minion1.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "minion1"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); button_minion2.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e)->{ Command command = new Command(commandword.getCommandWord("go"), "minion2"); for(String s: twot.goTo(command)){ textArea.appendText("\n" + s + "\n"); } updateGUI(); }); return root; } /** * Opens a FileOutputStream and an oObjectOutputStream and saves the game in a .data file with the date * and currentRoom as the name, and saves it in the projectfolder under a folder called "loads" */ public void saveGame(){ SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss"); Date date = new Date(); String strDate = sdf.format(date); try { FileOutputStream fos = new FileOutputStream("loads/" + twot.getCurrentRoomName() + "-" + strDate + ".data"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(twot); oos.close(); } catch(FileNotFoundException e){ e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } /** * checks the folder "loads" for files, and adds them to a list<String> and then returns it * @return */ public List<String> getLoadList(){ //create empty arraylist. List<String> loadList = new ArrayList(); //try to get each file in the directory "loads" by using Files.walk try{ //Go through each Path in the Stream. Stream<Path> paths = Files.walk(Paths.get("loads/")); paths.forEach(filePath -> { //if the file is a FILE continue if (Files.isRegularFile(filePath)) { //add the filename with extenstion to the List. loadList.add(filePath.getFileName().toString()); } }); } catch (IOException ex) { System.out.println("FAIL"); } //return the List return loadList; } /** * uses the filename and checks if the file exists, then it takes TWoT and equals the inputStream to that. * @param filename * @return */ public TWoT getLoad(String filename){ //Try loading the file. try { //Read from the stored file in folder "loads" FileInputStream fileInputStream = new FileInputStream(new File("loads/" + filename)); //Create a ObjectInputStream object from the FileInputStream ObjectInputStream input = new ObjectInputStream(fileInputStream); //load the TWoT file into object TWoT twot = (TWoT) input.readObject(); //close the objects input.close(); fileInputStream.close(); //returns the gamefile return twot; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Wrong version of game"); } catch (ClassNotFoundException e) { System.out.println("Game was not found."); } return null; } /** * method that sets twot to the loaded game * @param loaded */ public void setGame(TWoT loaded){ twot = loaded; } }
package water; import java.util.*; public abstract class Paxos { private static final boolean DEBUG = Boolean.getBoolean("water.paxos.debug"); public static class State extends Iced { public long _promise; public long _oldProposal; public long _idLo; public long _idHi; public H2ONode[] _members; public UUID uuid() { return new UUID(_idHi, _idLo); } } static H2ONode LEADER = H2O.SELF; // Leader has the lowest IP of any in the set static HashSet<H2ONode> PROPOSED_MEMBERS = new HashSet(); static HashSet<H2ONode> ACCEPTED = new HashSet(); static { PROPOSED_MEMBERS.add(H2O.SELF); } // We have a one-off internal buffer. // This buffer serves many duties: // - Storage of most recent proposal // - Storage of most recent promise // - Something to write to the UDP output buffer static State _state = new State(); static { _state._members = PROPOSED_MEMBERS.toArray(new H2ONode[1]); } // If we receive a Proposal, we need to see if it larger than any we have // received before. If so, then we need to Promise to honor it. Also, if we // have Accepted prior Proposals, we need to include that info in any Promise. static long PROPOSAL_MAX; static long PROPOSAL_MAX_SENT; // Whether or not we have common knowledge public static volatile boolean _commonKnowledge = false; // Whether or not we're allowing distributed-writes. The cloud is not // allowed to change shape once we begin writing. public static volatile boolean _cloudLocked = false; // This is a packet announcing what Cloud this Node thinks is the current // Cloud. static synchronized void doHeartbeat( H2ONode h2o ) { // If this packet is for *this* Cloud, just carry on (the heartbeat has // already been recorded. H2O cloud = H2O.CLOUD; if( h2o.is_cloud_member(cloud) ) { // However, do a 1-time printing when we realize all members of the cloud // are mutally agreed upon a new cloud shape. This is not the same as a // Paxos vote, which only requires a Quorum. This happens after everybody // has agreed to the cloud AND published that result to this node. boolean ck = true; // Assume true for( H2ONode h2o2 : cloud._memary ) if( !h2o2.is_cloud_member(cloud) ) ck = false; // This guy has not heartbeat'd that "he's in" if( ck == false && _commonKnowledge == true && _cloudLocked ) killCloud(); // Cloud-wide kill because things changed after key inserted if( !_commonKnowledge && ck ) { // Everybody just now agrees on the Cloud Paxos.class.notify(); // Also, wake up a worker thread stuck in DKV.put System.out.printf("[h2o] Paxos Cloud of size %d formed: %s\n", cloud._memset.size(), cloud._memset.toString()); } _commonKnowledge = ck; // Set or clear "common knowledge" return; // Do nothing! } print("hart: mismatched cloud announcement",h2o); // If this dude is supposed to be *in* our Cloud then maybe it's a slow or // delayed heartbeat packet, or maybe he's missed the Accepted announcement. // In either case, pound the news into his head. if( cloud._memset.contains(h2o) ) { if( H2O.isIDFromPrevCloud(h2o) ) { // In situations of rapid cloud formation, we could have: // A Cloud of {A,B} is voted on. // A Cloud of {A,B,C,D} is voted on by A,C,D forming a quorum. B is slow. // New members E,F,G appear to A, so A's proposed list is now {A-G} // B, still slow, heartbeats cloud {A,B} // At this point: B is in {A,B}, A is in {A,B,C} which includes B, // but A is busy working on {A-G}. print("hart: is member but did not get the news1",cloud._memset); print("hart: is member but did not get the news2",PROPOSED_MEMBERS); if( PROPOSED_MEMBERS.equals(cloud._memset) ) { // But if things are not moving fast... _state._members = PROPOSED_MEMBERS.toArray(new H2ONode[0]); UDPPaxosAccepted.build_and_multicast(_state); // Then try to update the slow guy } return; } else { // Trigger new round of Paxos voting: remove this guy from our cloud // (since he thinks he does not belong), and try again. PROPOSED_MEMBERS.remove(h2o); } } else { // Got a heartbeat from some dude not in the Cloud. Probably napping // Node woke up and hasn't yet smelled the roses (i.e., isn't aware the // Cloud shifted and kicked him out). Could be a late heartbeat from // him. Offer to vote him back in. if( !addProposedMember(h2o) ) print("hart: already part of proposal",PROPOSED_MEMBERS); } // Trigger a Paxos proposal because there is somebody new, or somebody old doChangeAnnouncement(cloud); } // Remove any laggards. Laggards should notice they are being removed from // the Cloud - and if they do they can complain about it and get // re-instated. If they don't notice... then they need to be removed. // Recompute leader. private static void removeLaggards() { long now = System.currentTimeMillis(); changeLeader(null); for( Iterator<H2ONode> i = PROPOSED_MEMBERS.iterator(); i.hasNext(); ) { H2ONode h2o = i.next(); // Check if node timed out long msec = now - h2o._last_heard_from; if( msec > HeartBeatThread.TIMEOUT ) { assert h2o != H2O.SELF; // Not timing-out self??? print("kill: Removing laggard ",h2o); i.remove(); } else { // Else find the lowest IP address to be leader if( h2o.compareTo(LEADER) < 0 ) changeLeader(h2o); } } return; } // Handle a mis-matched announcement; either a self-heartbeat has noticed a // laggard in our current Cloud, or we got a heartbeat from somebody outside // the cloud. The caller must have already synchronized. synchronized static void doChangeAnnouncement( H2O cloud ) { // Remove laggards and recompute leader removeLaggards(); // At this point, we have changed the current Proposal: either added due to // a heartbeat from an outsider, or tossed out a laggard or both. // Look again at the new proposed Cloud membership. If it matches the // existing Cloud... then we like things the way they are and we want to // ignore this change announcement. This can happen if e.g. somebody is // trying to vote-in a laggard; they have announced a Cloud with the // laggard and we're skeptical. if( cloud._memset.equals(PROPOSED_MEMBERS) ) { assert cloud._memary[0] == LEADER; print("chng: no change from current cloud, ignoring change request",PROPOSED_MEMBERS); return; } // Reset all memory of old accepted proposals; we're on to a new round of voting _state._members = PROPOSED_MEMBERS.toArray(new H2ONode[0]); // The Leader Node for this proposed Cloud will act as the distinguished // Proposer of a new Cloud membership. Non-Leaders will act as passive // Accepters. if( H2O.SELF == LEADER ) { // If we are proposing a leadership change, we need to do the Basic Paxos // algorithm from scratch. If we are keeping the leadership but, e.g. // adding or removing a local Node then we can go for the Multi-Paxos // steady-state response. // See if we are changing cloud leaders? if( cloud._memary[0] == LEADER ) { // TODO // throw new Error("Unimplemented: multi-paxos same-leader optimization"); } // We're fighting over Cloud leadership! We need to throw out a 'Prepare // N' so we can propose a new Cloud, where the proposal is bigger than // any previously submitted by this Node. Note that only people who // think they should be leaders get to toss out proposals. ACCEPTED.clear(); // Reset the Accepted count: we got no takings on this new Proposal long proposal_num = PROPOSAL_MAX+1; // note PROPOSAL_MAX_SENT never gets zeroed, unlike PROPOSAL_MAX if ( PROPOSAL_MAX_SENT > PROPOSAL_MAX ) { proposal_num = PROPOSAL_MAX_SENT+1; } PROPOSAL_MAX_SENT = proposal_num; UUID uuid = UUID.randomUUID(); _state._idLo = uuid.getLeastSignificantBits(); _state._idHi = uuid.getMostSignificantBits(); Paxos.print("send: Prepare "+proposal_num+" for leadership fight ",PROPOSED_MEMBERS); UDPPaxosProposal.build_and_multicast(proposal_num); } else { // Non-Leaders act as passive Accepters. All Nodes should respond in a // timely fashion, including Leaders - if they fail the basic heartbeat // timeout, then they may be voted out of the Cloud... which will start // another leadership fight at that time. Meanwhile, this is effectively a // Paxos Client request to the Paxos Leader / Proposer ... not to us. // Ignore it. print("do : got cloud change request as an acceptor; ignoring it",PROPOSED_MEMBERS); } } // This is a packet announcing a Proposal, which includes an 8-byte Proposal // number and the guy who sent it (and thinks he should be leader). static synchronized int doProposal( final long proposal_num, final H2ONode proposer ) { print("recv: Proposal num "+proposal_num+" by ",proposer); // We got a Proposal from somebody. We can toss this guy in the world- // state we're holding but we won't be pulling in all HIS Cloud // members... we wont find out about them until other people start // announcing themselves... so adding this dude here is an optimization. addProposedMember(proposer); // Is the Proposal New or Old? if( proposal_num < PROPOSAL_MAX ) { // Old Proposal! We can ignore it... // But we want to NAK this guy if( proposer != H2O.SELF ) UDPPaxosNack.build_and_multicast(PROPOSAL_MAX-1, proposer); return print("do_proposal NAK; self:" + H2O.SELF + " target:"+proposer + " proposal " + proposal_num, proposer); } else if( proposal_num == PROPOSAL_MAX ) { // Dup max proposal numbers? if( proposer == LEADER ) // Ignore dups from leader return print("do_proposal: ignoring duplicate proposal", proposer); // Ahh, a dup proposal from non-leader. Must be an old proposal if( proposer != H2O.SELF ) UDPPaxosNack.build_and_multicast(PROPOSAL_MAX, proposer); return print("do_proposal NAK; self:" + H2O.SELF + " target:"+proposer + " proposal " + proposal_num, proposer); } // A new larger Proposal number appeared; keep track of it PROPOSAL_MAX = proposal_num; ACCEPTED.clear(); // If I was acting as a Leader, my Proposal just got whacked if( LEADER == proposer ) { // New Proposal from what could be new Leader? // Now send a Promise to the Proposer that I will ignore Proposals less // than PROPOSAL_MAX (8 bytes) and include any prior ACCEPTED Proposal // number (8 bytes) and old the Proposal's Value assert _state._oldProposal < proposal_num; // we have not already promised what is about to be proposed _state._promise = proposal_num; if( H2O.SELF == LEADER ) { print("send: promise# "+proposal_num+" via direct call instead of UDP", proposer); return doPromise(_state, proposer); } else { print("send: promise# "+proposal_num, proposer); return UDPPaxosPromise.singlecast(_state, proposer); } } // Else proposal from some guy who I do not think should be leader in the // New World Order. If I am not Leader in the New World Order, let Leader // duke it out with this guy. if( H2O.SELF != LEADER ) return print("do : Proposal from non-leader to non-leader; ignore; leader should counter-propose",PROPOSED_MEMBERS); // I want to be leader, and this guy is messing with my proposal. Try // again to make him realize I should be leader. doChangeAnnouncement(H2O.CLOUD); return 0; } // Received a Nack on a proposal static synchronized void doNack( long proposal_num, final H2ONode h2o ) { print("recv: Nack num "+proposal_num+" by ",h2o); addProposedMember(h2o); // Nacking the named proposal if( proposal_num >= PROPOSAL_MAX ) { PROPOSAL_MAX = proposal_num; // At least bump proposal to here doChangeAnnouncement(H2O.CLOUD); // Re-vote from the start } } // Recieved a Promise from an Acceptor to ignore Proposals below a certain // number. Must be synchronized. Buf is freed upon return. static synchronized int doPromise( State state, H2ONode h2o ) { print("recv: Promise", PROPOSED_MEMBERS, state); long promised_num = state._promise; if( PROPOSAL_MAX==0 ) return print("do : nothing, received Promise "+promised_num+" but no proposal in progress",PROPOSED_MEMBERS); // Check for late-arriving promise, after a better Leader has announced // himself to me... and I do not want to be leader no more. if( LEADER != H2O.SELF ) return print("do : nothing: recieved promise ("+promised_num+"), but I gave up being leader" ,PROPOSED_MEMBERS); // Hey! Got a Promise from somebody, while I am a leader! // I always get my OWN proposals, which raise PROPOSAL_MAX, so this is for // some old one. I only need to track the current "largest proposal". if( promised_num < PROPOSAL_MAX ) return print("do : nothing: promise ("+promised_num+") is too old to care about ("+PROPOSAL_MAX+")",h2o); // Extract any prior accepted proposals long prior_proposal = state._oldProposal; // Extract the prior accepted Value also HashSet<H2ONode> prior_value = new HashSet(Arrays.asList(_state._members)); // Does this promise match the membership I like? If so, we'll accept the // promise. If not, we'll blow it off.. and hope for promises for what I // like. In normal Paxos, we have to report back any Value PREVIOUSLY // promised, even for new proposals. But in this case, the wrong promise // basically triggers a New Round of Paxos voting... so this becomes a // stale promise for the old round if( prior_proposal > 0 && !PROPOSED_MEMBERS.equals(prior_value) ) return print("do : nothing, because this is a promise for the wrong thing",prior_value); ACCEPTED.add(h2o); // See if we hit the Quorum needed final int quorum = (PROPOSED_MEMBERS.size()>>1)+1; if( ACCEPTED.size() < quorum ) return print("do : No Quorum yet "+ACCEPTED+"/"+quorum,PROPOSED_MEMBERS); if( ACCEPTED.size() > quorum ) return print("do : Nothing; Quorum exceeded and already sent AcceptRequest "+ACCEPTED+"/"+quorum,PROPOSED_MEMBERS); // We hit Quorum. We can now ask the Acceptors to accept this proposal. // Build & multicast an Accept! packet. It is our own proposal with the 8 // bytes of Accept number set, and includes the members as the agreed Value _state._oldProposal = PROPOSAL_MAX; _state._members = PROPOSED_MEMBERS.toArray(new H2ONode[0]); UDPPaxosAccept.build_and_multicast(_state); return print("send: AcceptRequest because hit Quorum ",PROPOSED_MEMBERS,_state); } // Recieved an Accept Request from some Proposer after he hit a Quorum. The // packet has 8 bytes of proposal number, and a membership list. Buf is // freed when done. static synchronized int doAccept( State state, H2ONode h2o ) { print("recv: AcceptRequest ", null, state); long proposal_num = state._oldProposal; if( PROPOSAL_MAX==0 ) return print("do : nothing, received Accept! "+proposal_num+" but no proposal in progress",PROPOSED_MEMBERS,state); if( proposal_num < PROPOSAL_MAX ) // We got an out-of-date AcceptRequest which we can ignore. The Leader // should have already started a new proposal round return print("do : ignoring out of date AcceptRequest ",null,state); PROPOSAL_MAX = proposal_num; // At this point, all Acceptors should tell all Learners via Accepted // messages about the new agreement. However, the Leader is also an // Acceptor so we'll let him do one broadcast to all Learners. if( LEADER != H2O.SELF ) { _state = state; // Remember the proposed value return print("do : record proposal state; Accept but I am not Leader, no need to send Accepted",PROPOSED_MEMBERS,_state); } UDPPaxosAccepted.build_and_multicast(state); return print("send: Accepted from leader only",PROPOSED_MEMBERS,state); } /** Recieved an Accepted packet from the Leader after he hit quorum. */ static synchronized int doAccepted( State state, H2ONode h2o ) { // Record most recent ping time from sender long proposal_num = state._promise; HashSet<H2ONode> members = new HashSet(Arrays.asList(_state._members)); print("recv: Accepted ", members, state); if( !members.contains(H2O.SELF) ) { // Not in this set? // This accepted set excludes me, so we need to start another round of // voting. Pick up the largest proposal to-date, and start voting again. if( proposal_num > PROPOSAL_MAX ) PROPOSAL_MAX = proposal_num; return print("do : Leader missed me; I am still not in the new Cloud, so refuse the Accept and let my Heartbeat publish me again",members,state); } if( proposal_num == PROPOSAL_MAX && state.uuid().equals(H2O.CLOUD._id) ) return print("do : Nothing: Accepted with same cloud membership list",members,state); // We just got a proposal to change the cloud if( _commonKnowledge ) { // We thought we knew what was going on? assert !_cloudLocked; _commonKnowledge = false; // No longer sure about things System.out.println("[h2o] Paxos Cloud voting in progress"); } H2O.CLOUD.set_next_Cloud(state.uuid(), members); PROPOSAL_MAX=0; // Reset voting; next proposal will be for a whole new cloud _state._promise = _state._oldProposal = 0; return print("do : Accepted so set new cloud membership list",members,state); } // Before we start doing distributed writes... block until the cloud // stablizes. After we start doing distrubuted writes, it is an error to // change cloud shape - the distributed writes will be in the wrong place. static void lockCloud() { if( _cloudLocked ) return; // Fast-path cutout synchronized(Paxos.class) { while( !_commonKnowledge ) try { Paxos.class.wait(); } catch( InterruptedException ie ) { } } _cloudLocked = true; } static private boolean addProposedMember(H2ONode n){ assert n._heartbeat != null; if(!PROPOSED_MEMBERS.contains(n)){ // H2O.OPT_ARGS.soft is a demo/hibernate mode launch if( _cloudLocked && (H2O.OPT_ARGS.soft == null) ) { System.err.println("[h2o] Killing "+n+" because the cloud is locked."); UDPRebooted.T.locked.send(n); return false; } if( !n._heartbeat.check_cloud_md5() ) { if( H2O.CLOUD.size() > 1 ) { System.err.println("[h2o] Killing "+n+" because of jar mismatch."); UDPRebooted.T.mismatch.send(n); } else { System.err.println("[h2o] Attempting to join "+n+" with a jar mismatch. Killing self."); System.exit(-1); } return false; } } if( PROPOSED_MEMBERS.add(n) ) { if( n.compareTo(LEADER) < 0 ) changeLeader(n); return true; } return false; } static void changeLeader( H2ONode newLeader ) { TypeMap.MAP.changeLeader(); LEADER = newLeader; } static void killCloud() { UDPRebooted.T.error.send(H2O.SELF); System.err.println("[h2o] Cloud changing after Keys distributed - fatal error."); System.err.println("[h2o] Received kill "+3+" from "+H2O.SELF); System.exit(-1); } static int print( String msg, HashSet<H2ONode> members, State state ) { return print(msg,members," promise:"+state._promise+" old:"+state._oldProposal); } static int print( String msg, H2ONode h2o ) { return print(msg, new HashSet(Arrays.asList(h2o)), ""); } static int print( String msg, HashSet<H2ONode> members ) { return print(msg,members,""); } static int print( String msg, HashSet<H2ONode> members, String msg2 ) { if( DEBUG ) System.out.println(msg+members+msg2); return 0; // handy flow-coding return } }
package jpower.core.test; import jpower.core.JPower; import jpower.core.utils.RuntimeUtils; import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.*; import static org.junit.Assume.assumeFalse; public class ReleaseInfoTest { @Test public void testVersionNotNull() { assumeFalse(RuntimeUtils.classExists("com.intellij.rt.execution.application.AppMain")); assertNotNull(JPower.getReleaseInfo().getVersion()); } @Test public void testVersionFormat() { assumeFalse(RuntimeUtils.classExists("com.intellij.rt.execution.application.AppMain")); assertTrue(JPower.getReleaseInfo().getVersion().contains(".")); assertEquals(3, JPower.getReleaseInfo().getVersion().split("\\.").length); } @Test public void testCommitNotNull() { assumeFalse(RuntimeUtils.classExists("com.intellij.rt.execution.application.AppMain")); // assertNotNull(JPower.getReleaseInfo().getCommit()); } @Test @Ignore("Fails") public void testCommitValid() { assumeFalse(RuntimeUtils.classExists("com.intellij.rt.execution.application.AppMain")); assertTrue(JPower.getReleaseInfo().getCommit().length() > 15); } }
package xml; import utility.GenericObservable; import utility.Observable; import utility.Observer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Set; /** * The Element class is used to represent a node in an XML tree. It must have * a tag (name) which identifies it. It may optionally have textual content, * attributes (key/value pairs) and children (other elements). * * @see Observable * @see GenericObservable */ public class Element implements Observable { private String tag; private String text; private HashMap<String, String> attributes; private ArrayList<Element> children; private GenericObservable observable; private Element parent; /** * Initialize an Element with no data in it. This element is invalid until * it has a tag. */ public Element() { tag = null; text = null; attributes = new HashMap<String, String>(); children = new ArrayList<Element>(); observable = new GenericObservable(); parent = null; } /** * Create a new element, initialize it with a tag * @param tagName The name of the tag to give to this element */ public Element(String tagName) { tag = tagName; text = null; attributes = new HashMap<String, String>(); children = new ArrayList<Element>(); observable = new GenericObservable(); parent = null; } /** * Get an exact (deep) copy of this element, but without children * @return a copy of this element */ public Element cloneWithoutChildren() { Element cloneElem = new Element(); cloneElem.setTag(tag); cloneElem.setText(text); String attVal; for (String attName : attributeNames()) { attVal = getAttribute(attName); cloneElem.setAttribute(attName, attVal); } cloneElem.setParent(parent); return cloneElem; } /** * Determine if this element is equivalent to another Element. This does * not take the element's children into account, just the actual element * itself. * @param obj The object to which to compare * @return true if the elements match, false otherwise */ @Override public boolean equals(Object obj) { if (obj.getClass() == getClass()) { Element elem = (Element) obj; if (!(elem.getTag().equals(tag))) { System.out.println("[DEBUG] Element.equals() tags differ"); return false; } if (text == null && elem.getText() != null) { System.out.println("[DEBUG] Element.equals() text differs"); System.out.printf("[DEBUG] text1 = \"%s\", text2 = \"%s\"\n", text, elem.getText()); return false; } else if (text != null && elem.getText() == null) { System.out.println("[DEBUG] Element.equals() text differs"); System.out.printf("[DEBUG] text1 = \"%s\", text2 = \"%s\"\n", text, elem.getText()); return false; } else if (text != null && elem.getText() != null) { if (!text.equals(elem.getText())) { System.out.println("[DEBUG] Element.equals() text differs"); System.out.printf("[DEBUG] text1 = \"%s\", text2 = \"%s\"\n", text, elem.getText()); return false; } } String attVal; for (String attName : elem.attributeNames()) { attVal = getAttribute(attName); if (!(elem.getAttribute(attName).equals(attVal))) { System.out.println("[DEBUG] Element.equals() Attribute differs "); System.out.printf("[DEBUG] key = \"%s\", val = \"%s\"\n", attName, attVal); return false; } } return true; } return false; } /** * Determine if this element has the same parent as another element * @param elem The element to compare with * @return true if they are siblings, false if not */ public boolean isSibling(Element elem) { return parent == elem.getParent(); } /** * Get the element's tag * @return The element's tag */ public String getTag() { return tag; } /** * Set this element's tag, which serves as an identifier for this type of * element. * @param tag The tag to apply to this element */ public void setTag(String tag) { this.tag = tag; } /** * @see Observable */ public void registerObserver(Observer observer) { observable.registerObserver(observer); } /** * @see Observable */ public void unregisterObserver(Observer observer) { observable.unregisterObserver(observer); } /** * @see Observable */ public void notifyObservers() { observable.notifyObservers(); } /** * Return this element's children as a collection * @see java.util.Collection * @return This element's children, as a Collection */ public Collection<Element> getChildren() { return children; } /** * Get this Elements' children as an Iterable * @see java.lang.Iterable * @return this Element's children as an Iterable */ public Iterable<Element> children() { return children; } /** * Determine if this element has children * @return true if this element has childre, false if it doesn't */ public boolean hasChildren() { if (children.size() > 0) { return true; } return false; } /** * Get the child at a particular index. Child elements have an order: * those added earlier will precede those added later. * @param index The index of the child * @return The child Element if it's found, null if it isn't */ public Element getChildAt(int index) { Element child = null; if (index >= 0 && index < children.size()) { child = children.get(index); } return child; } /** * Determine the number of children that this Element has * @return the number of children that this Element has */ public int getNumberOfChildren() { return children.size(); } /** * Get the index of a known child * @param elem The child element to look for * @return the index of the child if it's found, -1 if not */ public int getChildIndex(Element elem) { int index = -1; if (children.contains(elem)) { index = children.indexOf(elem); } return index; } /** * Get this Element's parent element, if it exists * @return This Element's parent or null if it doesn't have one */ public Element getParent() { return parent; } /** * Set this element's parent * @param parent The new parent to give this element */ public void setParent(Element parent) { this.parent = parent; } /** * Get a Set of the attribute names * @see java.util.Set * @return a Set of the attribute names */ public Set<String> attributeNames() { return attributes.keySet(); } /** * Get the value of a particular attribute * @param key The attribute's name * @return The value of the attribute */ public String getAttribute(String key) { return attributes.get(key); } /** * Set the value of an attribute * @param key The attribute's name * @param value The attribute's value/content */ public void setAttribute(String key, String value) { attributes.put(key, value); } /** * Get the total number of attributes that the Element has * @return the number of attributes that the Element has */ public int getNumberOfAttributes() { return attributes.size(); } /** * Determine if this element has textual content * @return true if this element has assigned text, false if not */ public boolean hasText() { return !(text == null); } /** * Get this Element's textual content * @return This element's text */ public String getText() { return text; } /** * Set this element's textual content * @param text The text to assign to this element */ public void setText(String text) { if (text != null && text.trim().length() > 0) { this.text = text; } } /** * Add a child to this Element * @param child The child to add to this Element */ public void addChild(Element child) { child.setParent(this); children.add(child); } /** * Determine the index of a child element * @param child The child Element whose index to search for * @return The index of the child if found, -1 in case of any error */ public int getIndexOfChild(Element child) { int idx = -1; if (child != null) { for (int i = 0; i < children.size(); i++) { if (child.equals(children.get(i))) { idx = i; } } } return idx; } /** * When converting an Element to a String, use the tag * @return the element's tag */ @Override public String toString() { return tag; } /** * Add a sub-element (child) to this element and return the new Element * @param tag The child's tag * @return the new child element */ public Element newSubElement(String tag) { Element child = new Element(tag); addChild(child); return child; } /** * Determine if this is the root element in a tree (i.e. it has no parent) * @return true if this is the root element, false if it's not */ public boolean isRoot() { boolean rootStatus = false; if (parent == null) { rootStatus = true; } return rootStatus; } /** * Compare an entire tree to see if they are equivalent * @param elem The element in the other tree * @return true if the trees match, false otherwise */ public boolean equalTree(Element elem) { if (!equals(elem)) { System.out.println("[DEBUG] equalTree(): Elements differ"); System.out.println("[DEBUG] element 1: " + tag + ", Element 2: " + elem); return false; } // Verify that all the children are equal and at the correct indices Element child, compareChild; for (int i = 0; i < getNumberOfChildren(); i++) { child = getChildAt(i); compareChild = elem.getChildAt(i); if (!child.equalTree(compareChild)) { return false; } } return true; } }
package org.restheart.mongodb.db; import com.mongodb.MongoClient; import com.mongodb.client.ClientSession; import static com.mongodb.client.model.Filters.eq; import com.mongodb.client.model.IndexOptions; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.conversions.Bson; import static org.restheart.exchange.ExchangeKeys.DB_META_DOCID; import org.restheart.utils.HttpStatus; /** * * @author Andrea Di Cesare {@literal <andrea@softinstigate.com>} */ class IndexDAO { public static final Bson METADATA_QUERY = eq("_id", DB_META_DOCID); private static final BsonDocument FIELDS_TO_RETURN_INDEXES; static { FIELDS_TO_RETURN_INDEXES = new BsonDocument(); FIELDS_TO_RETURN_INDEXES.put("key", new BsonInt32(1)); FIELDS_TO_RETURN_INDEXES.put("name", new BsonInt32(1)); } private final CollectionDAO collectionDAO; IndexDAO(MongoClient client) { this.collectionDAO = new CollectionDAO(client); } /** * * @param cs the client session * @param dbName * @param collName * @return */ List<BsonDocument> getCollectionIndexes( final ClientSession cs, final String dbName, final String collName) { var ret = new ArrayList<BsonDocument>(); var indexes = cs == null ? collectionDAO.getCollection(dbName, collName).listIndexes() : collectionDAO.getCollection(dbName, collName).listIndexes(cs); indexes.iterator().forEachRemaining( i -> { var bi = BsonDocument.parse(i.toJson()); var name = bi.remove("name"); bi.put("_id", name); ret.add(bi); }); return ret; } /** * * @param cs the client session * @param dbName * @param collection * @param keys * @param options */ void createIndex( final ClientSession cs, final String dbName, final String collection, final BsonDocument keys, final BsonDocument options) { if (options == null) { if (cs == null) { collectionDAO.getCollection(dbName, collection).createIndex(keys); } else { collectionDAO.getCollection(dbName, collection).createIndex(cs, keys); } } else { if (cs == null) { collectionDAO.getCollection(dbName, collection).createIndex(keys, getIndexOptions(options)); } else { collectionDAO.getCollection(dbName, collection).createIndex(cs, keys, getIndexOptions(options)); } } } /** * * @param cs the client session * @param db * @param collection * @param indexId * @return */ int deleteIndex( final ClientSession cs, final String dbName, final String collection, final String indexId) { if (cs == null) { collectionDAO.getCollection(dbName, collection).dropIndex(indexId); } else { collectionDAO.getCollection(dbName, collection).dropIndex(cs, indexId); } return HttpStatus.SC_NO_CONTENT; } @SuppressWarnings("deprecation") IndexOptions getIndexOptions(final BsonDocument options) { var ret = new IndexOptions();
// Importer.java package loci.plugins; import ij.*; import ij.io.FileInfo; import ij.measure.Calibration; import ij.process.*; import java.io.*; import java.util.*; import loci.formats.*; import loci.formats.ome.OMEReader; import loci.formats.ome.OMEXMLMetadata; import loci.plugins.browser.LociDataBrowser; public class Importer { // -- Fields -- /** * A handle to the plugin wrapper, for toggling * the canceled and success flags. */ private LociImporter plugin; private Vector imps = new Vector(); private String stackOrder = null; // -- Constructor -- public Importer(LociImporter plugin) { this.plugin = plugin; } // -- Importer API methods -- /** Executes the plugin. */ public void run(String arg) { // -- Step 1: parse core options -- ImporterOptions options = new ImporterOptions(); options.loadPreferences(); options.parseArg(arg); int status = options.promptLocation(); if (!statusOk(status)) return; status = options.promptId(); if (!statusOk(status)) return; String id = options.getId(); boolean quiet = options.isQuiet(); Location idLoc = options.getIdLocation(); String idName = options.getIdName(); String idType = options.getIdType(); // -- Step 2: construct reader and check id -- IFormatReader r = null; if (options.isLocal() || options.isHTTP()) { IJ.showStatus("Identifying " + idName); ImageReader reader = new ImageReader(); try { r = reader.getReader(id); } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was an error reading the file."); return; } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was a I/O problem reading the file."); return; } } else { // options.isOME r = new OMEReader(); } OMEXMLMetadata store = new OMEXMLMetadata(); r.setMetadataStore(store); IJ.showStatus(""); r.addStatusListener(new StatusEchoer()); // -- Step 3: get parameter values -- status = options.promptOptions(); if (!statusOk(status)) return; boolean mergeChannels = options.isMergeChannels(); boolean colorize = options.isColorize(); boolean showMetadata = options.isShowMetadata(); boolean groupFiles = options.isGroupFiles(); boolean concatenate = options.isConcatenate(); boolean specifyRanges = options.isSpecifyRanges(); boolean autoscale = options.isAutoscale(); boolean viewNone = options.isViewNone(); boolean viewStandard = options.isViewStandard(); boolean viewImage5D = options.isViewImage5D(); boolean viewBrowser = options.isViewBrowser(); boolean viewView5D = options.isViewView5D(); // -- Step 4: analyze and read from data source -- IJ.showStatus("Analyzing " + id); try { FileStitcher fs = null; r.setMetadataFiltered(true); r.setId(id); int pixelType = r.getPixelType(); String currentFile = r.getCurrentFile(); // -- Step 4a: prompt for the file pattern, if necessary -- if (groupFiles) { status = options.promptFilePattern(); if (!statusOk(status)) return; id = options.getId(); } // CTR FIXME -- why is the file stitcher separate from the reader? // (answer: because of the clunkiness of the 4D Data Browser integration) if (groupFiles) r = fs = new FileStitcher(r, true); r = new ChannelSeparator(r); r.setId(id); // -- Step 4b: prompt for which series to import, if necessary -- // populate series-related variables int seriesCount = r.getSeriesCount(); int[] num = new int[seriesCount]; int[] sizeC = new int[seriesCount]; int[] sizeZ = new int[seriesCount]; int[] sizeT = new int[seriesCount]; boolean[] certain = new boolean[seriesCount]; int[] cBegin = new int[seriesCount]; int[] cEnd = new int[seriesCount]; int[] cStep = new int[seriesCount]; int[] zBegin = new int[seriesCount]; int[] zEnd = new int[seriesCount]; int[] zStep = new int[seriesCount]; int[] tBegin = new int[seriesCount]; int[] tEnd = new int[seriesCount]; int[] tStep = new int[seriesCount]; boolean[] series = new boolean[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } series[0] = true; // build descriptive label for each series String[] seriesLabels = new String[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); StringBuffer sb = new StringBuffer(); String name = store.getImageName(new Integer(i)); if (name != null && name.length() > 0) { sb.append(name); sb.append(": "); } sb.append(r.getSizeX()); sb.append(" x "); sb.append(r.getSizeY()); sb.append("; "); sb.append(num[i]); sb.append(" plane"); if (num[i] > 1) { sb.append("s"); if (certain[i]) { sb.append(" ("); boolean first = true; if (sizeC[i] > 1) { sb.append(sizeC[i]); sb.append("C"); first = false; } if (sizeZ[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeZ[i]); sb.append("Z"); first = false; } if (sizeT[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeT[i]); sb.append("T"); first = false; } sb.append(")"); } } seriesLabels[i] = sb.toString(); } if (seriesCount > 1) { status = options.promptSeries(r, seriesLabels, series); if (!statusOk(status)) return; } // -- Step 4c: prompt for the range of planes to import, if necessary -- if (specifyRanges) { boolean needRange = false; for (int i=0; i<seriesCount; i++) { if (series[i] && num[i] > 1) needRange = true; } if (needRange) { IJ.showStatus(""); status = options.promptRange(r, series, seriesLabels, cBegin, cEnd, cStep, zBegin, zEnd, zStep, tBegin, tEnd, tStep); if (!statusOk(status)) return; } } int[] cCount = new int[seriesCount]; int[] zCount = new int[seriesCount]; int[] tCount = new int[seriesCount]; for (int i=0; i<seriesCount; i++) { cCount[i] = (cEnd[i] - cBegin[i] + cStep[i]) / cStep[i]; zCount[i] = (zEnd[i] - zBegin[i] + zStep[i]) / zStep[i]; tCount[i] = (tEnd[i] - tBegin[i] + tStep[i]) / tStep[i]; } // -- Step 4d: display metadata, if appropriate -- if (showMetadata) { IJ.showStatus("Populating metadata"); // display standard metadata in a table in its own window Hashtable meta = new Hashtable(); if (seriesCount == 1) meta = r.getMetadata(); meta.put(idType, currentFile); int digits = digits(seriesCount); for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); meta.putAll(r.getCoreMetadata().seriesMetadata[i]); String s = store.getImageName(new Integer(i)); if ((s == null || s.trim().length() == 0) && seriesCount > 1) { StringBuffer sb = new StringBuffer(); sb.append("Series "); int zeroes = digits - digits(i + 1); for (int j=0; j<zeroes; j++) sb.append(0); sb.append(i + 1); sb.append(" "); s = sb.toString(); } else s += " "; final String pad = " "; // puts core values first when alphabetizing meta.put(pad + s + "SizeX", new Integer(r.getSizeX())); meta.put(pad + s + "SizeY", new Integer(r.getSizeY())); meta.put(pad + s + "SizeZ", new Integer(r.getSizeZ())); meta.put(pad + s + "SizeT", new Integer(r.getSizeT())); meta.put(pad + s + "SizeC", new Integer(r.getSizeC())); meta.put(pad + s + "IsRGB", new Boolean(r.isRGB())); meta.put(pad + s + "PixelType", FormatTools.getPixelTypeString(r.getPixelType())); meta.put(pad + s + "LittleEndian", new Boolean(r.isLittleEndian())); meta.put(pad + s + "DimensionOrder", r.getDimensionOrder()); meta.put(pad + s + "IsInterleaved", new Boolean(r.isInterleaved())); } // sort metadata keys Enumeration e = meta.keys(); Vector v = new Vector(); while (e.hasMoreElements()) v.add(e.nextElement()); String[] keys = new String[v.size()]; v.copyInto(keys); Arrays.sort(keys); StringBuffer sb = new StringBuffer(); for (int i=0; i<keys.length; i++) { sb.append(keys[i]); sb.append("\t"); sb.append(meta.get(keys[i])); sb.append("\n"); } SearchableWindow w = new SearchableWindow("Metadata - " + id, "Key\tValue", sb.toString(), 400, 400); w.setVisible(true); } // -- Step 4e: read pixel data -- // only read data explicitly if not using 4D Data Browser if (!viewBrowser) { IJ.showStatus("Reading " + currentFile); for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); boolean[] load = new boolean[num[i]]; if (!viewNone) { for (int c=cBegin[i]; c<=cEnd[i]; c+=cStep[i]) { for (int z=zBegin[i]; z<=zEnd[i]; z+=zStep[i]) { for (int t=tBegin[i]; t<=tEnd[i]; t+=tStep[i]) { int index = r.getIndex(z, c, t); load[index] = true; } } } } int total = 0; for (int j=0; j<num[i]; j++) if (load[j]) total++; // dump OME-XML to ImageJ's description field, if available FileInfo fi = new FileInfo(); fi.description = store.dumpXML(); long startTime = System.currentTimeMillis(); long time = startTime; ImageStack stackB = null; // for byte images (8-bit) ImageStack stackS = null; // for short images (16-bit) ImageStack stackF = null; // for floating point images (32-bit) ImageStack stackO = null; // for all other images (24-bit RGB) int w = r.getSizeX(); int h = r.getSizeY(); int c = r.getRGBChannelCount(); int type = r.getPixelType(); int q = 0; stackOrder = options.getStackOrder(); if (stackOrder.equals(ImporterOptions.ORDER_DEFAULT)) { stackOrder = r.getDimensionOrder(); } if (options.isViewView5D()) { stackOrder = ImporterOptions.ORDER_XYZCT; } if (options.isViewImage5D()) { stackOrder = ImporterOptions.ORDER_XYCZT; } for (int j=0; j<num[i]; j++) { if (!load[j]) continue; // limit message update rate long clock = System.currentTimeMillis(); if (clock - time >= 100) { IJ.showStatus("Reading " + (seriesCount > 1 ? ("series " + (i + 1) + ", ") : "") + "plane " + (j + 1) + "/" + num[i]); time = clock; } IJ.showProgress((double) q++ / total); int ndx = FormatTools.getReorderedIndex(r, stackOrder, j); // construct label for this slice int[] zct = r.getZCTCoords(ndx); StringBuffer sb = new StringBuffer(); if (certain[i]) { boolean first = true; if (cCount[i] > 1) { if (first) first = false; else sb.append("; "); sb.append("ch:"); sb.append(zct[1] + 1); sb.append("/"); sb.append(sizeC[i]); } if (zCount[i] > 1) { if (first) first = false; else sb.append("; "); sb.append("z:"); sb.append(zct[0] + 1); sb.append("/"); sb.append(sizeZ[i]); } if (tCount[i] > 1) { if (first) first = false; else sb.append("; "); sb.append("t:"); sb.append(zct[2] + 1); sb.append("/"); sb.append(sizeT[i]); } } else { sb.append("no:"); sb.append(j + 1); sb.append("/"); sb.append(num[i]); } // put image name at the end, in case it is too long String imageName = store.getImageName(new Integer(i)); if (imageName != null) { sb.append(" - "); sb.append(imageName); } String label = sb.toString(); // get image processor for jth plane ImageProcessor ip = Util.openProcessor(r, ndx); if (ip == null) { plugin.canceled = true; return; } // add plane to image stack if (ip instanceof ByteProcessor) { if (stackB == null) stackB = new ImageStack(w, h); stackB.addSlice(label, ip); } else if (ip instanceof ShortProcessor) { if (stackS == null) stackS = new ImageStack(w, h); stackS.addSlice(label, ip); } else if (ip instanceof FloatProcessor) { // merge image plane into existing stack if possible if (stackB != null) { ip = ip.convertToByte(true); stackB.addSlice(label, ip); } else if (stackS != null) { ip = ip.convertToShort(true); stackS.addSlice(label, ip); } else { if (stackF == null) stackF = new ImageStack(w, h); stackF.addSlice(label, ip); } } else if (ip instanceof ColorProcessor) { if (stackO == null) stackO = new ImageStack(w, h); stackO.addSlice(label, ip); } } IJ.showStatus("Creating image"); IJ.showProgress(1); String seriesName = store.getImageName(new Integer(i)); showStack(stackB, currentFile, seriesName, store, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, fs, options); showStack(stackS, currentFile, seriesName, store, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, fs, options); showStack(stackF, currentFile, seriesName, store, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, fs, options); showStack(stackO, currentFile, seriesName, store, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, fs, options); long endTime = System.currentTimeMillis(); double elapsed = (endTime - startTime) / 1000.0; if (num[i] == 1) { IJ.showStatus("Bio-Formats: " + elapsed + " seconds"); } else { long average = (endTime - startTime) / num[i]; IJ.showStatus("Bio-Formats: " + elapsed + " seconds (" + average + " ms per plane)"); } } r.close(); if (concatenate) { Vector widths = new Vector(); Vector heights = new Vector(); Vector types = new Vector(); Vector newImps = new Vector(); for (int i=0; i<imps.size(); i++) { ImagePlus imp = (ImagePlus) imps.get(i); int w = imp.getWidth(); int h = imp.getHeight(); int type = imp.getBitDepth(); boolean append = false; for (int j=0; j<widths.size(); j++) { int width = ((Integer) widths.get(j)).intValue(); int height = ((Integer) heights.get(j)).intValue(); int t = ((Integer) types.get(j)).intValue(); if (width == w && height == h && type == t) { ImagePlus oldImp = (ImagePlus) newImps.get(j); ImageStack is = oldImp.getStack(); ImageStack newStack = imp.getStack(); for (int k=0; k<newStack.getSize(); k++) { is.addSlice(newStack.getSliceLabel(k+1), newStack.getProcessor(k+1)); } oldImp.setStack(oldImp.getTitle(), is); newImps.setElementAt(oldImp, j); append = true; j = widths.size(); } } if (!append) { widths.add(new Integer(w)); heights.add(new Integer(h)); types.add(new Integer(type)); newImps.add(imp); } } boolean splitC = options.isSplitChannels(); boolean splitZ = options.isSplitFocalPlanes(); boolean splitT = options.isSplitTimepoints(); for (int i=0; i<newImps.size(); i++) { ImagePlus imp = (ImagePlus) newImps.get(i); imp.show(); if (splitC || splitZ || splitT) { IJ.runPlugIn("loci.plugins.Slicer", "sliceZ=" + splitZ + ", sliceC=" + splitC + ", sliceT=" + splitT + ", stackOrder=" + stackOrder + ", keepOriginal=false"); } } } } // -- Step 5: finish up -- plugin.success = true; options.savePreferences(); if (viewBrowser) { boolean first = true; for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; IFormatReader reader = first ? r : null; FileStitcher stitcher = first ? fs : null; //new LociDataBrowser(reader, id, i, mergeChannels).run(); new LociDataBrowser(reader, stitcher, id, i, mergeChannels).run(); first = false; } } } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was a problem reading the data."); } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was an I/O problem reading the data."); } } // -- Helper methods -- /** * Displays the given image stack according to * the specified parameters and import options. */ private void showStack(ImageStack stack, String file, String series, OMEXMLMetadata store, int cCount, int zCount, int tCount, int sizeZ, int sizeC, int sizeT, FileInfo fi, IFormatReader r, FileStitcher fs, ImporterOptions options) throws FormatException, IOException { if (stack == null) return; String title = file.substring(file.lastIndexOf(File.separator) + 1); if (series != null && !file.endsWith(series)) { title += " - " + series; } if (title.length() > 128) { String a = title.substring(0, 122); String b = title.substring(title.length() - 122); title = a + "..." + b; } ImagePlus imp = new ImagePlus(title, stack); imp.setProperty("Info", "File full path=" + file + "\nSeries name=" + series + "\n"); // retrieve the spatial calibration information, if available applyCalibration(store, imp, r.getSeries()); imp.setFileInfo(fi); imp.setDimensions(cCount, zCount, tCount); displayStack(imp, r, fs, options); } /** Displays the image stack using the appropriate plugin. */ private void displayStack(ImagePlus imp, IFormatReader r, FileStitcher fs, ImporterOptions options) { boolean mergeChannels = options.isMergeChannels(); boolean concatenate = options.isConcatenate(); int nChannels = imp.getNChannels(); int nSlices = imp.getNSlices(); int nFrames = imp.getNFrames(); if (options.isAutoscale()) Util.adjustColorRange(imp); // convert to RGB if needed int pixelType = r.getPixelType(); if (mergeChannels && r.getSizeC() > 1 && r.getSizeC() < 4 && (pixelType == FormatTools.UINT8 || pixelType == FormatTools.INT8) && !r.isIndexed()) { makeRGB(imp, r, r.getSizeC(), options.isAutoscale()); } else if (mergeChannels && r.getSizeC() > 1 && r.getSizeC() < 4 && !r.isIndexed()) { // use compareTo instead of IJ.versionLessThan(...), because we want // to suppress the error message if (imp.getStackSize() == r.getSizeC() && ImageJ.VERSION.compareTo("1.38n") < 0) { // use reflection to construct CompositeImage, // in case ImageJ version is too old ReflectedUniverse ru = new ReflectedUniverse(); try { ru.exec("import ij.CompositeImage"); ru.setVar("imp", imp); ru.setVar("sizeC", r.getSizeC()); imp = (ImagePlus) ru.exec("new CompositeImage(imp, sizeC)"); } catch (ReflectException exc) { imp = new CustomImage(imp, stackOrder, r.getSizeZ(), r.getSizeT(), r.getSizeC(), options.isAutoscale()); } } else { imp = new CustomImage(imp, stackOrder, r.getSizeZ(), r.getSizeT(), r.getSizeC(), options.isAutoscale()); } } else if (mergeChannels && r.getSizeC() >= 4) { // ask the user what they would like to do... // CTR FIXME -- migrate into ImporterOptions? // also test with macros, and merging multiple image stacks // (i.e., what happens if this code executes more than once?) int planes1 = r.getImageCount() / 2; if (planes1 * 2 < r.getImageCount()) planes1++; int planes2 = r.getImageCount() / 3; if (planes2 * 3 < r.getImageCount()) planes2++; if (options.promptMergeOption(planes1, planes2) == ImporterOptions.STATUS_OK) { String option = options.getMergeOption(); if (option.indexOf("2 channels") != -1) { makeRGB(imp, r, 2, options.isAutoscale()); } else if (option.indexOf("3 channels") != -1) { makeRGB(imp, r, 3, options.isAutoscale()); } } } boolean splitC = options.isSplitChannels(); boolean splitZ = options.isSplitFocalPlanes(); boolean splitT = options.isSplitTimepoints(); imp.setDimensions(imp.getStackSize() / (nSlices * nFrames), nSlices, nFrames); if (options.isViewBrowser()) { } else if (options.isViewImage5D()) { ReflectedUniverse ru = new ReflectedUniverse(); try { ru.exec("import i5d.Image5D"); ru.setVar("title", imp.getTitle()); ru.setVar("stack", imp.getStack()); ru.setVar("sizeC", r.getSizeC()); ru.setVar("sizeZ", r.getSizeZ()); ru.setVar("sizeT", r.getSizeT()); ru.exec("i5d = new Image5D(title, stack, sizeC, sizeZ, sizeT)"); ru.setVar("cal", imp.getCalibration()); ru.setVar("fi", imp.getFileInfo()); ru.exec("i5d.setCalibration(cal)"); ru.exec("i5d.setFileInfo(fi)"); //ru.exec("i5d.setDimensions(sizeC, sizeZ, sizeT)"); ru.exec("i5d.show()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem interfacing with Image5D"); return; } } else if (options.isViewView5D()) { WindowManager.setTempCurrentImage(imp); IJ.run("View5D ", ""); } else if (!options.isViewNone()) { if (!concatenate) { imp.show(); if (splitC || splitZ || splitT) { IJ.runPlugIn("loci.plugins.Slicer", "slice_z=" + splitZ + " slice_c=" + splitC + " slice_t=" + splitT + " stack_order=" + stackOrder + " keep_original=false"); } } else imps.add(imp); } } /** Applies spatial calibrations to an image stack. */ private void applyCalibration(OMEXMLMetadata store, ImagePlus imp, int series) { double xcal = Double.NaN, ycal = Double.NaN, zcal = Double.NaN; Integer ii = new Integer(series); Float xf = store.getPixelSizeX(ii); if (xf != null) xcal = xf.floatValue(); Float yf = store.getPixelSizeY(ii); if (yf != null) ycal = yf.floatValue(); Float zf = store.getPixelSizeZ(ii); if (zf != null) zcal = zf.floatValue(); if (xcal == xcal || ycal == ycal || zcal == zcal) { Calibration cal = new Calibration(); cal.setUnit("micron"); cal.pixelWidth = xcal; cal.pixelHeight = ycal; cal.pixelDepth = zcal; imp.setCalibration(cal); } } private void makeRGB(ImagePlus imp, IFormatReader r, int c, boolean scale) { ImageStack s = imp.getStack(); ImageStack newStack = new ImageStack(s.getWidth(), s.getHeight()); for (int i=0; i<s.getSize(); i++) { ImageProcessor p = s.getProcessor(i + 1).convertToByte(true); newStack.addSlice(s.getSliceLabel(i + 1), p); } imp.setStack(imp.getTitle(), newStack); if (scale) Util.adjustColorRange(imp); s = imp.getStack(); newStack = new ImageStack(s.getWidth(), s.getHeight()); int sizeZ = r.getSizeZ(); int sizeT = r.getSizeT(); int[][] indices = new int[c][s.getSize() / c]; int[] pt = new int[c]; Arrays.fill(pt, 0); for (int i=0; i<s.getSize(); i++) { int[] zct = FormatTools.getZCTCoords(stackOrder, sizeZ, r.getEffectiveSizeC(), sizeT, r.getImageCount(), i); int cndx = zct[1]; indices[cndx][pt[cndx]++] = i; } for (int i=0; i<indices[0].length; i++) { ColorProcessor cp = new ColorProcessor(s.getWidth(), s.getHeight()); byte[][] bytes = new byte[indices.length][]; for (int j=0; j<indices.length; j++) { bytes[j] = (byte[]) s.getProcessor(indices[j][i] + 1).getPixels(); } cp.setRGB(bytes[0], bytes[1], bytes.length == 3 ? bytes[2] : new byte[s.getWidth() * s.getHeight()]); newStack.addSlice(s.getSliceLabel( indices[indices.length - 1][i] + 1), cp); } imp.setStack(imp.getTitle(), newStack); } /** Computes the given value's number of digits. */ private int digits(int value) { int digits = 0; while (value > 0) { value /= 10; digits++; } return digits; } /** Verifies that the given status result is OK. */ private boolean statusOk(int status) { if (status == ImporterOptions.STATUS_CANCELED) plugin.canceled = true; return status == ImporterOptions.STATUS_OK; } /** Reports the given exception with stack trace in an ImageJ error dialog. */ private void reportException(Throwable t, boolean quiet, String msg) { IJ.showStatus(""); if (!quiet) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(buf)); String s = new String(buf.toByteArray()); StringTokenizer st = new StringTokenizer(s, "\n\r"); while (st.hasMoreTokens()) IJ.write(st.nextToken()); IJ.error("Bio-Formats Importer", msg); } } // -- Main method -- /** Main method, for testing. */ public static void main(String[] args) { new ImageJ(null); StringBuffer sb = new StringBuffer(); for (int i=0; i<args.length; i++) { if (i > 0) sb.append(" "); sb.append(args[i]); } new LociImporter().run(sb.toString()); } // -- Helper classes -- /** Used to echo status messages to the ImageJ status bar. */ private static class StatusEchoer implements StatusListener { public void statusUpdated(StatusEvent e) { IJ.showStatus(e.getStatusMessage()); } } }
package name.abuchen.portfolio.util; import java.math.BigInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public class Iban { private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$ private static final String DEFAULT_CHECK_DIGIT = "00"; public static final String PATTERN = "[A-Z]{2}[0-9.?-]{2}[0-9]{18}"; //$NON-NLS-1$ public static final int IBANNUMBER_MIN_SIZE = 22; public static final int IBANNUMBER_MAX_SIZE = 22; public static final BigInteger IBANNUMBER_MAGIC_NUMBER = new BigInteger("97"); public static final String IBANNUMBER_DUMMY = "NA68012345678901234567"; public static final String IBANNUMBER_ANY = "NA08765432109876543210"; public Iban() { } public static final boolean isValid(String iban) // NOSONAR { if (iban == null) return false; String newAccountNumber = iban.trim(); // Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid. We could also check // for specific length according to country, but for now we won't if (newAccountNumber.length() < IBANNUMBER_MIN_SIZE || newAccountNumber.length() > IBANNUMBER_MAX_SIZE) return false; // Move the four initial characters to the end of the string. newAccountNumber = newAccountNumber.substring(4) + newAccountNumber.substring(0, 4); // Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35. StringBuilder numericAccountNumber = new StringBuilder(); int numericValue; for (int i = 0;i < newAccountNumber.length();i++) { numericValue = Character.getNumericValue(newAccountNumber.charAt(i)); if(-1 >= numericValue) return false; else numericAccountNumber.append(numericValue); } // Interpret the string as a decimal integer and compute the remainder of that number on division by 97. BigInteger ibanNumber = new BigInteger(numericAccountNumber.toString()); int i = ibanNumber.mod(IBANNUMBER_MAGIC_NUMBER).intValue(); return i == 1; } private static int calculateMod(final String iban) { final String reformattedIban = iban.substring(4) + iban.substring(0, 4); long total = 0; for (int i = 0; i < reformattedIban.length(); i++) { final int numericValue = Character.getNumericValue(reformattedIban.charAt(i)); total = (numericValue > 9 ? total * 100 : total * 10) + numericValue; if (total > 999999999) total = (total % IBANNUMBER_MAGIC_NUMBER.intValue()); } return (int) (total % IBANNUMBER_MAGIC_NUMBER.intValue()); } public static String calculateCheckDigit(final String iban) { Pattern pattern = Pattern.compile(PATTERN); //$NON-NLS-1$ //$NON-NLS-2$ Matcher matcher = pattern.matcher(iban); if (matcher.matches()) { final String reformattedIban = String.format("%2s%2s%18s", iban.substring(0, 2), Iban.DEFAULT_CHECK_DIGIT, StringUtils.leftPad(iban.substring(4), 18, '0')); final int modResult = calculateMod(reformattedIban); final int checkDigitIntValue = (IBANNUMBER_MAGIC_NUMBER.intValue() + 1 - modResult); final String checkDigit = Integer.toString(checkDigitIntValue); return checkDigitIntValue > 9 ? checkDigit : "0" + checkDigit; } return "XX"; } public static final String suggestIban(String iban) { if ((iban.substring(2, 4).equals("..") || iban.substring(2, 4).equals("??")) && (iban.length() >= IBANNUMBER_MIN_SIZE && iban.length() <= IBANNUMBER_MAX_SIZE)) iban = (iban.substring(0, 2) + calculateCheckDigit(iban) + iban.substring(4, 22)).toUpperCase(); return iban; } public static final String DEconvert(String blz, String account) // NOSONAR { String country = "DE"; String iban = String.format("%2s%2s%8s%10s", country, "XX", StringUtils.leftPad(blz, 8, '0'), StringUtils.leftPad(account, 10, '0')); iban = iban.substring(0, 2) + calculateCheckDigit(iban) + iban.substring(4); return iban; } }
package nakadi; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Scheduler; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.exceptions.UndeliverableException; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; import io.reactivex.schedulers.Schedulers; import java.io.BufferedReader; import java.io.IOException; import java.io.InterruptedIOException; import java.io.UncheckedIOException; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * API support for streaming events to a consumer. * <p> * Supports both the name event type streams and the more recent subscription based streams. * The API's connection streaming models are fundamentally the same, but have some differences * in detail, such as request parameters and the structure of the batch cursor. Users * should consult the Nakadi API documentation and {@link StreamConfiguration} for details * on the streaming options. * </p> * * @see nakadi.StreamConfiguration */ public class StreamProcessor implements StreamProcessorManaged { private static final Logger logger = LoggerFactory.getLogger(NakadiClient.class.getSimpleName()); private static final int DEFAULT_HALF_OPEN_CONNECTION_GRACE_SECONDS = 90; private static final int DEFAULT_BUFFER_SIZE = 16000; private final NakadiClient client; private final StreamConfiguration streamConfiguration; private final StreamObserverProvider streamObserverProvider; private final StreamOffsetObserver streamOffsetObserver; private final ExecutorService streamProcessorExecutorService; private final JsonBatchSupport jsonBatchSupport; private final long maxRetryDelay; private final String scope; // non builder supplied private final AtomicBoolean started = new AtomicBoolean(false); private final ExecutorService monoIoExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setNameFormat("nakadi-java-io-%d") .setUncaughtExceptionHandler((t, e) -> handleUncaught(t, e, "stream_processor_err_io")) .build()); private final ExecutorService monoComputeExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setNameFormat("nakadi-java-compute-%d") .setUncaughtExceptionHandler( (t, e) -> handleUncaught(t, e, "stream_processor_err_compute")) .build()); private final Scheduler monoIoScheduler = Schedulers.from(monoIoExecutor); private final Scheduler monoComputeScheduler = Schedulers.from(monoComputeExecutor); private final CountDownLatch startBlockingLatch; private final StreamProcessorRequestFactory streamProcessorRequestFactory; private CompositeDisposable composite; @VisibleForTesting @SuppressWarnings("unused") StreamProcessor(NakadiClient client, StreamProcessorRequestFactory streamProcessorRequestFactory) { this.client = client; this.streamConfiguration = null; this.streamObserverProvider = null; this.streamOffsetObserver = null; this.streamProcessorExecutorService = null; this.jsonBatchSupport = new JsonBatchSupport(client.jsonSupport()); this.maxRetryDelay = StreamConnectionRetryFlowable.DEFAULT_MAX_DELAY_SECONDS; this.scope = null; this.composite = new CompositeDisposable(); startBlockingLatch = new CountDownLatch(1); this.streamProcessorRequestFactory = streamProcessorRequestFactory; } private StreamProcessor(Builder builder) { this.streamConfiguration = builder.streamConfiguration; this.client = builder.client; this.streamObserverProvider = builder.streamObserverProvider; this.streamOffsetObserver = builder.streamOffsetObserver; this.streamProcessorExecutorService = builder.executorService; this.jsonBatchSupport = new JsonBatchSupport(client.jsonSupport()); this.maxRetryDelay = streamConfiguration.maxRetryDelaySeconds(); this.scope = builder.scope; this.composite = new CompositeDisposable(); startBlockingLatch = new CountDownLatch(1); this.streamProcessorRequestFactory = builder.streamProcessorRequestFactory; } /** * Provide a new builder for creating a stream processor. * * @param client the client * @return a builder */ public static StreamProcessor.Builder newBuilder(NakadiClient client) { return new StreamProcessor.Builder().client(client); } private static boolean isInterrupt(Throwable e) { // unwrap to see if this is an InterruptedIOException bubbled up from rx/okio if (e instanceof UndeliverableException) { if (e.getCause() != null && e.getCause() instanceof UncheckedIOException) { if (e.getCause().getCause() != null && e.getCause().getCause() instanceof InterruptedIOException) { return true; } } } return false; } private static ExecutorService newStreamProcessorExecutorService() { final ThreadFactory tf = new ThreadFactoryBuilder() .setUncaughtExceptionHandler((t, e) -> handleUncaught(t, e, "stream_processor_err")) .setNameFormat("nakadi-java").build(); return Executors.newFixedThreadPool(1, tf); } private static void handleUncaught(Thread t, Throwable e, String name) { if (isInterrupt(e)) { Thread.currentThread().interrupt(); } else { logger.error("{} {}, {}", name, t, e); } } /** * Start consuming the stream. This runs in a background executor and will not block the * calling thread. Callers must hold onto a reference in order to be able to shut it down. * The underlying executor calls {@link #startBlocking}. * * <p> * Calling start multiple times is the same as calling it once, when stop is not also called * or interleaved with. * </p> * * @see #stop() */ public void start() { if (!started.getAndSet(true)) { executorService().submit(this::startStreaming); } } /** * Perform a controlled shutdown of the stream. The {@link StreamObserver} will have * its onCompleted or onError called under normal circumstances. The {@link StreamObserver} * in turn can call its {@link StreamOffsetObserver} to perform cleanup. * * <p> * Calling stop multiple times is the same as calling it once, when start is not also called * or interleaved with. * </p> * * @see #start() */ public void stop() { if (started.getAndSet(false)) { stopStreaming(); } } /** * Start consuming the stream. This blocks the calling thread. This method is currently * visible for testing and development. It will be removed for 1.0.0 and should not be * relied upon. * * <p> * Calling start multiple times is undefined. Clients must assume responsibility for ensuring * this is called once. * </p> */ @VisibleForTesting public void startBlocking() { if (!started.getAndSet(true)) { startStreaming(); try { startBlockingLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } void startStreaming() { stream(streamConfiguration, streamObserverProvider); } void stopStreaming() { logger.info("stopping stream executor"); ExecutorServiceSupport.shutdown(executorService()); logger.info("stopping stream schedulers"); Schedulers.shutdown(); logger.info("stopping subscriber"); composite.dispose(); startBlockingLatch.countDown(); } @VisibleForTesting StreamOffsetObserver streamOffsetObserver() { return streamOffsetObserver; } private ExecutorService executorService() { return streamProcessorExecutorService; } private <T> void stream(StreamConfiguration sc, StreamObserverProvider<T> observerProvider) { final StreamObserver<T> observer = observerProvider.createStreamObserver(); final TypeLiteral<T> typeLiteral = observerProvider.typeLiteral(); final Flowable<StreamBatchRecord<T>> observable = this.buildStreamObservable(observer, sc, typeLiteral); /* Do processing on monoComputeScheduler; if the monoIoScheduler (or any shared single thread executor) is used, the pipeline can lock up as the thread is dominated by io and never frees to process batches. monoComputeScheduler is a single thread executor to make things easier to reason about for now wrt to ordering/sequential batch processing (but the regular computation scheduler could work as well maybe). */ Optional<Integer> maybeBuffering = observer.requestBuffer(); if (maybeBuffering.isPresent()) { logger.info("Creating buffering subscriber buffer={} {}", maybeBuffering.get(), sc); /* if the stream observer wants buffering set that up; it will still see discrete batches but the rx observer wrapping around it here will be given buffered up lists */ composite.add(observable.observeOn(monoComputeScheduler) .buffer(maybeBuffering.get()) .subscribeWith( new StreamBatchRecordBufferingSubscriber<>(observer, client.metricCollector()))); } else { logger.info("Creating regular subscriber {}", sc); composite.add(observable.observeOn(monoComputeScheduler) .subscribeWith( new StreamBatchRecordSubscriber<>(observer, client.metricCollector()))); } } private <T> Flowable<StreamBatchRecord<T>> buildStreamObservable( StreamObserver<T> streamObserver, StreamConfiguration streamConfiguration, TypeLiteral<T> typeLiteral) { /* compute a timeout after which we assume the server's gone away or we're on one end of a half-open connection. this is a big downside trying to emulate a streaming model over http get; you really need bidirectional comms instead todo: make these configurable */ TimeUnit halfOpenUnit = TimeUnit.SECONDS; long halfOpenGrace = DEFAULT_HALF_OPEN_CONNECTION_GRACE_SECONDS; long batchFlushTimeoutSeconds = this.streamConfiguration.batchFlushTimeoutSeconds(); long halfOpenKick = halfOpenUnit.toSeconds(batchFlushTimeoutSeconds + halfOpenGrace); logger.info( "configuring half open timeout, batch_flush_timeout={}, grace_period={}, disconnect_after={} {}", batchFlushTimeoutSeconds, halfOpenGrace, halfOpenKick, halfOpenUnit.name().toLowerCase()); final Flowable<StreamBatchRecord<T>> flowable = Flowable.using( resourceFactory(streamConfiguration), observableFactory(typeLiteral, streamConfiguration), observableDispose() ) .subscribeOn(monoIoScheduler) .unsubscribeOn(monoIoScheduler) .doOnSubscribe(subscription -> streamObserver.onStart()) .doOnComplete(streamObserver::onCompleted) .doOnCancel(streamObserver::onStop) .timeout(halfOpenKick, halfOpenUnit) // retries handle issues like network failures and 409 conflicts .retryWhen(buildStreamConnectionRetryFlowable()) // restarts handle when the server closes the connection (eg checkpointing fell behind) .compose(buildRestartHandler()) /* todo: investigate why Integer.max causes io.reactivex.exceptions.UndeliverableException: java.lang.NegativeArraySizeException at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:366) */ .onBackpressureBuffer(DEFAULT_BUFFER_SIZE, true, true); return Flowable.defer(() -> flowable); } private StreamConnectionRetryFlowable buildStreamConnectionRetryFlowable( ) { return new StreamConnectionRetryFlowable(ExponentialRetry.newBuilder() .initialInterval(StreamConnectionRetryFlowable.DEFAULT_INITIAL_DELAY_SECONDS, StreamConnectionRetryFlowable.DEFAULT_TIME_UNIT) .maxInterval(maxRetryDelay, StreamConnectionRetryFlowable.DEFAULT_TIME_UNIT) .build(), buildRetryFunction(), client.metricCollector()); } private <T> FlowableTransformer<StreamBatchRecord<T>, StreamBatchRecord<T>> buildRestartHandler() { long restartDelay = StreamConnectionRestart.DEFAULT_DELAY_SECONDS; TimeUnit restartDelayUnit = StreamConnectionRestart.DEFAULT_DELAY_UNIT; int maxRestarts = StreamConnectionRestart.DEFAULT_MAX_RESTARTS; return new StreamConnectionRestart() .repeatWhenWithDelayAndUntil( stopRepeatingPredicate(), restartDelay, restartDelayUnit, maxRestarts); } private Function<Throwable, Boolean> buildRetryFunction() { return ExceptionSupport::isConsumerStreamRetryable; } private Predicate<Long> stopRepeatingPredicate() { return attemptCount -> { // todo: track the actual events checkpointed or seen instead if (streamConfiguration.streamLimit() != StreamConfiguration.DEFAULT_STREAM_TIMEOUT) { logger.info( "stream repeater will not continue to restart, request for a bounded number of events detected stream_limit={} restarts={}", streamConfiguration.streamLimit(), attemptCount); return true; } client.metricCollector().mark(MetricCollector.Meter.streamRestart); return false; }; } private Consumer<? super Response> observableDispose() { return (response) -> { logger.info("stream_connection_dispose thread {} {} {}", Thread.currentThread().getName(), response.hashCode(), response); try { response.responseBody().close(); logger.info("stream_connection_dispose_ok thread {} {} {}", Thread.currentThread().getName(), response.hashCode(), response); } catch (IOException e) { throw new NakadiException( Problem.networkProblem("failed to close stream response", e.getMessage()), e); } }; } private <T> Function<? super Response, Flowable<StreamBatchRecord<T>>> observableFactory( TypeLiteral<T> typeLiteral, StreamConfiguration sc) { return (Response response) -> { final BufferedReader br = new BufferedReader(response.responseBody().asReader()); return Flowable.fromIterable(br.lines()::iterator) .doOnError(throwable -> { boolean closed = false; final String tName = Thread.currentThread().getName(); try { logger.info("stream_iterator_response_close_ask thread={} error={} {} {}", tName, throwable.getMessage(), response.hashCode(), response); response.responseBody().close(); closed = true; logger.info("stream_iterator_response_close_ok thread={} error={} {} {}", tName, throwable.getMessage(), response.hashCode(), response); } catch (Exception e) { logger.warn( "stream_iterator_response_close_error problem closing thread={} {} {} {} {}", tName, e.getClass().getName(), e.getMessage(), response.hashCode(), response); } finally { if (!closed) { try { response.responseBody().close(); closed = true; } catch (IOException e) { logger.warn( "stream_iterator_response_close_error problem re-attempting close thread={} {} {} {} {}", tName, e.getClass().getName(), e.getMessage(), response.hashCode(), response); } } if (!closed) { logger.warn( String.format( "stream_iterator_response_close_failed did not close response thread=%s err=%s %s %s", tName, throwable.getMessage(), response.hashCode(), response), throwable); } } }) .onBackpressureBuffer(DEFAULT_BUFFER_SIZE, true, true) .map(r -> lineToStreamBatchRecord(r, typeLiteral, response, sc)) ; }; } @SuppressWarnings("WeakerAccess") @VisibleForTesting Callable<Response> resourceFactory(StreamConfiguration sc) { return streamProcessorRequestFactory.createCallable(sc); } @SuppressWarnings("WeakerAccess") @VisibleForTesting Response requestStreamConnection(String url, ResourceOptions options, Resource resource) { return resource.requestThrowing(Resource.GET, url, options); } private <T> StreamBatchRecord<T> lineToStreamBatchRecord(String line, TypeLiteral<T> typeLiteral, Response response, StreamConfiguration sc) { logger.debug("tokenized line from stream {}, {}", line, response); if (sc.isSubscriptionStream()) { String xNakadiStreamId = response.headers().get("X-Nakadi-StreamId").get(0); return jsonBatchSupport.lineToSubscriptionStreamBatchRecord( line, typeLiteral.type(), streamOffsetObserver(), xNakadiStreamId, sc.subscriptionId()); } else { return jsonBatchSupport.lineToEventStreamBatchRecord( line, typeLiteral.type(), streamOffsetObserver()); } } @SuppressWarnings("WeakerAccess") @VisibleForTesting Resource buildResource(StreamConfiguration sc) { return client.resourceProvider() .newResource() .readTimeout(sc.readTimeoutMillis(), TimeUnit.MILLISECONDS) .connectTimeout(sc.connectTimeoutMillis(), TimeUnit.MILLISECONDS); } @VisibleForTesting String findEventTypeNameForSubscription(StreamConfiguration sc) { nakadi.Subscription sub = client.resources().subscriptions().find(sc.subscriptionId()); return sub.eventTypes().get(0); } @SuppressWarnings("WeakerAccess") public static class Builder { private NakadiClient client; private StreamObserverProvider streamObserverProvider; private SubscriptionOffsetCheckpointer checkpointer; private StreamOffsetObserver streamOffsetObserver; private StreamConfiguration streamConfiguration; private ExecutorService executorService; private String scope; private StreamProcessorRequestFactory streamProcessorRequestFactory; public Builder() { } public StreamProcessor build() { NakadiException.throwNonNull(streamConfiguration, "Please provide a stream configuration"); if (streamConfiguration.isSubscriptionStream() && streamConfiguration.isEventTypeStream()) { throw new NakadiException(Problem.localProblem( "Cannot be configured with both a subscriptionId and an eventTypeName", String.format("subscriptionId=%s eventTypeName=%s", streamConfiguration.subscriptionId(), streamConfiguration.eventTypeName()))); } if (!streamConfiguration.isSubscriptionStream() && !streamConfiguration.isEventTypeStream()) { throw new NakadiException( Problem.localProblem("Please supply either a subscription id or an event type", "")); } NakadiException.throwNonNull(client, "Please provide a client"); NakadiException.throwNonNull(streamObserverProvider, "Please provide a StreamObserverProvider"); if (streamConfiguration.isSubscriptionStream() && streamOffsetObserver == null) { if (checkpointer == null) { this.checkpointer = new SubscriptionOffsetCheckpointer(client).suppressInvalidSessionException(false); } this.streamOffsetObserver = new SubscriptionOffsetObserver(checkpointer); } if (streamConfiguration.isEventTypeStream() && streamOffsetObserver == null) { this.streamOffsetObserver = new LoggingStreamOffsetObserver(); } if (executorService == null) { this.executorService = newStreamProcessorExecutorService(); } this.scope = Optional.ofNullable(scope).orElse(TokenProvider.NAKADI_EVENT_STREAM_READ); if (streamProcessorRequestFactory == null) { streamProcessorRequestFactory = new StreamProcessorRequestFactory(client, scope); } return new StreamProcessor(this); } public Builder client(NakadiClient client) { this.client = client; return this; } public Builder scope(String scope) { this.scope = scope; return this; } public Builder streamObserverFactory( StreamObserverProvider streamObserverProvider) { this.streamObserverProvider = streamObserverProvider; return this; } public Builder streamOffsetObserver(StreamOffsetObserver streamOffsetObserver) { this.streamOffsetObserver = streamOffsetObserver; return this; } public Builder streamConfiguration(StreamConfiguration streamConfiguration) { this.streamConfiguration = streamConfiguration; return this; } @SuppressWarnings("unused") public Builder executorService(ExecutorService executorService) { this.executorService = executorService; return this; } @Unstable public Builder checkpointer(SubscriptionOffsetCheckpointer checkpointer) { this.checkpointer = checkpointer; return this; } @VisibleForTesting Builder streamProcessorRequestFactory(StreamProcessorRequestFactory factory) { this.streamProcessorRequestFactory = factory; return this; } } }
package de.golfgl.gdxgamesvcs; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.StreamUtils; import com.google.api.client.http.FileContent; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import com.google.api.services.games.model.AchievementDefinition; import com.google.api.services.games.model.Leaderboard; import com.google.api.services.games.model.LeaderboardEntry; import com.google.api.services.games.model.LeaderboardScores; import com.google.api.services.games.model.Player; import com.google.api.services.games.model.PlayerAchievement; import de.golfgl.gdxgamesvcs.GameServiceException.NotSupportedException; import de.golfgl.gdxgamesvcs.IGameServiceListener.GsErrorType; import de.golfgl.gdxgamesvcs.achievement.IAchievement; import de.golfgl.gdxgamesvcs.achievement.IFetchAchievementsResponseListener; import de.golfgl.gdxgamesvcs.gamestate.IFetchGameStatesListResponseListener; import de.golfgl.gdxgamesvcs.gamestate.ILoadGameStateResponseListener; import de.golfgl.gdxgamesvcs.gamestate.ISaveGameStateResponseListener; import de.golfgl.gdxgamesvcs.leaderboard.IFetchLeaderBoardEntriesResponseListener; import de.golfgl.gdxgamesvcs.leaderboard.ILeaderBoardEntry; public class GpgsClient implements IGameServiceClient { private static final String TAG = IGameServiceClient.GS_GOOGLEPLAYGAMES_ID; /** * Shortcut for current user as per Google API doc. */ private static final String ME = "me"; /** current application name */ protected String applicationName; private IGameServiceListener gameListener; private Thread authorizationThread; private volatile boolean connected; private volatile boolean connecting; private boolean initialized; private String playerName; private static interface SafeRunnable{ void run() throws IOException; } private void background(final SafeRunnable runnable){ new Thread(new Runnable() { @Override public void run() { try { runnable.run(); } catch (Throwable e) { Gdx.app.error(TAG, "Gpgs Error", e); if(gameListener != null) gameListener.gsErrorMsg(GsErrorType.errorUnknown, e.getMessage(), e); } } }).start(); } /** * Configure underlying service log level * @param logLevel log level as defined in {@link Application} LOG_* constants. */ public void setLogLevel(int logLevel){ // configure root java logger to gdx log level. Logger.getLogger("").setLevel(getLogLevel(logLevel)); } /** Gdx to Log4j log level mapping */ private static Level getLogLevel(int logLevel){ switch(logLevel){ case Application.LOG_NONE: return Level.OFF; case Application.LOG_ERROR : return Level.SEVERE; case Application.LOG_INFO : return Level.INFO; case Application.LOG_DEBUG : return Level.FINEST; default: return Level.ALL; } } @Override public String getGameServiceId() { return IGameServiceClient.GS_GOOGLEPLAYGAMES_ID; } @Override public void setListener(IGameServiceListener gsListener) { gameListener = gsListener; } /** * Get the data store directory for your app. * This is where users credential (token) will be stored. * * Subclass may override this method in order to provide another location. * * Default is USER_HOME/.store/APPLICATION_NAME * * @return directory to store users credentials for this application */ protected java.io.File getDataStoreDirectory() { java.io.File dataStoresDirectory = new java.io.File(System.getProperty("user.home"), ".store"); return new java.io.File(dataStoresDirectory, applicationName); } /** * Provide a user identifier for the current user. It is only used to store/restore user * credentials (API token) during authorization ({@link #connect(boolean)}. * * Subclass may override this method in order to provide dynamically a user ID based on their own * login system and want to store different credentials for different users. * * Default is the OS user name. * * @return a current user identifier, shouldn't be null. */ protected String getUserId(){ return System.getProperty("user.name"); } /** * Initialize connector. Must be called at application startup. * @param applicationName Application name registered in Google Play. * @param clientSecret client/secret json data you get from Google Play. * * Format is : * <pre> * { * "installed": { * "client_id": "xxxxxxx-yyyyyyyyyyyyyyyyy.apps.googleusercontent.com", * "client_secret": "zzzzzzzzzzzzzzzzzzzzzzzzz" * } * } * </pre> * * @throws GdxRuntimeException if initialisation fails. * @return method chaining */ public GpgsClient initialize(String applicationName, InputStream clientSecret){ this.applicationName = applicationName; try { GApiGateway.init(applicationName, clientSecret, getDataStoreDirectory()); initialized = true; } catch (GeneralSecurityException e) { throw new GdxRuntimeException(e); } catch (IOException e) { throw new GdxRuntimeException(e); } return this; } /** * Initialize with a clientSecretFile. * see {@link #initialize(String, InputStream)} * @param applicationName * @param clientSecretFile * @return method chaining */ public GpgsClient initialize(String applicationName, FileHandle clientSecretFile){ initialize(applicationName, clientSecretFile.read()); return this; } /** * Try to authorize user. This method is blocking until user accept * autorization. */ private void waitForUserAuthorization() { // load user token or open browser for user authorizations. boolean success = false; try { GApiGateway.authorize(getUserId()); success = true; } catch (IOException e) { if(gameListener != null) gameListener.gsErrorMsg(GsErrorType.errorUnknown, "failed to get authorization from user", e); } // try to retreive palyer name if(success){ try { Player player = GApiGateway.games.players().get(ME).execute(); playerName = player.getDisplayName(); } catch (IOException e) { if(gameListener != null) gameListener.gsErrorMsg(GsErrorType.errorUnknown, "Failed to retreive player name", e); } } connected = success; // dispatch status if(gameListener != null){ if(connected){ gameListener.gsConnected(); }else{ gameListener.gsDisconnected(); } } } @Override public boolean connect(boolean silent) { if(initialized && !connected && !connecting){ connecting = true; playerName = null; authorizationThread = new Thread(new Runnable() { @Override public void run() { try{ waitForUserAuthorization(); }finally{ connecting = false; } } }, "GpgsAuthorization"); authorizationThread.start(); } // return false only if client has not been properly initialized. return initialized; } @Override public void disconnect() { // nothing special to do here since there is no resources to freeup. if(gameListener != null) gameListener.gsDisconnected(); } @Override public void logOff() { connected = false; playerName = null; GApiGateway.closeSession(); disconnect(); } @Override public String getPlayerDisplayName() { return playerName; } @Override public boolean isConnected() { return connected; } @Override public boolean isConnectionPending() { return connecting; } @Override public void showLeaderboards(String leaderBoardId) throws GameServiceException { throw new NotSupportedException(); } @Override public void showAchievements() throws GameServiceException { throw new NotSupportedException(); } @Override public boolean submitToLeaderboard(final String leaderboardId, final long score, final String tag) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { submitToLeaderboardSync(leaderboardId, score, tag); } }); } return connected; } /** * Blocking version of {@link #submitToLeaderboard(String, long, String)} * @param leaderboardId * @param score * @param tag * @throws IOException */ public void submitToLeaderboardSync(String leaderboardId, long score, String tag) throws IOException { GApiGateway.games.scores().submit(leaderboardId, score).execute(); } @Override public boolean submitEvent(final String eventId, final int increment) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { submitEventSync(eventId, increment); } }); } return connected; } /** * Blocking version of {@link #submitEvent(String, int)} * @param eventId * @param increment */ public void submitEventSync(String eventId, int increment) { // TODO don't know the API for this use case throw new IllegalStateException("Not implemented"); } @Override public boolean unlockAchievement(final String achievementId) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { unlockAchievementSync(achievementId); } }); } return connected; } /** * Blocking version of {@link #unlockAchievement(String)} * @param achievementId * @throws IOException */ public void unlockAchievementSync(String achievementId) throws IOException { GApiGateway.games.achievements().unlock(achievementId).execute(); } @Override public boolean incrementAchievement(final String achievementId, final int incNum, final float completionPercentage) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { incrementAchievementSync(achievementId, incNum, completionPercentage); } }); } return connected; } /** * Blocking version of {@link #incrementAchievement(String, int, float)} * @param achievementId * @param incNum * @param completionPercentage * @throws IOException */ public void incrementAchievementSync(String achievementId, int incNum, float completionPercentage) throws IOException { GApiGateway.games.achievements().increment(achievementId, incNum).execute(); } @Override public boolean fetchGameStates(final IFetchGameStatesListResponseListener callback) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { Array<String> result = null; try{ result = fetchGamesSync(); }finally{ callback.onFetchGameStatesListResponse(result); } } }); } return connected; } /** * Blocking version of {@link #fetchGamesSync()} * @return game states * @throws IOException */ public Array<String> fetchGamesSync() throws IOException { Array<String> games = new Array<String>(); FileList l = GApiGateway.drive.files().list() .setSpaces("appDataFolder") .setFields("files(name)") .execute(); for(File f : l.getFiles()){ games.add(f.getName()); } return games; } @Override public boolean deleteGameState(final String fileId, final ISaveGameStateResponseListener listener) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { try{ deleteGameStateSync(fileId); if(listener != null) listener.onGameStateSaved(true, null); }catch(IOException e){ if(listener != null) listener.onGameStateSaved(false, "Cannot delete game"); throw e; } } }); } return connected; } public void deleteGameStateSync(String fileId) throws IOException { File remoteFile = findFileByNameSync(fileId); if(remoteFile != null){ GApiGateway.drive.files().delete(remoteFile.getId()).execute(); } } @Override public void saveGameState(final String fileId, final byte[] gameState, final long progressValue, final ISaveGameStateResponseListener listener) { background(new SafeRunnable() { @Override public void run() throws IOException { try{ saveGameStateSync(fileId, gameState, progressValue); if(listener != null) listener.onGameStateSaved(true, null); }catch(IOException e){ if(listener != null) listener.onGameStateSaved(false, "Cannot save game"); throw e; } } }); } private File findFileByNameSync(String name) throws IOException{ // escape some chars (') see : https://developers.google.com/drive/v3/web/search-parameters#fn1 List<File> files = GApiGateway.drive.files().list().setSpaces("appDataFolder").setQ("name='" + name + "'").execute().getFiles(); if(files.size() > 1){ throw new GdxRuntimeException("multiple files with name " + name + " exists."); } else if(files.size() < 1) { return null; } else { return files.get(0); } } /** * Blocking version of {@link #saveGameState(String, byte[], long, ISaveGameStateResponseListener)} * @param fileId * @param gameState * @param progressValue * @throws IOException */ public void saveGameStateSync(String fileId, byte[] gameState, long progressValue) throws IOException { java.io.File file = java.io.File.createTempFile("games", "dat"); new FileHandle(file).writeBytes(gameState, false); // no type since it is binary data FileContent mediaContent = new FileContent(null, file); // find file on server File remoteFile = findFileByNameSync(fileId); // file exists then update it if(remoteFile != null){ // just update content, leave metadata intact. GApiGateway.drive.files().update(remoteFile.getId(), null, mediaContent).execute(); Gdx.app.log(TAG, "File updated ID: " + remoteFile.getId()); } // file doesn't exists then create it else{ File fileMetadata = new File(); fileMetadata.setName(fileId); // app folder is a reserved keyyword for current application private folder. fileMetadata.setParents(Collections.singletonList("appDataFolder")); remoteFile = GApiGateway.drive.files().create(fileMetadata, mediaContent) .setFields("id") .execute(); Gdx.app.log(TAG, "File created ID: " + remoteFile.getId()); } } @Override public void loadGameState(final String fileId, final ILoadGameStateResponseListener listener) { background(new SafeRunnable() { @Override public void run() throws IOException { try{ byte[] data = loadGameStateSync(fileId); if(gameListener != null) listener.gsGameStateLoaded(data); }catch(IOException e){ if(gameListener != null) listener.gsGameStateLoaded(null); throw e; } } }); } /** * Blocking version of {@link #loadGameState(String, ILoadGameStateResponseListener)} * @param fileId * @return game state data * @throws IOException */ public byte [] loadGameStateSync(String fileId) throws IOException { InputStream stream = null; byte [] data = null; try { File remoteFile = findFileByNameSync(fileId); if(remoteFile != null){ stream = GApiGateway.drive.files().get(remoteFile.getId()).executeMediaAsInputStream(); data = StreamUtils.copyStreamToByteArray(stream); } } finally { StreamUtils.closeQuietly(stream); } return data; } @Override public boolean fetchAchievements(final IFetchAchievementsResponseListener callback) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { Array<IAchievement> result = null; try{ result = fetchAchievementsSync(); }finally{ callback.onFetchAchievementsResponse(result); } } }); } return connected; } /** * Blocking version of {@link #fetchAchievements(IFetchAchievementsResponseListener)} * @return the achievement list * @throws IOException */ public Array<IAchievement> fetchAchievementsSync() throws IOException { Array<IAchievement> achievements = new Array<IAchievement>(); // fetch all definitions ObjectMap<String, AchievementDefinition> defs = new ObjectMap<String, AchievementDefinition>(); for(AchievementDefinition def : GApiGateway.games.achievementDefinitions().list().execute().getItems()){ defs.put(def.getId(), def); } // Fetch player achievements for(PlayerAchievement p : GApiGateway.games.achievements().list(ME).execute().getItems()){ AchievementDefinition def = defs.get(p.getId()); String state = p.getAchievementState(); // filter hidden achievements : there is no reasons to display these // to the player. User code could unlock/increment it anyway and user code // can check if this achievement is hidden by its absence in the returned list. if("HIDDEN".equals(state)) continue; GpgsAchievement a = new GpgsAchievement(); a.setAchievementId(def.getId()); a.setTitle(def.getName()); a.setDescription(def.getDescription()); boolean isIncremental = "INCREMENTAL".equals(def.getAchievementType()); boolean unlocked = "UNLOCKED".equals(state); if(unlocked){ a.setCompletionPercentage(1f); } else if(isIncremental){ int currentSteps = 0; if(p.getCurrentSteps() != null){ currentSteps = p.getCurrentSteps().intValue(); } // total steps range between 2 and 10.000 int totalSteps = def.getTotalSteps().intValue(); a.setCompletionPercentage(MathUtils.floorPositive((float)currentSteps / (float)totalSteps)); }else{ a.setCompletionPercentage(0f); } a.setIconUrl(unlocked ? def.getUnlockedIconUrl() : def.getRevealedIconUrl()); achievements.add(a); } return achievements; } @Override public boolean fetchLeaderboardEntries(final String leaderBoardId, final int limit, final boolean relatedToPlayer, final IFetchLeaderBoardEntriesResponseListener callback) { if(connected){ background(new SafeRunnable() { @Override public void run() throws IOException { Array<ILeaderBoardEntry> result = null; try{ result = fetchLeaderboardSync(leaderBoardId, limit, relatedToPlayer, false); }finally{ callback.onLeaderBoardResponse(result); } } }); } return connected; } /** * Blocking version of {@link #fetchLeaderboardEntries(String, int, boolean, IFetchLeaderBoardEntriesResponseListener)} * @param leaderBoardId * @throws IOException */ public Array<ILeaderBoardEntry> fetchLeaderboardSync(String leaderBoardId, int limit, boolean aroundPlayer, boolean friendsOnly) throws IOException { // TODO implement limit Array<ILeaderBoardEntry> result = new Array<ILeaderBoardEntry>(); Leaderboard lb = GApiGateway.games.leaderboards().get(leaderBoardId).execute(); // XXX no longer LB info ... // result.id = lb.getId(); // result.name = lb.getName(); // result.scores = new Array<LeaderBoard.Score>(); // result.iconUrl = lb.getIconUrl(); LeaderboardScores r; if(aroundPlayer){ r = GApiGateway.games.scores().listWindow(leaderBoardId, friendsOnly ? "SOCIAL" : "PUBLIC", "ALL_TIME").execute(); }else{ r = GApiGateway.games.scores().list(leaderBoardId, friendsOnly ? "SOCIAL" : "PUBLIC", "ALL_TIME").execute(); } LeaderboardEntry playerScore = r.getPlayerScore(); // player is null when not having a score yet. // we add it to the list because non-public profile won't appear in // the full list. if(playerScore != null){ GpgsLeaderBoardEntry ps = mapPlayerScore(r.getPlayerScore()); ps.setCurrentPlayer(true); result.add(ps); } // r.getItems is null when no score has been submitted yet. if(r.getItems() != null){ for(LeaderboardEntry score : r.getItems()){ // when player is public it appear in this list as well, so we filter it. if(playerScore == null || !score.getPlayer().getPlayerId().equals(playerScore.getPlayer().getPlayerId())){ GpgsLeaderBoardEntry s = mapPlayerScore(score); s.setCurrentPlayer(false); result.add(s); } } } // maybe already sorted but API doesn't say anything about it : // so we sort list depending of score meaning. final int order = "SMALLER_IS_BETTER".equals(lb.getOrder()) ? 1 : -1; result.sort(new Comparator<ILeaderBoardEntry>() { @Override public int compare(ILeaderBoardEntry o1, ILeaderBoardEntry o2) { return order * Long.compare(o1.getSortValue(), o2.getSortValue()); } }); return result; } private GpgsLeaderBoardEntry mapPlayerScore(LeaderboardEntry score) throws IOException{ GpgsLeaderBoardEntry s = new GpgsLeaderBoardEntry(); s.setUserDisplayName(score.getPlayer().getDisplayName()); s.setScoreRank(score.getFormattedScoreRank()); s.setFormattedValue(score.getFormattedScore()); s.setSortValue(score.getScoreValue() != null ? score.getScoreValue().longValue() : 0); s.setAvatarUrl(score.getPlayer().getAvatarImageUrl()); return s; } @Override public boolean isFeatureSupported(GameServiceFeature feature) { switch(feature){ case FetchAchievements: case FetchGameStates: case FetchLeaderBoardEntries: case GameStateDelete: case GameStateMultipleFiles: case GameStateStorage: return true; default: return false; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.m2mp.db.common; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import java.util.ArrayList; import java.util.List; import org.m2mp.db.DBAccess; /** * * @author Florent Clairambault */ public class GeneralSetting { public static final String TABLE = "GeneralSettings"; // <editor-fold defaultstate="collapsed" desc="Get value"> public static int get(DBAccess db, String name, int defaultValue) { String value = get(db, name, (String) null); return value != null ? Integer.parseInt(value) : defaultValue; } public static String get(DBAccess db, String name, String defaultValue) { ResultSet rs = db.execute(db.prepare("SELECT value FROM " + TABLE + " WHERE name = ?;").bind(name)); for (Row r : rs) { return r.getString(0); } return defaultValue; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Set value"> public static void set(DBAccess db, String name, int value) { set(db, name, "" + value); } public static ResultSet set(DBAccess db, String name, String value) { return db.execute(db.prepare("INSERT INTO " + TABLE + " ( name, value ) VALUES ( ?, ? );").bind(name, value)); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Table creation"> public static void prepareTable(DBAccess db) { TableCreation.checkTable(db, new TableIncrementalDefinition() { @Override public String getTableDefName() { return TABLE; } @Override public List<TableIncrementalDefinition.TableChange> getTableDefChanges() { List<TableIncrementalDefinition.TableChange> list = new ArrayList<>(); list.add(new TableIncrementalDefinition.TableChange(1, "CREATE TABLE " + getTableDefName() + " ( name text PRIMARY KEY, value text );")); return list; } @Override public int getTableDefVersion() { return 1; } }); } // </editor-fold> }
package jade.util; import java.util.Vector; //#MIDP_EXCLUDE_BEGIN import java.util.EventObject; //#MIDP_EXCLUDE_END /** * This class represents a generic event carrying some information * (accessible in the form of <code>Object</code> parameters) and * provides support for synchronous processing through the * <code>waitUntilProcessed()</code> and <code>notifyProcessed()</code> * methods. * This class can be effectively used in combination with the * <code>InputQueue</code> class to support a synchronization between an * external therad (posting events in the <code>InputQueue</code>) * and the Agent thread (processing the events). * @see jade.util.InputQueue * @author Giovanni Caire - TILab */ public class Event //#MIDP_EXCLUDE_BEGIN extends EventObject //#MIDP_EXCLUDE_END { /*#MIDP_INCLUDE_BEGIN protected Object source; #MIDP_INCLUDE_END*/ /** The type of this event. */ protected int type; private Vector param = null; private boolean processed = false; private Object processingResult = null; /** Construct an <code>Event</code> of a given type produced by the indicated source @param type The type of the event @param source The source that generated the event */ public Event(int type, Object source) { //#MIDP_EXCLUDE_BEGIN super(source); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN this.source = source; #MIDP_INCLUDE_END*/ this.type = type; } /** Construct an <code>Event</code> of a given type produced by the indicated source and carrying a given information. @param type The type of the event @param source The source that generated the event @param info The information associated to the event. This value is handled as the first parameter of the event and can be accessed using the <code>getParameter(0)</code> method */ public Event(int type, Object source, Object info) { this(type, source); addParameter(info); } /*#MIDP_INCLUDE_BEGIN public Object getSource() { return source; } #MIDP_INCLUDE_END*/ /** Retrieve the type of this event. @return the type of this <code>Event</code> object */ public int getType() { return type; } /** Add a parameter to this <code>Event</code> object @param obj The parameter to be added */ public void addParameter(Object obj) { if (param == null) { param = new Vector(); } param.addElement(obj); } /** Retrieve an element of the event parameter list. @param index The index of the parameter to retrieve. @return the index-th parameter of this <code>Event</code> object. */ public Object getParameter(int index) { if (param == null) { throw new IndexOutOfBoundsException(); } else { return param.elementAt(index); } } /** Blocks the calling thread until the <code>notifyProcessed()</code> method is called. @return the result of the processing of this <code>Event</code> object as set by the <code>notifyProcessed()</code> method. */ public synchronized Object waitUntilProcessed() throws InterruptedException { while (!processed) { wait(); } return processingResult; } /** Wakes up threads waiting for the processing of this <code>Event</code> object within the <code>waitUntilProcessed()</code> method. @param result The result of the processing. This value is passed to the waked threads as the result of the <code>waitUntilProcessed()</code> method. */ public synchronized void notifyProcessed(Object result) { if (!processed) { processingResult = result; processed = true; notifyAll(); } } /** Reset the status of this <code>Event</code> */ public synchronized void reset() { processed = false; processingResult = null; if (param != null) { param.removeAllElements(); } } //#MIDP_EXCLUDE_BEGIN /** Reset the status of this <code>Event</code> @deprecated Use <code>reset()</code> instead */ public void resetProcessed() { reset(); } //#MIDP_EXCLUDE_END }
package main; import grid.GridAndGoals; import grid.GridGraph; import grid.ReachableNodes; import grid.StartGoalPoints; import java.awt.Color; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import main.graphgeneration.DefaultGenerator; import main.utility.Utility; import uiandio.FileIO; import uiandio.GraphImporter; import algorithms.AStar; import algorithms.Anya; import algorithms.BasicThetaStar; import algorithms.JumpPointSearch; import algorithms.StrictVisibilityGraphAlgorithm; import algorithms.StrictVisibilityGraphAlgorithmV2; import algorithms.datatypes.Point; import algorithms.datatypes.SnapshotItem; import algorithms.sparsevgs.LineOfSightScanner; import algorithms.strictthetastar.RecursiveStrictThetaStar; import algorithms.strictthetastar.StrictThetaStar; import algorithms.visibilitygraph.VisibilityGraph; import draw.DrawCanvas; import draw.GridLineSet; import draw.GridObjects; import draw.GridPointSet; public class Experiment { public static void run() { // testVisibilityGraphSize(); // testAbilityToFindGoal(); // findStrictThetaStarIssues(); // findUpperBound(); // testAlgorithmOptimality(); //testAgainstReferenceAlgorithm(); //countTautPaths(); // other(); testLOSScan(); } /** * Custom code for experiments. */ public static void other() { // This is how to generate test data for the grid. (Use the VisibilityGraph algorithm to generate optimal path lengths) // ArrayList<Point> points = ReachableNodes.computeReachable(gridGraph, 5, 5); // System.out.println(points.size()); // generateRandomTestDataAndPrint(gridGraph); //This is how to conduct a running time / path length test for tha algorithm: // TestResult test1 = testAlgorithm(gridGraph, sx, sy, ex, ey, 1, 1); // System.out.println(test1); // TestResult test2 = testAlgorithm(gridGraph, sx, sy, ex, ey, 30, 25); // System.out.println(test2); } /** * Generates and prints out random test data for the gridGraph in question. <br> * Note: the algorithm used is the one specified in the algoFunction. * Use setDefaultAlgoFunction to choose the algorithm. * @param gridGraph the grid to test. */ private static void generateRandomTestDataAndPrint(GridGraph gridGraph) { AlgoFunction algo = AnyAnglePathfinding.setDefaultAlgoFunction(); ArrayList<Point> points = ReachableNodes.computeReachable(gridGraph, 5, 5); LinkedList<Integer> startX = new LinkedList<>(); LinkedList<Integer> startY = new LinkedList<>(); LinkedList<Integer> endX = new LinkedList<>(); LinkedList<Integer> endY = new LinkedList<>(); LinkedList<Double> length = new LinkedList<>(); int size = points.size(); System.out.println("Points: " + size); for (int i=0; i<100; i++) { Random random = new Random(); int first = random.nextInt(size); int last = random.nextInt(size-1); if (last == first) last = size-1; // prevent first and last from being the same Point s = points.get(first); Point f = points.get(last); int[][] path = Utility.generatePath(algo, gridGraph, s.x, s.y, f.x, f.y); if (path.length >= 2) { double len = Utility.computePathLength(gridGraph, path); startX.offer(s.x); startY.offer(s.y); endX.offer(f.x); endY.offer(f.y); length.offer(len); } if (i%10 == 0) System.out.println("Computed: " + i); } System.out.println(startX); System.out.println(startY); System.out.println(endX); System.out.println(endY); System.out.println(length); } /** * Returns true iff there is a path from the start to the end. Uses the current algorithm to check.<br> * Use setDefaultAlgoFunction to choose the algorithm. */ private static boolean hasSolution(AlgoFunction algo, GridGraph gridGraph, StartGoalPoints p) { int[][] path = Utility.generatePath(algo, gridGraph, p.sx, p.sy, p.ex, p.ey); return path.length > 1; } private static void testLOSScan() { GridAndGoals gridAndGoals = AnyAnglePathfinding.loadMaze(); GridGraph gridGraph = gridAndGoals.gridGraph; ArrayList<GridObjects> gridObjectsList = new ArrayList<>(); GridLineSet gridLineSet = new GridLineSet();; GridPointSet gridPointSet = new GridPointSet(); int dx, dy; Random rand = new Random(); { int sx = rand.nextInt(gridGraph.sizeX+1); int sy = rand.nextInt(gridGraph.sizeY+1); sx = gridAndGoals.startGoalPoints.sx; sy = gridAndGoals.startGoalPoints.sy; sx = 24; sy = 24; dx = -1; dy = 2; LineOfSightScanner losScanner = new LineOfSightScanner(gridGraph); try { // Expected running time: 500x500, blocked ratio 25 ==> 0.07ms to 0.1ms per iteration. int iterations = 30000; long start = System.nanoTime(); for (int i=0;i<iterations;++i) { //losScanner.computeAllVisibleTautSuccessors(rand.nextInt(gridGraph.sizeX+1), rand.nextInt(gridGraph.sizeY+1)); //losScanner.clearSnapshots(); } long end = System.nanoTime(); double totalTime = (end-start)/1000000.; // convert to milliseconds System.out.println("Total Time: " + totalTime); System.out.println("Per iteration time: " + (totalTime/iterations)); //losScanner.computeAllVisibleTwoWayTautSuccessors(sx, sy); //losScanner.computeAllVisibleTautSuccessors(sx, sy); losScanner.computeAllVisibleIncrementalTautSuccessors(sx, sy, dx, dy); } catch (Exception e) { e.printStackTrace(); } for (int i=0;i<losScanner.nSuccessors;++i) { int x = losScanner.successorsX[i]; int y = losScanner.successorsY[i]; gridLineSet.addLine(sx, sy, x,y, Color.GREEN); gridPointSet.addPoint(x, y, Color.RED); } //gridLineSet = generateRandomTestLines(gridGraph, 10); gridPointSet.addPoint(sx, sy, Color.BLUE); gridObjectsList.add(new GridObjects(gridLineSet, gridPointSet)); for (List<SnapshotItem> l : LineOfSightScanner.snapshotList) { gridObjectsList.add(GridObjects.create(l)); } } DrawCanvas drawCanvas = new DrawCanvas(gridGraph, gridLineSet); Visualisation.setupMainFrame(drawCanvas, gridObjectsList); } /** * Generates random lines on the map. Used to test whether the line-of-sight * algorithm is correct. Returns a gridLineSet containing all the test lines. */ private static GridLineSet generateRandomTestLines(GridGraph gridGraph, int amount) { GridLineSet gridLineSet = new GridLineSet(); Random rand = new Random(); for (int i=0; i<amount; i++) { int x1 = rand.nextInt(gridGraph.sizeX); int y1 = rand.nextInt(gridGraph.sizeY); int x2 = rand.nextInt(gridGraph.sizeX); int y2 = rand.nextInt(gridGraph.sizeY); Experiment.testAndAddLine(x1,y1,x2,y2,gridGraph,gridLineSet); } return gridLineSet; } /** * Tests a set of coordinates for line-of-sight. Adds a green line to the * gridLineSet if there is line-of-sight between (x1,y1) and (x2,y2). * Adds a red line otherwise. */ private static void testAndAddLine(int x1, int y1, int x2, int y2, GridGraph gridGraph, GridLineSet gridLineSet) { if (gridGraph.lineOfSight(x1, y1, x2, y2)) { gridLineSet.addLine(x1, y1, x2, y2, Color.GREEN); } else { gridLineSet.addLine(x1, y1, x2, y2, Color.RED); } } private static void testAgainstReferenceAlgorithm() { AnyAnglePathfinding.setDefaultAlgoFunction(); AlgoFunction currentAlgo = AnyAnglePathfinding.setDefaultAlgoFunction(); AlgoFunction referenceAlgo = AStar::new; Random seedRand = new Random(3); int initial = seedRand.nextInt(); for (int i=0; i<500000; i++) { int sizeX = seedRand.nextInt(70) + 10; int sizeY = seedRand.nextInt(70) + 10; int seed = i+initial; int ratio = seedRand.nextInt(40) + 5; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnlyOld(seed, sizeX, sizeY, ratio); int[][] path = Utility.generatePath(referenceAlgo, gridGraph, sx, sy, ex, ey); double referencePathLength = Utility.computePathLength(gridGraph, path); boolean referenceValid = (referencePathLength > 0.00001f); path = Utility.generatePath(currentAlgo, gridGraph, sx, sy, ex, ey); double algoPathLength = Utility.computePathLength(gridGraph, path); boolean algoValid = (referencePathLength > 0.00001f); if (referenceValid != algoValid) { System.out.println("============"); System.out.println("Validity Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Reference: " + referenceValid + " , Current: " + algoValid); System.out.println("============"); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { if (Math.abs(algoPathLength - referencePathLength) > 0.0001) { System.out.println("============"); System.out.println("Path Length Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Reference: " + referencePathLength + " , Current: " + algoPathLength); System.out.println("============"); throw new UnsupportedOperationException("DISCREPANCY!!"); } if (i%1000 == 0) System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); } } } /** * Tests random generated maps of various sizes and obstacle densities for * the size of the visibility graphs.<br> * The results are output to the file VisibilityGraphSizes.txt. */ private static void testVisibilityGraphSize() { FileIO fileIO = new FileIO(AnyAnglePathfinding.PATH_TESTDATA + "VisibilityGraphSizes.txt"); Random seedGenerator = new Random(); fileIO.writeRow("Seed", "Size", "%Blocked", "Vertices", "Edges (Directed)"); for (int i=0; i<30; i++) { for (int r=0; r<3; r++) { int currentRatio = (r == 0 ? 7 : (r == 1 ? 15 : 50)); int currentSize = 10 + i*10; int currentSeed = seedGenerator.nextInt(); GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(currentSeed, currentSize, currentSize, currentRatio, 0, 0, currentSize, currentSize); VisibilityGraph vGraph = new VisibilityGraph(gridGraph, 0, 0, currentSize, currentSize); vGraph.initialise(); String seedString = currentSeed + ""; String sizeString = currentSize + ""; String ratioString = gridGraph.getPercentageBlocked()*100f + ""; String verticesString = vGraph.size() + ""; String edgesString = vGraph.computeSumDegrees() + ""; fileIO.writeRow(seedString, sizeString, ratioString, verticesString, edgesString); fileIO.flush(); } } fileIO.close(); } private static void findUpperBound() { System.out.println("Strict Theta Star"); AlgoFunction testAlgo = (gridGraph, sx, sy, ex, ey) -> new RecursiveStrictThetaStar(gridGraph, sx, sy, ex, ey); AlgoFunction optimalAlgo = (gridGraph, sx, sy, ex, ey) -> new StrictVisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); double upperBound = 1.5; double maxRatio = 1; int wins = 0; int ties = 0; Random seedRand = new Random(-2814121L); long initial = seedRand.nextLong(); for (int i=0; i>=0; i++) { int sizeX = seedRand.nextInt(30 + (int)(Math.sqrt(i))) + 1; int sizeY = seedRand.nextInt(10 + (int)(Math.sqrt(i))) + 1; sizeX = seedRand.nextInt(50) + 1; sizeY = seedRand.nextInt(30) + 1; long seed = i+initial; int ratio = seedRand.nextInt(60) + 1; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); //GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); GridGraph gridGraph = DefaultGenerator.generateSeededTrueRandomGraphOnly(seed, sizeX, sizeY, ratio); //gridGraph = GraphImporter.importGraphFromFile("custommaze4.txt"); //sx = 0; sy=0;ex=10+i;ey=2; //if (ex > 22) break; int[][] path = Utility.generatePath(testAlgo, gridGraph, sx, sy, ex, ey); double testPathLength = Utility.computePathLength(gridGraph, path); path = Utility.generatePath(optimalAlgo, gridGraph, sx, sy, ex, ey); double optimalPathLength = Utility.computePathLength(gridGraph, path); if (testPathLength > optimalPathLength*upperBound) { System.out.println("============"); System.out.println("Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Test: " + testPathLength + " , Optimal: " + optimalPathLength); System.out.println("Ratio: " + (testPathLength/optimalPathLength)); System.out.println("============"); System.out.println("WINS: " + wins + ", TIES: " + ties); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { //System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); double lengthRatio = (double)testPathLength/optimalPathLength; if (lengthRatio > maxRatio) { //System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Test: " + testPathLength + " , Optimal: " + optimalPathLength); System.out.println("Ratio: " + (testPathLength/optimalPathLength)); maxRatio = lengthRatio; System.out.println(maxRatio); } } } //System.out.println(maxRatio); } private static void findStrictThetaStarIssues() { // AlgoFunction basicThetaStar = (gridGraph, sx, sy, ex, ey) -> new BasicThetaStar(gridGraph, sx, sy, ex, ey);; // AlgoFunction strictThetaStar = (gridGraph, sx, sy, ex, ey) -> new StrictThetaStarV1(gridGraph, sx, sy, ex, ey); AlgoFunction basicThetaStar = (gridGraph, sx, sy, ex, ey) -> RecursiveStrictThetaStar.setBuffer(gridGraph, sx, sy, ex, ey, 0.4f); AlgoFunction strictThetaStar = (gridGraph, sx, sy, ex, ey) -> RecursiveStrictThetaStar.setBuffer(gridGraph, sx, sy, ex, ey, 0.2f); int wins = 0; int ties = 0; Random seedRand = new Random(192213); int initial = seedRand.nextInt(); for (int i=0; i<500000; i++) { int sizeX = seedRand.nextInt(5) + 8; int sizeY = seedRand.nextInt(5) + 8; int seed = i+initial; int ratio = seedRand.nextInt(40) + 5; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); int[][] path = Utility.generatePath(basicThetaStar, gridGraph, sx, sy, ex, ey); double basicPathLength = Utility.computePathLength(gridGraph, path); path = Utility.generatePath(strictThetaStar, gridGraph, sx, sy, ex, ey); double strictPathLength = Utility.computePathLength(gridGraph, path); if (basicPathLength < strictPathLength-0.01f) { System.out.println("============"); System.out.println("Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Basic: " + basicPathLength + " , Strict: " + strictPathLength); System.out.println("============"); System.out.println("WINS: " + wins + ", TIES: " + ties); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); if (strictPathLength < basicPathLength - 0.01f) { wins += 1; } else { ties += 1; } } } } private static void testAlgorithmOptimality() { //AlgoFunction rVGA = (gridGraph, sx, sy, ex, ey) -> new RestrictedVisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); //AlgoFunction rVGA = (gridGraph, sx, sy, ex, ey) -> new VisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); //AlgoFunction rVGA = (gridGraph, sx, sy, ex, ey) -> new StrictVisibilityGraphAlgorithm(gridGraph, sx, sy, ex, ey); AlgoFunction testAlgo = Anya::new; AlgoFunction refAlgo = StrictVisibilityGraphAlgorithmV2::new; //AlgoFunction VGA = (gridGraph, sx, sy, ex, ey) -> VisibilityGraphAlgorithm.graphReuseNoHeuristic(gridGraph, sx, sy, ex, ey); //printSeed = false; // keep this commented out. Random seedRand = new Random(-2059321351); int initial = seedRand.nextInt(); for (int i=0; i<50000000; i++) { int sizeX = seedRand.nextInt(300) + 10; int sizeY = seedRand.nextInt(300) + 10; int seed = i+initial; int ratio = seedRand.nextInt(50) + 10; int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); double restPathLength = 0, normalPathLength = 0; try { GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); //for (int iii=0;iii<100;++iii) Utility.generatePath(testAlgo, gridGraph, seedRand.nextInt(sizeX+1),seedRand.nextInt(sizeY+1),seedRand.nextInt(sizeX+1),seedRand.nextInt(sizeY+1)); int[][] path = Utility.generatePath(testAlgo, gridGraph, sx, sy, ex, ey); path = Utility.removeDuplicatesInPath(path); restPathLength = Utility.computePathLength(gridGraph, path); path = Utility.generatePath(refAlgo, gridGraph, sx, sy, ex, ey); path = Utility.removeDuplicatesInPath(path); normalPathLength = Utility.computePathLength(gridGraph, path); }catch (Exception e) { e.printStackTrace(); System.out.println("EXCEPTION OCCURRED!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); throw new UnsupportedOperationException("DISCREPANCY!!"); } if (Math.abs(restPathLength - normalPathLength) > 0.000001f) { System.out.println("============"); System.out.println("Discrepancy Discovered!"); System.out.println("Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Start = " + sx + "," + sy + " End = " + ex + "," + ey); System.out.println("Actual: " + restPathLength + " , Expected: " + normalPathLength); System.out.println(restPathLength / normalPathLength); System.out.println("============"); throw new UnsupportedOperationException("DISCREPANCY!!"); } else { if (i%10000 == 9999) { System.out.println("Count: " + (i+1)); System.out.println("OK: Seed = " + seed +" , Ratio = " + ratio + " , Size: x=" + sizeX + " y=" + sizeY); System.out.println("Actual: " + restPathLength + " , Expected: " + normalPathLength); } } } } private static boolean testTautness(GridGraph gridGraph, AlgoFunction algo, int sx, int sy, int ex, int ey) { int[][] path = Utility.generatePath(algo, gridGraph, sx, sy, ex, ey); path = Utility.removeDuplicatesInPath(path); return Utility.isPathTaut(gridGraph, path); } private static boolean hasSolution(GridGraph gridGraph, AlgoFunction algo, int sx, int sy, int ex, int ey) { int[][] path = Utility.generatePath(algo, gridGraph, sx, sy, ex, ey); return path.length > 1; } private static void countTautPaths() { int nTaut1=0;int nTaut2=0; int nTaut3=0; AlgoFunction hasPathChecker = JumpPointSearch::new; AlgoFunction algo3 = BasicThetaStar::new; AlgoFunction algo2 = StrictThetaStar::new; AlgoFunction algo1 = RecursiveStrictThetaStar::new; //printSeed = false; // keep this commented out. int pathsPerGraph = 100; int nIterations = 100000; int nPaths = 0; String[] maps = { "obst10_random512-10-0", "obst10_random512-10-1", "obst10_random512-10-2", "obst10_random512-10-3", "obst10_random512-10-4", "obst10_random512-10-5", "obst10_random512-10-6", "obst10_random512-10-7", "obst10_random512-10-8", "obst10_random512-10-9", "obst40_random512-40-0", "obst40_random512-40-1", "obst40_random512-40-2", "obst40_random512-40-3", "obst40_random512-40-4", "obst40_random512-40-5", "obst40_random512-40-6", "obst40_random512-40-7", "obst40_random512-40-8", "obst40_random512-40-9" }; nIterations = maps.length; System.out.println(maps.length); Random seedRand = new Random(-14); int initial = seedRand.nextInt(); for (int i=0;i<nIterations;++i) { String map = maps[i]; System.out.println("Map: " + map); GridGraph gridGraph = GraphImporter.loadStoredMaze(map); int sizeX = gridGraph.sizeX; int sizeY = gridGraph.sizeY; /*int sizeX = seedRand.nextInt(20) + 300; int sizeY = seedRand.nextInt(20) + 300; int seed = i+initial; int ratio = seedRand.nextInt(30) + 5; GridGraph gridGraph = DefaultGenerator.generateSeededGraphOnly(seed, sizeX, sizeY, ratio); System.out.println("Ratio: " + ratio);*/ for (int j=0;j<pathsPerGraph;++j) { int max = (sizeX+1)*(sizeY+1); int p1 = seedRand.nextInt(max); int p2 = seedRand.nextInt(max-1); if (p2 == p1) { p2 = max-1; } int sx = p1%(sizeX+1); int sy = p1/(sizeX+1); int ex = p2%(sizeX+1); int ey = p2/(sizeX+1); if (hasSolution(gridGraph, hasPathChecker, sx, sy, ex, ey)) { if (testTautness(gridGraph, algo1, sx,sy,ex,ey)) nTaut1++; if (testTautness(gridGraph, algo2, sx,sy,ex,ey)) nTaut2++; if (testTautness(gridGraph, algo3, sx,sy,ex,ey)) nTaut3++; nPaths++; } else { j } } System.out.println("Total = " + nPaths); System.out.println("1: " + ((float)nTaut1/nPaths)); System.out.println("2: " + ((float)nTaut2/nPaths)); System.out.println("3: " + ((float)nTaut3/nPaths)); } } }
package com.openxc.remote; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import com.openxc.DataPipeline; import com.openxc.interfaces.VehicleInterface; import com.openxc.interfaces.VehicleInterfaceException; import com.openxc.interfaces.VehicleInterfaceFactory; import com.openxc.interfaces.VehicleInterfaceManagerUtils; import com.openxc.interfaces.usb.UsbVehicleInterface; import com.openxc.sinks.RemoteCallbackSink; import com.openxc.sinks.VehicleDataSink; import com.openxc.sources.ApplicationSource; import com.openxc.sources.VehicleDataSource; /** * The VehicleService is the centralized source of all vehicle data. * * This server is intended to be a singleton on an Android device. All OpenXC * applciations funnel data to and from this service so they can share sources, * sinks and vehicle interfaces. * * Applications should not use this service directly, but should bind to the * in-process {@link com.openxc.VehicleManager} instead - that has an interface * that respects Measurement types. The interface used for the * VehicleService is purposefully primative as there are a small set of * objects that can be natively marshalled through an AIDL interface. * * By default, the {@link UsbVehicleInterface} is activated as a * {@link VehicleInterface}. Other vehicle interfaces can be activated with the * {@link #addVehicleInterface(Class, String)} method and they can removed with * {@link #removeVehicleInterface(Class)}. * * This service uses the same {@link com.openxc.DataPipeline} as the * {@link com.openxc.VehicleManager} to move data from sources to sinks, but it * the pipeline is not modifiable by the application as there is no good way to * pass running sources through the AIDL interface. The same style is used here * for clarity and in order to share code. */ public class VehicleService extends Service { private final static String TAG = "VehicleService"; private DataPipeline mPipeline = new DataPipeline(); private ApplicationSource mApplicationSource = new ApplicationSource(); private CopyOnWriteArrayList<VehicleInterface> mInterfaces = new CopyOnWriteArrayList<VehicleInterface>(); private RemoteCallbackSink mNotifier = new RemoteCallbackSink(); @Override public void onCreate() { super.onCreate(); Log.i(TAG, "Service starting"); } /** * Shut down any associated services when this service is about to die. * * This stops the data source (e.g. stops trace playback) and kills the * thread used for notifying measurement listeners. */ @Override public void onDestroy() { Log.i(TAG, "Service being destroyed"); mPipeline.stop(); } /** * Initialize the service and data source when a client binds to us. */ @Override public IBinder onBind(Intent intent) { Log.i(TAG, "Service binding in response to " + intent); initializeDefaultSources(); initializeDefaultSinks(mPipeline); return mBinder; } private void initializeDefaultSinks(DataPipeline pipeline) { pipeline.addSink(mNotifier); } private void initializeDefaultSources() { mPipeline.addSource(mApplicationSource); addVehicleInterface(UsbVehicleInterface.class); } private final VehicleServiceInterface.Stub mBinder = new VehicleServiceInterface.Stub() { public RawMeasurement get(String measurementId) { return mPipeline.get(measurementId); } public boolean send(RawMeasurement command) { return VehicleInterfaceManagerUtils.send(mInterfaces, command); } public void receive(RawMeasurement measurement) { mApplicationSource.handleMessage(measurement); } public void register(VehicleServiceListener listener) { Log.i(TAG, "Adding listener " + listener); mNotifier.register(listener); } public void unregister(VehicleServiceListener listener) { Log.i(TAG, "Removing listener " + listener); mNotifier.unregister(listener); } public int getMessageCount() { return VehicleService.this.mPipeline.getMessageCount(); } public void addVehicleInterface(String interfaceName, String resource) { VehicleService.this.addVehicleInterface( interfaceName, resource); } public void removeVehicleInterface(String interfaceName) { VehicleService.this.removeVehicleInterface(interfaceName); } public List<String> getSourceSummaries() { ArrayList<String> sources = new ArrayList<String>(); for(VehicleDataSource source : mPipeline.getSources()) { sources.add(source.toString()); } return sources; } public List<String> getSinkSummaries() { ArrayList<String> sinks = new ArrayList<String>(); for(VehicleDataSink sink : mPipeline.getSinks()) { sinks.add(sink.toString()); } return sinks; } }; private void addVehicleInterface( Class<? extends VehicleInterface> interfaceType) { addVehicleInterface(interfaceType, null); } private void addVehicleInterface( Class<? extends VehicleInterface> interfaceType, String resource) { VehicleInterface vehicleInterface = findActiveVehicleInterface(interfaceType); if(vehicleInterface == null || !vehicleInterface.sameResource(resource)) { if(vehicleInterface != null) { removeVehicleInterface(vehicleInterface); } try { vehicleInterface = VehicleInterfaceFactory.build( VehicleService.this, interfaceType, resource); } catch(VehicleInterfaceException e) { Log.w(TAG, "Unable to add vehicle interface", e); return; } mInterfaces.add(vehicleInterface); mPipeline.addSource(vehicleInterface); } else { Log.d(TAG, "Vehicle interface " + vehicleInterface + " already running"); } Log.i(TAG, "Added vehicle interface " + vehicleInterface); } private void addVehicleInterface(String interfaceName, String resource) { try { addVehicleInterface( VehicleInterfaceFactory.findClass(interfaceName), resource); } catch(VehicleInterfaceException e) { Log.w(TAG, "Unable to add vehicle interface", e); } } private void removeVehicleInterface(String interfaceName) { removeVehicleInterface(findActiveVehicleInterface(interfaceName)); } private void removeVehicleInterface(VehicleInterface vehicleInterface) { if(vehicleInterface != null) { vehicleInterface.stop(); mInterfaces.remove(vehicleInterface); mPipeline.removeSource(vehicleInterface); } } private VehicleInterface findActiveVehicleInterface( Class<? extends VehicleInterface> interfaceType) { for(VehicleInterface vehicleInterface : mInterfaces) { if(vehicleInterface.getClass().equals(interfaceType)) { return vehicleInterface; } } return null; } private VehicleInterface findActiveVehicleInterface(String interfaceName) { try { return findActiveVehicleInterface( VehicleInterfaceFactory.findClass(interfaceName)); } catch(VehicleInterfaceException e) { return null; } } }
package aes.motive.core.asm; import java.util.ConcurrentModificationException; import java.util.LinkedList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.tileentity.TileEntityRenderer; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import aes.motive.tileentity.TileEntityMoverBase; import aes.utils.Obfuscation; import aes.utils.PrivateFieldAccess; import aes.utils.Vector2i; import aes.utils.Vector3i; public class RenderHook { public static RenderHook INSTANCE = new RenderHook(); public static boolean worldRendererContainsMovingBlocks(WorldRenderer worldrenderer) { worldrenderer.worldObj.theProfiler.startSection("checkContainsMoving"); for (final TileEntityMoverBase tileEntityMoverBase : TileEntityMoverBase.getMovers(Minecraft.getMinecraft().theWorld).values()) { if (tileEntityMoverBase.moving && tileEntityMoverBase.affectedChunks.contains(new Vector2i(worldrenderer.posX >> 4, worldrenderer.posZ >> 4))) // if(WorldUtils.containsChunk(tileEntityMoverBase.getAffectedBlocks(), // chunkLocation)) { worldrenderer.worldObj.theProfiler.endSection(); return false; } } worldrenderer.worldObj.theProfiler.endSection(); return false; } // public Map<Vector3i, TileEntityMoverBase> movers = new HashMap<Vector3i, // TileEntityMoverBase>(); Block modifyingBlock = null; TileEntityMoverBase modifyingMover = null; public List<Tessellator> movedTessellators = null; private RenderHook() { } public MovingObjectPosition collisionRayTrace(World par1World, int par2, int par3, int par4, Vec3 par5Vec3, Vec3 par6Vec3, boolean par3a, boolean par4a, int k1, int l1) { int blockId = par1World.getBlockId(par2, par3, par4); if (blockId != 0) { final Block block = Block.blocksList[blockId]; if (block != null && (!par4a || block == null || block.getCollisionBoundingBoxFromPool(par1World, par2, par3, par4) != null) && k1 > 0 && block.canCollideCheck(l1, par3a)) { final MovingObjectPosition result = block.collisionRayTrace(par1World, par2, par3, par4, par5Vec3, par6Vec3); if (result != null) return result; } } final int x = par2; final int y = par3; final int z = par4; for (final ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { par2 = x + direction.offsetX; par3 = y + direction.offsetY; par4 = z + direction.offsetZ; blockId = par1World.getBlockId(par2, par3, par4); if (blockId != 0) { final Block block = Block.blocksList[blockId]; if (block != null) { if (block.canCollideCheck(par1World.getBlockMetadata(par2, par3, par4), par3a)) { final MovingObjectPosition result = block.collisionRayTrace(par1World, par2, par3, par4, par5Vec3, par6Vec3); if (result != null) return result; } } } } return null; } public TileEntityMoverBase getMoverMoving(World world, int x, int y, int z) { Minecraft.getMinecraft().mcProfiler.startSection("getMoverMoving"); try { // if(false) { final Vector3i coord = new Vector3i(x, y, z); for (final TileEntityMoverBase mover : TileEntityMoverBase.getMovers(world).values()) { if (mover.moving && mover.getConnectedBlocks().blocks.contains(coord)) // return null; return mover; } } return null; } catch (final ConcurrentModificationException e) { return getMoverMoving(world, x, y, z); } finally { Minecraft.getMinecraft().mcProfiler.endSection(); } } public boolean isBlockMoving(int par1, int par2, int par3) { // return false; return getMoverMoving(Minecraft.getMinecraft().theWorld, par1, par2, par3) != null; } public void modifyMovingBlockBounds(World world, int x, int y, int z) { final int blockId = world.getBlockId(x, y, z); final Block block = Block.blocksList[blockId]; final TileEntityMoverBase mover = getMoverMoving(Minecraft.getMinecraft().theWorld, x, y, z); if (mover != null) { this.modifyingBlock = block; this.modifyingMover = mover; block.setBlockBounds((float) block.getBlockBoundsMinX() + mover.moved.x, (float) block.getBlockBoundsMinY() + mover.moved.y, (float) block.getBlockBoundsMinZ() + mover.moved.z, (float) block.getBlockBoundsMaxX() + mover.moved.x, (float) block.getBlockBoundsMaxY() + mover.moved.y, (float) block.getBlockBoundsMaxZ() + mover.moved.z); } } public void modifyMovingTesselator(int x, int y, int z) { final TileEntityMoverBase mover = getMoverMoving(Minecraft.getMinecraft().theWorld, x, y, z); if (mover != null) { this.modifyingMover = mover; this.movedTessellators = new LinkedList<Tessellator>(); if (!this.movedTessellators.contains(Tessellator.instance)) { this.movedTessellators.add(Tessellator.instance); Tessellator.instance.addTranslation(mover.moved.x, mover.moved.y, mover.moved.z); } return; } this.movedTessellators = null; } public MovingObjectPosition rayTraceBlocks_do_do(World world, Vec3 from, Vec3 to, boolean includeLiquids, boolean includeEmpty) { if (!Double.isNaN(from.xCoord) && !Double.isNaN(from.yCoord) && !Double.isNaN(from.zCoord)) { if (!Double.isNaN(to.xCoord) && !Double.isNaN(to.yCoord) && !Double.isNaN(to.zCoord)) { final int xFrom = MathHelper.floor_double(to.xCoord); final int yFrom = MathHelper.floor_double(to.yCoord); final int zFrom = MathHelper.floor_double(to.zCoord); int xTo = MathHelper.floor_double(from.xCoord); int yTo = MathHelper.floor_double(from.yCoord); int zTo = MathHelper.floor_double(from.zCoord); int k1 = world.getBlockId(xTo, yTo, zTo); final int l1 = world.getBlockMetadata(xTo, yTo, zTo); MovingObjectPosition movingobjectposition = collisionRayTrace(world, xTo, yTo, zTo, from, to, includeLiquids, includeEmpty, k1, l1); if (movingobjectposition != null) return movingobjectposition; k1 = 200; while (k1 if (Double.isNaN(from.xCoord) || Double.isNaN(from.yCoord) || Double.isNaN(from.zCoord)) return null; if (xTo == xFrom && yTo == yFrom && zTo == zFrom) return null; boolean xVarying = true; boolean yVarying = true; boolean zVarying = true; double nextX = 999.0D; double nextY = 999.0D; double nextZ = 999.0D; if (xFrom > xTo) { nextX = xTo + 1.0D; } else if (xFrom < xTo) { nextX = xTo + 0.0D; } else { xVarying = false; } if (yFrom > yTo) { nextY = yTo + 1.0D; } else if (yFrom < yTo) { nextY = yTo + 0.0D; } else { yVarying = false; } if (zFrom > zTo) { nextZ = zTo + 1.0D; } else if (zFrom < zTo) { nextZ = zTo + 0.0D; } else { zVarying = false; } double d3 = 999.0D; double d4 = 999.0D; double d5 = 999.0D; final double d6 = to.xCoord - from.xCoord; final double d7 = to.yCoord - from.yCoord; final double d8 = to.zCoord - from.zCoord; if (xVarying) { d3 = (nextX - from.xCoord) / d6; } if (yVarying) { d4 = (nextY - from.yCoord) / d7; } if (zVarying) { d5 = (nextZ - from.zCoord) / d8; } byte b0; if (d3 < d4 && d3 < d5) { if (xFrom > xTo) { b0 = 4; } else { b0 = 5; } from.xCoord = nextX; from.yCoord += d7 * d3; from.zCoord += d8 * d3; } else if (d4 < d5) { if (yFrom > yTo) { b0 = 0; } else { b0 = 1; } from.xCoord += d6 * d4; from.yCoord = nextY; from.zCoord += d8 * d4; } else { if (zFrom > zTo) { b0 = 2; } else { b0 = 3; } from.xCoord += d6 * d5; from.yCoord += d7 * d5; from.zCoord = nextZ; } final Vec3 vec32 = world.getWorldVec3Pool().getVecFromPool(from.xCoord, from.yCoord, from.zCoord); xTo = (int) (vec32.xCoord = MathHelper.floor_double(from.xCoord)); if (b0 == 5) { --xTo; ++vec32.xCoord; } yTo = (int) (vec32.yCoord = MathHelper.floor_double(from.yCoord)); if (b0 == 1) { --yTo; ++vec32.yCoord; } zTo = (int) (vec32.zCoord = MathHelper.floor_double(from.zCoord)); if (b0 == 3) { --zTo; ++vec32.zCoord; } movingobjectposition = collisionRayTrace(world, xTo, yTo, zTo, from, to, includeLiquids, includeEmpty, k1, l1); if (movingobjectposition != null) return movingobjectposition; } return null; } else return null; } else return null; } public void renderTileEntity(TileEntitySpecialRenderer renderer, TileEntity tileEntity, double x, double y, double z, float partialTickTime) { final TileEntityMoverBase blocks = getMoverMoving(Minecraft.getMinecraft().theWorld, (int) (x + TileEntityRenderer.staticPlayerX), (int) (y + TileEntityRenderer.staticPlayerY), (int) (z + TileEntityRenderer.staticPlayerZ)); if (blocks != null) { x += blocks.moved.x; y += blocks.moved.y; z += blocks.moved.z; } renderer.renderTileEntityAt(tileEntity, x, y, z, partialTickTime); } public void resetMovingBlockBounds(World world, int x, int y, int z) { final int blockId = world.getBlockId(x, y, z); final Block block = Block.blocksList[blockId]; if (this.modifyingBlock == block) { final TileEntityMoverBase mover = this.modifyingMover; block.setBlockBounds((float) block.getBlockBoundsMinX() - mover.moved.x, (float) block.getBlockBoundsMinY() - mover.moved.y, (float) block.getBlockBoundsMinZ() - mover.moved.z, (float) block.getBlockBoundsMaxX() - mover.moved.x, (float) block.getBlockBoundsMaxY() - mover.moved.y, (float) block.getBlockBoundsMaxZ() - mover.moved.z); this.modifyingBlock = null; this.modifyingMover = null; } } public void resetMovingTesselator() { if (this.movedTessellators != null) { for (final Tessellator movedTessellator : this.movedTessellators) { movedTessellator.addTranslation(-this.modifyingMover.moved.x, -this.modifyingMover.moved.y, -this.modifyingMover.moved.z); } } this.movedTessellators = null; } @SuppressWarnings("unchecked") public void updateWorldRendererTileEntities() { final RenderGlobal renderGlobal = Minecraft.getMinecraft().renderGlobal; renderGlobal.tileEntities.clear(); for (final WorldRenderer renderer : (WorldRenderer[]) PrivateFieldAccess.getValue(renderGlobal, Obfuscation.getSrgName("worldRenderers"))) { if (renderer != null && renderer.tileEntityRenderers != null) { renderGlobal.tileEntities.addAll(renderer.tileEntityRenderers); } } } }
package com.spoon.backgroundfileupload; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.util.Log; import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork; import com.sromku.simple.storage.SimpleStorage; import com.sromku.simple.storage.Storage; import com.sromku.simple.storage.helpers.OrderType; import net.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.ServerResponse; import net.gotev.uploadservice.UploadInfo; import net.gotev.uploadservice.UploadNotificationConfig; import net.gotev.uploadservice.UploadService; import net.gotev.uploadservice.UploadServiceBroadcastReceiver; import net.gotev.uploadservice.okhttp.OkHttpStack; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class FileTransferBackground extends CordovaPlugin { private CallbackContext uploadCallback; private boolean isNetworkAvailable = false; private Long lastProgressTimestamp = 0L; private boolean ready = false; private Disposable networkObservable; private UploadServiceBroadcastReceiver broadcastReceiver = new UploadServiceBroadcastReceiver() { @Override public void onProgress(Context context, UploadInfo uploadInfo) { Long currentTimestamp = System.currentTimeMillis() / 1000; if (currentTimestamp - lastProgressTimestamp >= 1) { lastProgressTimestamp = currentTimestamp; JSONObject objResult = new JSONObject(new HashMap() {{ put("id", uploadInfo.getUploadId()); put("progress", uploadInfo.getProgressPercent()); put("state", "UPLOADING"); }}); sendCallback(objResult); } } @Override public void onError(final Context context, final UploadInfo uploadInfo, final ServerResponse serverResponse, final Exception exception) { logMessage("eventLabel:'upload failed' uploadId:'" + uploadInfo.getUploadId() + "' error:'" + exception.getMessage() + "'"); deletePendingUploadAndSendEvent(new JSONObject(new HashMap() {{ put("id", uploadInfo.getUploadId()); put("state", "FAILED"); put("error", "upload failed: " + exception != null ? exception.getMessage() : ""); put("errorCode", serverResponse != null ? serverResponse.getHttpCode() : 0); }})); } @Override public void onCompleted(Context context, UploadInfo uploadInfo, ServerResponse serverResponse) { logMessage("eventLabel:'upload completed' uploadId:'" + uploadInfo.getUploadId() + "' response:'" + serverResponse.getBodyAsString() + "'"); deletePendingUploadAndSendEvent(new JSONObject(new HashMap() {{ put("id", uploadInfo.getUploadId()); put("state", "UPLOADED"); put("serverResponse", serverResponse.getBodyAsString()); put("statusCode", serverResponse.getHttpCode()); }})); } @Override public void onCancelled(Context context, UploadInfo uploadInfo) { logMessage("eventLabel:'upload cancelled' uploadId:'" + uploadInfo.getUploadId() + "'"); deletePendingUploadAndSendEvent(new JSONObject(new HashMap() {{ put("id", uploadInfo.getUploadId()); put("state", "FAILED"); put("errorCode", -999); put("error", "upload cancelled"); }})); } }; public void createAndSendEvent(JSONObject obj) { UploadEvent event = UploadEvent.create(obj); sendCallback(event.dataRepresentation()); } public void sendCallback(JSONObject obj) { /* we check the webview has not been destroyed*/ if (ready) { PluginResult result = new PluginResult(PluginResult.Status.OK, obj); result.setKeepCallback(true); uploadCallback.sendPluginResult(result); } } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if (action.equalsIgnoreCase("initManager")) { uploadCallback = callbackContext; this.initManager(args.get(0).toString()); } else if (action.equalsIgnoreCase("removeUpload")) { this.removeUpload(args.get(0).toString(), callbackContext); } else if (action.equalsIgnoreCase("acknowledgeEvent")) { this.acknowledgeEvent(args.getString(0), callbackContext); } else if (action.equalsIgnoreCase("startUpload")) { this.upload((JSONObject) args.get(0)); } return true; } private void initManager(String options) { if (this.ready) { logMessage("eventLabel:'initManager was called more than once'"); return; } this.ready = true; int parallelUploadsLimit = 1; try { JSONObject settings = new JSONObject(options); parallelUploadsLimit = settings.getInt("parallelUploadsLimit"); } catch (JSONException error) { logMessage("eventLabel:'could not read parallelUploadsLimit from config' error:'" + error.getMessage() + "'"); } UploadService.HTTP_STACK = new OkHttpStack(); UploadService.UPLOAD_POOL_SIZE = parallelUploadsLimit; UploadService.NAMESPACE = cordova.getContext().getPackageName(); cordova.getActivity().getApplicationContext().registerReceiver(broadcastReceiver, new IntentFilter(UploadService.NAMESPACE + ".uploadservice.broadcast.status")); networkObservable = ReactiveNetwork .observeNetworkConnectivity(cordova.getContext()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(connectivity -> { this.isNetworkAvailable = connectivity.state() == NetworkInfo.State.CONNECTED; if (this.isNetworkAvailable) { logMessage("eventLabel:'Network now available, restarting pending uploads'"); uploadPendingList(); } }); //mark v1 uploads as failed migrateOldUploads(); //broadcast all completed upload events for (UploadEvent event : UploadEvent.all()) { sendCallback(event.dataRepresentation()); } } private void migrateOldUploads() { Storage storage = SimpleStorage.getInternalStorage(this.cordova.getActivity().getApplicationContext()); String uploadDirectoryName = "FileTransferBackground"; if (storage.isDirectoryExists(uploadDirectoryName)) { for (String uploadId : getOldUploadIds()) { createAndSendEvent(new JSONObject(new HashMap() {{ put("id", uploadId); put("state", "FAILED"); put("errorCode", 0); put("error", "upload failed"); }})); } // remove all old uploads storage.deleteDirectory(uploadDirectoryName); } } private ArrayList<String> getOldUploadIds() { Storage storage = SimpleStorage.getInternalStorage(this.cordova.getActivity().getApplicationContext()); String uploadDirectoryName = "FileTransferBackground"; ArrayList<String> previousUploads = new ArrayList(); List<File> files = storage.getFiles(uploadDirectoryName, OrderType.DATE); for (File file : files) { if (file.getName().endsWith(".json")) { String content = storage.readTextFile(uploadDirectoryName, file.getName()); if (content != null) { try { previousUploads.add(new JSONObject(content).getString("id")); } catch (JSONException exception) { logMessage("eventLabel:'could not read old uploads' error:'" + exception.getMessage() + "'"); } } } } return previousUploads; } private void uploadPendingList() { List<PendingUpload> previousUploads = PendingUpload.all(); for (PendingUpload upload : previousUploads) { JSONObject obj = null; try { obj = new JSONObject(upload.data); } catch (JSONException exception) { logMessage("eventLabel:'could not parse pending upload' uploadId:'" + upload.uploadId + "' error:'" + exception.getMessage() + "'"); } if (obj != null) { this.upload(obj); } } } private void upload(JSONObject jsonPayload) { HashMap payload = null; try { payload = convertToHashMap(jsonPayload); } catch (JSONException error) { logMessage("eventLabel:'could not read id from payload' error:'" + error.getMessage() + "'"); } if (payload == null) return; String id = payload.get("id").toString(); if (UploadService.getTaskList().contains(id)) { logMessage("eventLabel:'upload is already being uploaded. ignoring re-upload request' uploadId:'" + id + "'"); return; } logMessage("eventLabel:'adding upload' uploadId:'" + id + "'"); PendingUpload.create(jsonPayload); if (isNetworkAvailable) { MultipartUploadRequest request = null; try { request = new MultipartUploadRequest(this.cordova.getActivity().getApplicationContext(), id, payload.get("serverUrl").toString()).addFileToUpload(payload.get("filePath").toString(), payload.get("fileKey").toString()).setMaxRetries(0); } catch (MalformedURLException error) { sendAddingUploadError(id, error); return; } catch (IllegalArgumentException error){ sendAddingUploadError(id, error); return; } catch (FileNotFoundException error) { sendAddingUploadError(id, error); return; } UploadNotificationConfig config = getNotificationConfiguration("uploading files"); request.setNotificationConfig(config); try { HashMap<String, Object> headers = convertToHashMap((JSONObject) payload.get("headers")); for (String key : headers.keySet()) { request.addHeader(key, headers.get(key).toString()); } } catch (JSONException exception) { logMessage("eventLabel:'could not parse request headers' uploadId:'" + id + "' error:'" + exception.getMessage() + "'"); sendAddingUploadError(id, exception); return; } try { HashMap<String, Object> parameters = convertToHashMap((JSONObject) payload.get("parameters")); for (String key : parameters.keySet()) { request.addParameter(key, parameters.get(key).toString()); } } catch (JSONException exception) { logMessage("eventLabel:'could not parse request parameters' uploadId:'" + id + "' error:'" + exception.getMessage() + "'"); sendAddingUploadError(id, exception); return; } request.startUpload(); } else { logMessage("eventLabel:'No network available, upload has been queued' uploadId:'" + id + "'"); } } private void sendAddingUploadError(String uploadId, Exception error) { deletePendingUploadAndSendEvent(new JSONObject(new HashMap() {{ put("id", uploadId); put("state", "FAILED"); put("errorCode", 0); put("error", error.getMessage()); }})); } public void deletePendingUploadAndSendEvent(JSONObject obj) { try { PendingUpload.remove(obj.getString("id")); } catch (JSONException error) { logMessage("eventLabel:'could not delete pending upload' error:'" + error.getMessage() + "'"); } createAndSendEvent(obj); } private UploadNotificationConfig getNotificationConfiguration(String title) { UploadNotificationConfig config = new UploadNotificationConfig(); config.getCompleted().autoClear = true; config.getCancelled().autoClear = true; config.getError().autoClear = true; config.setClearOnActionForAllStatuses(true); Intent intent = new Intent(cordova.getContext(), cordova.getActivity().getClass()); PendingIntent pendingIntent = PendingIntent.getActivity(cordova.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); config.setClickIntentForAllStatuses(pendingIntent); config.getProgress().title = title; return config; } private HashMap<String, Object> convertToHashMap(JSONObject jsonObject) throws JSONException { HashMap<String, Object> hashMap = new HashMap<>(); if (jsonObject != null) { Iterator<?> keys = jsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object value = jsonObject.get(key); hashMap.put(key, value); } } return hashMap; } private void logMessage(String message) { Log.d("CordovaBackgroundUpload", message); } private void removeUpload(String fileId, CallbackContext context) { PendingUpload.remove(fileId); UploadService.stopUpload(fileId); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); context.sendPluginResult(result); } private void acknowledgeEvent(String eventId, CallbackContext context) { String onlyNumbers = eventId.replaceAll("\\D+", ""); UploadEvent.destroy(Long.valueOf(onlyNumbers).longValue()); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); context.sendPluginResult(result); } public void onDestroy() { logMessage("eventLabel:'plugin onDestroy'"); ready = false; if (networkObservable != null) networkObservable.dispose(); // broadcastReceiver.unregister(cordova.getActivity().getApplicationContext()); } }
package com.example; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.apache.cordova.PluginResult.Status; import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import android.os.Bundle; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.os.StrictMode; import android.print.PageRange; import android.print.PrintAttributes; import android.print.PrintDocumentAdapter; import android.print.PrintDocumentInfo; import android.print.PrintManager; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.io.IOException; import android.util.Log; import java.util.Date; public class BarPrinter extends CordovaPlugin { private static final String TAG = "BarPrinter"; public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); Log.d(TAG, "Initializing BarPrinter"); } public String PrintPdf2(String file) { PrintDocumentAdapter pda = new PrintDocumentAdapter(){ @Override public void onWrite(PageRange[] pages, final ParcelFileDescriptor destination, CancellationSignal cancellationSignal,final WriteResultCallback callback){ cordova.getThreadPool().execute(new Runnable() { @Override public void run() { InputStream input = null; OutputStream output = null; try { input = new URL("http://5.100.254.203/~promo/test.pdf").openStream(); output = new FileOutputStream(destination.getFileDescriptor()); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); } callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES}); input.close(); output.close(); } catch (FileNotFoundException ee){ //Catch exception Log.e("bar",ee.getMessage()); } catch (Exception e) { Log.e("bar",e.toString()); //Catch exception } finally { } } }); } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){ if (cancellationSignal.isCanceled()) { callback.onLayoutCancelled(); return; } PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); callback.onLayoutFinished(pdi, true); } }; PrintManager printManager = (PrintManager) cordova.getActivity().getSystemService(Context.PRINT_SERVICE); // PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE); String jobName = " Document"; printManager.print(jobName, pda, null); return file+" . got It out"; } public String PrintPdf(String file) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); final String[] print = {"http://5.100.254.203/~promo/test.pdf"}; PrintDocumentAdapter pda = new PrintDocumentAdapter(){ @Override public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){ InputStream input = null; OutputStream output = null; try { input = new URL(print[0]).openStream(); output = new FileOutputStream(destination.getFileDescriptor()); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buf)) > 0) { output.write(buf, 0, bytesRead); } callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES}); } catch (FileNotFoundException ee){ //Catch exception Log.e("bar",ee.getMessage()); } catch (Exception e) { Log.e("bar",e.toString()); //Catch exception } finally { /* try { // input.close(); // output.close(); } catch (IOException e) { e.printStackTrace(); } */ } } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){ if (cancellationSignal.isCanceled()) { callback.onLayoutCancelled(); return; } PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build(); callback.onLayoutFinished(pdi, true); } }; PrintManager printManager = (PrintManager) cordova.getActivity().getSystemService(Context.PRINT_SERVICE); // PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE); String jobName = " Document"; printManager.print(jobName, pda, null); return file+" . got It"; } public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { if(action.equals("PrintPdf")) { String phrase = args.getString(0); // callbackContext.success("bar shahaf"); String got = "bbbbb";// PrintPdf2(phrase ); PrintPdf2("bbb" ); /* cordova.getActivity().runOnUiThread( new Runnable() { @Override public void run() { PrintPdf2("bbb" ); } }); */ final PluginResult result = new PluginResult(PluginResult.Status.OK, (got)); callbackContext.sendPluginResult(result); // Echo back the first argument Log.d(TAG, phrase); } else if(action.equals("echo")) { String phrase = args.getString(0); // callbackContext.success("bar shahaf"); final PluginResult result = new PluginResult(PluginResult.Status.OK, ("lolll")); callbackContext.sendPluginResult(result); // Echo back the first argument Log.d(TAG, phrase); } else if(action.equals("getDate")) { // An example of returning data back to the web layer // return new PluginResult("ok", "result"); //callbackContext.success("bar shahaf"); } return true; } }
package com.exedio.cope.pattern; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.exedio.cope.DataField; import com.exedio.cope.DataLengthViolationException; import com.exedio.cope.DateField; import com.exedio.cope.Field; import com.exedio.cope.FunctionField; import com.exedio.cope.Item; import com.exedio.cope.MandatoryViolationException; import com.exedio.cope.Pattern; import com.exedio.cope.SetValue; import com.exedio.cope.StringField; import com.exedio.cope.Field.Option; public final class Media extends CachedMedia { final boolean optional; final DataField body; final ContentType contentType; final DateField lastModified; public static final long DEFAULT_LENGTH = DataField.DEFAULT_LENGTH; private Media(final boolean optional, final long bodyMaximumLength, final ContentType contentType) { this.optional = optional; registerSource(this.body = optional(new DataField(), optional).lengthMax(bodyMaximumLength)); this.contentType = contentType; final StringField contentTypeField = contentType.field; if(contentTypeField!=null) registerSource(contentTypeField); registerSource(this.lastModified = optional(new DateField(), optional)); assert optional == !body.isMandatory(); assert (contentTypeField==null) || (optional == !contentTypeField.isMandatory()); assert optional == !lastModified.isMandatory(); assert contentType!=null; } private static final DataField optional(final DataField field, final boolean optional) { return optional ? field.optional() : field; } private static final DateField optional(final DateField field, final boolean optional) { return optional ? field.optional() : field; } /** * @deprecated use {@link #contentType(String)} instead. */ @Deprecated public Media(final String fixedMimeMajor, final String fixedMimeMinor) { this(false, DEFAULT_LENGTH, new FixedContentType(fixedMimeMajor, fixedMimeMinor)); } /** * @deprecated use {@link #optional()} and {@link #contentType(String)} instead. */ @Deprecated public Media(final Option option, final String fixedMimeMajor, final String fixedMimeMinor) { this(option.optional, DEFAULT_LENGTH, new FixedContentType(fixedMimeMajor, fixedMimeMinor)); if(option.unique) throw new RuntimeException("Media cannot be unique"); } /** * @deprecated use {@link #contentTypeMajor(String)} instead. */ @Deprecated public Media(final String fixedMimeMajor) { this(false, DEFAULT_LENGTH, new HalfFixedContentType(fixedMimeMajor, false)); } /** * @deprecated use {@link #optional()} and {@link #contentTypeMajor(String)} instead. */ @Deprecated public Media(final Option option, final String fixedMimeMajor) { this(option.optional, DEFAULT_LENGTH, new HalfFixedContentType(fixedMimeMajor, option.optional)); if(option.unique) throw new RuntimeException("Media cannot be unique"); } public Media() { this(false, DEFAULT_LENGTH, new DefaultContentType(false)); } /** * @deprecated use {@link #optional()} instead. */ @Deprecated public Media(final Option option) { this(option.optional, DEFAULT_LENGTH, new DefaultContentType(option.optional)); if(option.unique) throw new RuntimeException("Media cannot be unique"); } public Media optional() { return new Media(true, body.getMaximumLength(), contentType.optional()); } public Media lengthMax(final long maximumLength) { return new Media(optional, maximumLength, contentType.copy()); } /** * Creates a new media, that must contain the given content type only. */ public Media contentType(final String contentType) { return new Media(optional, body.getMaximumLength(), new FixedContentType(contentType)); } /** * Creates a new media, that must contain the a content type with the given major part only. */ public Media contentTypeMajor(final String majorContentType) { return new Media(optional, body.getMaximumLength(), new HalfFixedContentType(majorContentType, optional)); } public boolean checkContentType(final String contentType) { return this.contentType.check(contentType); } public String getContentTypeDescription() { return contentType.describe(); } public long getMaximumLength() { return body.getMaximumLength(); } public DataField getBody() { return body; } public StringField getContentType() { return contentType.field; } public DateField getLastModified() { return lastModified; } public FunctionField getIsNull() { return lastModified; } @Override public void initialize() { super.initialize(); final String name = getName(); if(!body.isInitialized()) initialize(body, name+"Body"); final StringField contentTypeField = contentType.field; if(contentTypeField!=null && !contentTypeField.isInitialized()) initialize(contentTypeField, name + contentType.name); initialize(lastModified, name+"LastModified"); } public boolean isNull(final Item item) { return optional ? (lastModified.get(item)==null) : false; } /** * Returns the major mime type for the given content type. * Returns null, if content type is null. */ public final static String toMajor(final String contentType) throws IllegalContentTypeException { return toMajorMinor(contentType, true); } /** * Returns the minor mime type for the given content type. * Returns null, if content type is null. */ public final static String toMinor(final String contentType) throws IllegalContentTypeException { return toMajorMinor(contentType, false); } private final static String toMajorMinor(final String contentType, final boolean major) throws IllegalContentTypeException { if(contentType!=null) { final int pos = contentType.indexOf('/'); if(pos<0) throw new RuntimeException(contentType); return major ? contentType.substring(0, pos) : contentType.substring(contentType.indexOf('/')+1); } else return null; } /** * Returns the content type of this media. * Returns null, if this media is null. */ @Override public String getContentType(final Item item) { if(isNull(item)) return null; return contentType.get(item); } /** * Returns the date of the last modification * of this media. * Returns -1, if this media is null. */ @Override public long getLastModified(final Item item) { if(isNull(item)) return -1; return lastModified.get(item).getTime(); } /** * Returns the length of the body of this media. * Returns -1, if this media is null. */ public long getLength(final Item item) { if(isNull(item)) return -1; final long result = body.getLength(item); assert result>=0 : item.getCopeID(); return result; } /** * Returns the body of this media. * Returns null, if this media is null. */ public byte[] getBody(final Item item) { return this.body.get(item); } /** * Sets the contents of this media. * @param body give null to make this media null. * @throws MandatoryViolationException * if body is null and field is {@link Field#isMandatory() mandatory}. * @throws DataLengthViolationException * if body is longer than {@link #getMaximumLength()} */ public void set(final Item item, final byte[] body, final String contentType) throws DataLengthViolationException { try { set(item, (Object)body, contentType); } catch(IOException e) { throw new RuntimeException(e); } } /** * Writes the body of this media into the given steam. * Does nothing, if this media is null. * @throws NullPointerException * if <tt>body</tt> is null. * @throws IOException if writing <tt>body</tt> throws an IOException. */ public void getBody(final Item item, final OutputStream body) throws IOException { this.body.get(item, body); } /** * Sets the contents of this media. * Closes <tt>body</tt> after reading the contents of the stream. * @param body give null to make this media null. * @throws MandatoryViolationException * if <tt>body</tt> is null and field is {@link Field#isMandatory() mandatory}. * @throws DataLengthViolationException * if <tt>body</tt> is longer than {@link #getMaximumLength()} * @throws IOException if reading <tt>body</tt> throws an IOException. */ public void set(final Item item, final InputStream body, final String contentType) throws DataLengthViolationException, IOException { try { set(item, (Object)body, contentType); } finally { if(body!=null) body.close(); } } /** * Writes the body of this media into the given file. * Does nothing, if this media is null. * @throws NullPointerException * if <tt>body</tt> is null. * @throws IOException if writing <tt>body</tt> throws an IOException. */ public void getBody(final Item item, final File body) throws IOException { this.body.get(item, body); } /** * Sets the contents of this media. * @param body give null to make this media null. * @throws MandatoryViolationException * if <tt>body</tt> is null and field is {@link Field#isMandatory() mandatory}. * @throws DataLengthViolationException * if <tt>body</tt> is longer than {@link #getMaximumLength()} * @throws IOException if reading <tt>body</tt> throws an IOException. */ public void set(final Item item, final File body, final String contentType) throws DataLengthViolationException, IOException { set(item, (Object)body, contentType); } private void set(final Item item, final Object body, final String contentType) throws DataLengthViolationException, IOException { if(body!=null) { if(contentType==null) throw new RuntimeException("if body is not null, content type must also be not null"); if(!this.contentType.check(contentType)) throw new IllegalContentTypeException(this, item, contentType); final long length; if(body instanceof byte[]) length = ((byte[])body).length; else if(body instanceof InputStream) length = -1; else length = ((File)body).length(); if(length>this.body.getMaximumLength()) throw new DataLengthViolationException(this.body, item, length, true); } else { if(contentType!=null) throw new RuntimeException("if body is null, content type must also be null"); } final ArrayList<SetValue> values = new ArrayList<SetValue>(4); final StringField contentTypeField = this.contentType.field; if(contentTypeField!=null) values.add(contentTypeField.map(contentType!=null ? this.contentType.map(contentType) : null)); values.add(this.lastModified.map(body!=null ? new Date() : null)); if(body instanceof byte[]) values.add(this.body.map((byte[])body)); item.set(values.toArray(new SetValue[values.size()])); // TODO set InputStream/File via Item.set(SetValue[]) as well if(body instanceof byte[]) /* already set above */; else if(body instanceof InputStream) this.body.set(item, (InputStream)body); else this.body.set(item, (File)body); } public final static Media get(final DataField field) { for(final Pattern pattern : field.getPatterns()) { if(pattern instanceof Media) { final Media media = (Media)pattern; if(media.getBody()==field) return media; } } throw new NullPointerException(field.toString()); } @Override public Media.Log doGetIfModified( final HttpServletRequest request, final HttpServletResponse response, final Item item, final String extension) throws ServletException, IOException { final String contentType = getContentType(item); //System.out.println("contentType="+contentType); if(contentType==null) return isNull; response.setContentType(contentType); final int contentLength = (int)getLength(item); //System.out.println("contentLength="+String.valueOf(contentLength)); response.setContentLength(contentLength); //response.setHeader("Cache-Control", "public"); //System.out.println(request.getMethod()+' '+request.getProtocol()+" IMS="+format(ifModifiedSince)+" LM="+format(lastModified)+" modified: "+contentLength); ServletOutputStream out = null; try { out = response.getOutputStream(); getBody(item, out); return delivered; } finally { if(out!=null) out.close(); } } private static abstract class ContentType { final StringField field; final String name; ContentType(final StringField field, final String name) { this.field = field; this.name = name; assert (field==null) == (name==null); } abstract ContentType copy(); abstract ContentType optional(); abstract boolean check(String contentType); abstract String describe(); abstract String get(Item item); abstract String map(String contentType); protected static final StringField makeField(final boolean optional, final int maxLength) { final StringField f = new StringField().lengthRange(1, maxLength); return optional ? f.optional() : f; } } private static final class DefaultContentType extends ContentType { DefaultContentType(final boolean optional) { super(makeField(optional, 61), "ContentType"); } @Override DefaultContentType copy() { return new DefaultContentType(!field.isMandatory()); } @Override DefaultContentType optional() { return new DefaultContentType(true); } @Override boolean check(final String contentType) { return contentType.indexOf('/')>=0; } @Override String describe() { return "*/*"; } @Override String get(final Item item) { return field.get(item); } @Override String map(final String contentType) { return contentType; } } private static final class FixedContentType extends ContentType { private final String full; FixedContentType(final String full) { super(null, null); this.full = full; } /** * @deprecated is used from deprecated code only */ @Deprecated FixedContentType(final String major, final String minor) { this(major + '/' + minor); if(major==null) throw new NullPointerException("fixedMimeMajor must not be null"); if(minor==null) throw new NullPointerException("fixedMimeMinor must not be null"); } @Override FixedContentType copy() { return new FixedContentType(full); } @Override FixedContentType optional() { return copy(); } @Override boolean check(final String contentType) { return this.full.equals(contentType); } @Override String describe() { return full; } @Override String get(final Item item) { return full; } @Override String map(final String contentType) { throw new RuntimeException(); } } private static final class HalfFixedContentType extends ContentType { private final String major; private final String prefix; private final int prefixLength; HalfFixedContentType(final String major, final boolean optional) { super(makeField(optional, 30), "Minor"); this.major = major; this.prefix = major + '/'; this.prefixLength = this.prefix.length(); if(major==null) throw new NullPointerException("fixedMimeMajor must not be null"); } @Override HalfFixedContentType copy() { return new HalfFixedContentType(major, !field.isMandatory()); } @Override HalfFixedContentType optional() { return new HalfFixedContentType(major, true); } @Override boolean check(final String contentType) { return contentType.startsWith(prefix); } @Override String describe() { return prefix + '*'; } @Override String get(final Item item) { return prefix + field.get(item); } @Override String map(final String contentType) { assert check(contentType); return contentType.substring(prefixLength); } } }
package divestoclimb.scuba.equipment; import android.app.Activity; import android.os.Bundle; import android.text.util.Linkify; import android.widget.TextView; public class Info extends Activity { // The Activity takes two arguments via its Intent: // Specify the string resource to use for the title public static final String KEY_TITLE = "title"; // Specify the string resource to use for the body text public static final String KEY_TEXT = "text"; private int mTextResId, mTitleResId; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Bundle params = icicle != null? icicle: getIntent().getExtras(); mTitleResId = params.getInt(KEY_TITLE); setTitle(mTitleResId); setContentView(R.layout.text_dialog); TextView text = (TextView)findViewById(R.id.text); mTextResId = params.getInt(KEY_TEXT); text.setText(getText(mTextResId)); // Make links Linkify.addLinks(text, Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(KEY_TITLE, mTitleResId); outState.putInt(KEY_TEXT, mTextResId); } }
package org.neo4j.impl.core; // Java imports import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import org.neo4j.api.core.Direction; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.api.core.ReturnableEvaluator; import org.neo4j.api.core.StopEvaluator; import org.neo4j.api.core.Traverser; import org.neo4j.api.core.Traverser.Order; import org.neo4j.impl.event.Event; import org.neo4j.impl.event.EventData; import org.neo4j.impl.event.EventManager; import org.neo4j.impl.transaction.IllegalResourceException; import org.neo4j.impl.transaction.LockManager; import org.neo4j.impl.transaction.LockNotFoundException; import org.neo4j.impl.transaction.LockType; import org.neo4j.impl.transaction.NotInTransactionException; import org.neo4j.impl.transaction.TransactionFactory; import org.neo4j.impl.traversal.TraverserFactory; import org.neo4j.impl.util.ArrayIntSet; import org.neo4j.impl.util.ArrayMap; /** * This is the implementation of {@link Node}. Class <CODE>NodeImpl</CODE> * has two different states/phases for relationships and properties. * First phase the full node isn't in memory, some or non of the properties and * relationships may be in memory. The second phase (full phase) all properties * or relationships are in memory. * <p> * All public methods must be invoked within a transaction context, * failure to do so will result in an exception. * Modifying methods will create a command that can execute and undo the desired * operation. The command will be associated with the transaction and * if the transaction fails all the commands participating in the transaction * will be undone. * <p> * Methods that uses commands will first create a command and verify that * we're in a transaction context. To persist operations a pro-active event * is generated and will cause the * {@link org.neo4j.impl.persistence.BusinessLayerMonitor} to persist the * then operation. * If the event fails (false is returned) the transaction is marked as * rollback only and if the command will be undone. * <p> * This implementation of node does not rely on persistence storage to * enforce constrains. This is done by {@link NeoConstraints} that evaluates * the events generated by modifying operations. */ class NodeImpl implements Node, Comparable<Node> { private static enum NodePhase { EMPTY_PROPERTY, FULL_PROPERTY, EMPTY_REL, FULL_REL } private static Logger log = Logger.getLogger( NodeImpl.class.getName() ); private static final LockManager lockManager = LockManager.getManager(); private static final LockReleaser lockReleaser = LockReleaser.getManager(); private static final NodeManager nodeManager = NodeManager.getManager(); private static final TraverserFactory travFactory = TraverserFactory.getFactory(); private final int id; private boolean isDeleted = false; private NodePhase nodePropPhase; private NodePhase nodeRelPhase; private ArrayMap<String,ArrayIntSet> relationshipMap = new ArrayMap<String,ArrayIntSet>(); private ArrayMap<Integer,Property> propertyMap = null; // new ArrayMap<Integer,Property>( 9, false, true ); NodeImpl( int id ) { this.id = id; this.nodePropPhase = NodePhase.EMPTY_PROPERTY; this.nodeRelPhase = NodePhase.EMPTY_REL; } // newNode will only be true for NodeManager.createNode NodeImpl( int id, boolean newNode ) { this.id = id; if ( newNode ) { this.nodePropPhase = NodePhase.FULL_PROPERTY; this.nodeRelPhase = NodePhase.FULL_REL; } } public long getId() { return this.id; } public Iterable<Relationship> getRelationships() { acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // Iterate through relationshipMap's values (which are sets // of relationships ids) and merge them all into one list. // Convert it to array and return it. // TODO: rewrite this with iterator wrapper /* List<Relationship> allRelationships = new LinkedList<Relationship>(); Iterator<ArrayIntSet> values = relationshipMap.values().iterator(); while ( values.hasNext() ) { ArrayIntSet relTypeSet = values.next(); for ( int relId : relTypeSet.values() ) { allRelationships.add( new RelationshipProxy( relId ) ); } } return allRelationships;*/ Iterator<ArrayIntSet> values = relationshipMap.values().iterator(); int size = 0; while ( values.hasNext() ) { ArrayIntSet relTypeSet = values.next(); size += relTypeSet.size(); } values = relationshipMap.values().iterator(); int[] ids = new int[size]; int position = 0; while ( values.hasNext() ) { ArrayIntSet relTypeSet = values.next(); for ( int relId : relTypeSet.values() ) { ids[position++] = relId; } } return new RelationshipIterator( ids, this, Direction.BOTH ); } finally { releaseLock( this, LockType.READ ); } } public Iterable<Relationship> getRelationships( Direction dir ) { if ( dir == Direction.BOTH ) { return getRelationships(); } acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // Iterate through relationshipMap's values (which are lists // of relationships) and merge them all into one list. Convert it // to array and return it. // TODO: rewrite this with iterator wrapper /* List<Relationship> allRelationships = new LinkedList<Relationship>(); Iterator<ArrayIntSet> values = relationshipMap.values().iterator(); while ( values.hasNext() ) { ArrayIntSet relTypeSet = values.next(); for ( int relId : relTypeSet.values() ) { Relationship rel = nodeManager.getRelationshipById( relId ); if ( dir == Direction.OUTGOING && rel.getStartNode().equals( this ) ) { allRelationships.add( rel ); } else if ( dir == Direction.INCOMING && rel.getEndNode().equals( this ) ) { allRelationships.add( rel ); } } } return allRelationships;*/ Iterator<ArrayIntSet> values = relationshipMap.values().iterator(); int size = 0; while ( values.hasNext() ) { ArrayIntSet relTypeSet = values.next(); size += relTypeSet.size(); } values = relationshipMap.values().iterator(); int[] ids = new int[size]; int position = 0; while ( values.hasNext() ) { ArrayIntSet relTypeSet = values.next(); for ( int relId : relTypeSet.values() ) { ids[position++] = relId; } } return new RelationshipIterator( ids, this, dir ); } finally { releaseLock( this, LockType.READ ); } } public Iterable<Relationship> getRelationships( RelationshipType type ) { acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // TODO: rewrite with iterator wrapper ArrayIntSet relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet == null ) { return Collections.emptyList(); } /* List<Relationship> rels = new LinkedList<Relationship>(); Iterator<Integer> values = relationshipSet.iterator(); while ( values.hasNext() ) { rels.add( new RelationshipProxy( values.next() ) ); } return rels;*/ int[] ids = new int[relationshipSet.size()]; int position = 0; for ( int relId : relationshipSet.values() ) { ids[position++] = relId; } return new RelationshipIterator( ids, this, Direction.BOTH ); } finally { releaseLock( this, LockType.READ ); } } public Iterable<Relationship> getRelationships( RelationshipType... types ) { acquireLock( this, LockType.READ ); try { ensureFullRelationships(); int size = 0; for ( RelationshipType type : types ) { ArrayIntSet relTypeSet = relationshipMap.get( type.name() ); if ( relTypeSet != null ) { size += relTypeSet.size(); } } int[] ids = new int[size]; int position = 0; for ( RelationshipType type : types ) { ArrayIntSet relTypeSet = relationshipMap.get( type.name() ); if ( relTypeSet != null ) { for ( int relId : relTypeSet.values() ) { ids[position++] = relId; } } } return new RelationshipIterator( ids, this, Direction.BOTH ); } finally { releaseLock( this, LockType.READ ); } } public Relationship getSingleRelationship( RelationshipType type, Direction dir ) { Iterator<Relationship> rels = getRelationships( type, dir ).iterator(); if ( !rels.hasNext() ) { return null; } Relationship rel = rels.next(); if ( rels.hasNext() ) { throw new NotFoundException( "More then one relationship[" + type + "] found" ); } return rel; } public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir ) { if ( dir == Direction.BOTH ) { return getRelationships( type ); } acquireLock( this, LockType.READ ); try { ensureFullRelationships(); if ( relationshipMap == null ) { return Collections.emptyList(); } // TODO: rewrite with iterator wrapper ArrayIntSet relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet == null ) { return Collections.emptyList(); } /* List<Relationship> rels = new LinkedList<Relationship>(); Iterator<Integer> values = relationshipSet.iterator(); while ( values.hasNext() ) { Relationship rel = nodeManager.getRelationshipById( values.next() ); if ( dir == Direction.OUTGOING && rel.getStartNode().equals( this ) ) { rels.add( rel ); } else if ( dir == Direction.INCOMING && rel.getEndNode().equals( this ) ) { rels.add( rel ); } } return rels;*/ int[] ids = new int[relationshipSet.size()]; int position = 0; for ( int relId : relationshipSet.values() ) { ids[position++] = relId; } return new RelationshipIterator( ids, this, dir ); } finally { releaseLock( this, LockType.READ ); } } /** * Deletes this node removing it from cache and persistent storage. If * unable to delete, a <CODE>DeleteException</CODE> is thrown. * <p> * If the node is in first phase it will be changed to full. This is done * because we don't rely on the underlying persistence storage to make sure * all relationships connected to this node has been deleted. Instead * {@link NeoConstraintsListener} will validate that all deleted nodes in * the transaction don't have any relationships connected to them before * the transaction completes. * <p> * Invoking any method on this node after delete is invalid, doing so might * result in a checked or runtime exception being thrown. * * @throws DeleteException if unable to delete */ public void delete() // throws DeleteException { acquireLock( this, LockType.WRITE ); try { EventManager em = EventManager.getManager(); EventData eventData = new EventData( new NodeOpData( this, id ) ); if ( !em.generateProActiveEvent( Event.NODE_DELETE, eventData ) ) { setRollbackOnly(); throw new DeleteException( "Generate pro-active event failed, " + "unable to delete " + this ); } // normal node phase here isn't necessary, if something breaks we // still have the node as it was in memory and the transaction will // rollback so the full node will still be persistent nodeRelPhase = NodePhase.EMPTY_REL; nodePropPhase = NodePhase.EMPTY_PROPERTY; relationshipMap = new ArrayMap<String,ArrayIntSet>(); propertyMap = new ArrayMap<Integer,Property>( 9, false, true ); nodeManager.removeNodeFromCache( id ); em.generateReActiveEvent( Event.NODE_DELETE, eventData ); } finally { releaseLock( this, LockType.WRITE ); } } /** * Returns all properties on <CODE>this</CODE> node. The whole node will be * loaded (if not full phase already) to make sure that all properties are * present. * * @return an object array containing all properties. */ public Iterable<Object> getPropertyValues() { acquireLock( this, LockType.READ ); try { ensureFullProperties(); List<Object> properties = new ArrayList<Object>(); for ( Property property : propertyMap.values() ) { properties.add( property.getValue() ); } return properties; } finally { releaseLock( this, LockType.READ ); } } /** * Returns all property keys on <CODE>this</CODE> node. The whole node will * be loaded (if not full phase already) to make sure that all properties * are present. * * @return a string array containing all property keys. */ public Iterable<String> getPropertyKeys() { acquireLock( this, LockType.READ ); try { ensureFullProperties(); List<String> propertyKeys = new ArrayList<String>(); for ( int keyId : propertyMap.keySet() ) { propertyKeys.add( PropertyIndex.getIndexFor( keyId ).getKey() ); } return propertyKeys; } finally { releaseLock( this, LockType.READ ); } } /** * Returns the property for <CODE>key</CODE>. If key is null or the * property <CODE>key</CODE> dosen't exist {@link NotFoundException} is * thrown. If node is in first phase the cache is first checked and if * the property isn't found the node enters full phase and the cache is * checked again. * * @param key the property key * @return the property object * @throws NotFoundException if this property doesn't exist */ public Object getProperty( String key ) throws NotFoundException { if ( key == null ) { throw new IllegalArgumentException( "null key" ); } acquireLock( this, LockType.READ ); try { for ( PropertyIndex index : PropertyIndex.index( key ) ) { Property property = null; if ( propertyMap != null ) { property = propertyMap.get( index.getKeyId() ); } if ( property != null ) { return property.getValue(); } if ( ensureFullProperties() ) { property = propertyMap.get( index.getKeyId() ); if ( property != null ) { return property.getValue(); } } } if ( !PropertyIndex.hasAll() ) { ensureFullProperties(); for ( int keyId : propertyMap.keySet() ) { if ( !PropertyIndex.hasIndexFor( keyId ) ) { PropertyIndex indexToCheck = PropertyIndex.getIndexFor( keyId ); if ( indexToCheck.getKey().equals( key ) ) { return propertyMap.get( indexToCheck.getKeyId() ).getValue(); } } } } } finally { releaseLock( this, LockType.READ ); } throw new NotFoundException( "" + key + " property not found." ); } public Object getProperty( String key, Object defaultValue ) { if ( key == null ) { throw new IllegalArgumentException( "null key" ); } acquireLock( this, LockType.READ ); try { for ( PropertyIndex index : PropertyIndex.index( key ) ) { Property property = null; if ( propertyMap != null ) { property = propertyMap.get( index.getKeyId() ); } if ( property != null ) { return property.getValue(); } if ( ensureFullProperties() ) { property = propertyMap.get( index.getKeyId() ); if ( property != null ) { return property.getValue(); } } } if ( !PropertyIndex.hasAll() ) { ensureFullProperties(); for ( int keyId : propertyMap.keySet() ) { if ( !PropertyIndex.hasIndexFor( keyId ) ) { PropertyIndex indexToCheck = PropertyIndex.getIndexFor( keyId ); if ( indexToCheck.getKey().equals( key ) ) { return propertyMap.get( indexToCheck.getKeyId() ).getValue(); } } } } } finally { releaseLock( this, LockType.READ ); } return defaultValue; } /** * Returns true if this node has the property <CODE>key</CODE>. If node is * in first phase the cache is first checked and if the property isn't * found the node enters full phase and the cache is checked again. * If <CODE>key</CODE> is null false is returned. * * @param key the property key * @return true if <CODE>key</CODE> property exists */ public boolean hasProperty( String key ) { acquireLock( this, LockType.READ ); try { for ( PropertyIndex index : PropertyIndex.index( key ) ) { Property property = null; if ( propertyMap != null ) { property = propertyMap.get( index.getKeyId() ); } if ( property != null ) { return true; } if ( ensureFullProperties() ) { if ( propertyMap.get( index.getKeyId() ) != null ) { return true; } } } ensureFullProperties(); for ( int keyId : propertyMap.keySet() ) { PropertyIndex indexToCheck = PropertyIndex.getIndexFor( keyId ); if ( indexToCheck.getKey().equals( key ) ) { return true; } } return false; } finally { releaseLock( this, LockType.READ ); } } public void setProperty( String key, Object value ) throws IllegalValueException { if ( key == null || value == null ) { throw new IllegalValueException( "Null parameter, " + "key=" + key + ", " + "value=" + value ); } acquireLock( this, LockType.WRITE ); try { // must make sure we don't add already existing property ensureFullProperties(); PropertyIndex index = null; Property property = null; for ( PropertyIndex cachedIndex : PropertyIndex.index( key ) ) { property = propertyMap.get( cachedIndex.getKeyId() ); index = cachedIndex; if ( property != null ) { break; } } if ( property == null && !PropertyIndex.hasAll() ) { for ( int keyId : propertyMap.keySet() ) { if ( !PropertyIndex.hasIndexFor( keyId ) ) { PropertyIndex indexToCheck = PropertyIndex.getIndexFor( keyId ); if ( indexToCheck.getKey().equals( key ) ) { index = indexToCheck; property = propertyMap.get( indexToCheck.getKeyId() ); break; } } } } if ( index == null ) { index = PropertyIndex.createPropertyIndex( key ); } Event event = Event.NODE_ADD_PROPERTY; NodeOpData data; if ( property != null ) { int propertyId = property.getId(); data = new NodeOpData( this, id, propertyId, index, value ); event = Event.NODE_CHANGE_PROPERTY; } else { data = new NodeOpData( this, id, -1, index, value ); } EventManager em = EventManager.getManager(); EventData eventData = new EventData( data ); if ( !em.generateProActiveEvent( event, eventData ) ) { setRollbackOnly(); throw new IllegalValueException( "Generate pro-active event failed, " + " unable to add property[" + key + "," + value + "] on " + this ); } if ( event == Event.NODE_ADD_PROPERTY ) { doAddProperty( index, new Property( data.getPropertyId(), value ) ); } else { doChangeProperty( index, new Property( data.getPropertyId(), value ) ); } em.generateReActiveEvent( event, eventData ); } finally { releaseLock( this, LockType.WRITE ); } } /** * Removes the property <CODE>key</CODE>. If null property <CODE>key</CODE> * a <CODE>NotFoundException</CODE> is thrown. If property doesn't exist * <CODE>null</CODE> is returned. * * @param key the property key * @return the removed property value */ public Object removeProperty( String key ) { if ( key == null ) { throw new IllegalArgumentException( "Null parameter." ); } acquireLock( this, LockType.WRITE ); try { Property property = null; for ( PropertyIndex cachedIndex : PropertyIndex.index( key ) ) { property = null; if ( propertyMap != null ) { property = propertyMap.remove( cachedIndex.getKeyId() ); } if ( property == null ) { if ( ensureFullProperties() ) { property = propertyMap.remove( cachedIndex.getKeyId() ); if ( property != null ) { break; } } } else { break; } } if ( property == null && !PropertyIndex.hasAll() ) { ensureFullProperties(); for ( int keyId : propertyMap.keySet() ) { if ( !PropertyIndex.hasIndexFor( keyId ) ) { PropertyIndex indexToCheck = PropertyIndex.getIndexFor( keyId ); if ( indexToCheck.getKey().equals( key ) ) { property = propertyMap.remove( indexToCheck.getKeyId() ); break; } } } } if ( property == null ) { return null; } NodeOpData data = new NodeOpData( this, id, property.getId() ); EventManager em = EventManager.getManager(); EventData eventData = new EventData( data ); if ( !em.generateProActiveEvent( Event.NODE_REMOVE_PROPERTY, eventData ) ) { setRollbackOnly(); throw new NotFoundException( "Generate pro-active event failed, " + "unable to remove property[" + key + "] from " + this ); } em.generateReActiveEvent( Event.NODE_REMOVE_PROPERTY, eventData ); return property.getValue(); } finally { releaseLock( this, LockType.WRITE ); } } /** * If object <CODE>node</CODE> is a node, 0 is returned if <CODE>this</CODE> * node id equals <CODE>node's</CODE> node id, 1 if <CODE>this</CODE> * node id is greater and -1 else. * <p> * If <CODE>node</CODE> isn't a node a ClassCastException will be thrown. * * @param node the node to compare this node with * @return 0 if equal id, 1 if this id is greater else -1 */ public int compareTo( Node n ) { int ourId = (int) this.getId(), theirId = (int) n.getId(); if ( ourId < theirId ) { return -1; } else if ( ourId > theirId ) { return 1; } else { return 0; } } /** * Returns true if object <CODE>o</CODE> is a node with the same id * as <CODE>this</CODE>. * * @param o the object to compare * @return true if equal, else false */ public boolean equals( Object o ) { // verify type and not null, should use Node inteface if ( !(o instanceof Node) ) { return false; } // The equals contract: // o reflexive: x.equals(x) // o symmetric: x.equals(y) == y.equals(x) // o transitive: ( x.equals(y) && y.equals(z) ) == true // then x.equals(z) == true // o consistent: the nodeId never changes return this.getId() == ((Node) o).getId(); } public int hashCode() { return id; } /** * Returns this node's string representation. * * @return the string representation of this node */ public String toString() { return "Node #" + this.getId(); } /** * NOTE: caller is responsible for acquiring write lock on this node * before calling this method. */ void doAddProperty( PropertyIndex index, Property value ) throws IllegalValueException { if ( propertyMap.get( index.getKeyId() ) != null ) { throw new IllegalValueException( "Property[" + index.getKey() + "] already added." ); } propertyMap.put( index.getKeyId(), value ); } // caller is responsible for acquiring lock Property doRemoveProperty( PropertyIndex index ) throws NotFoundException { Property property = propertyMap.remove( index.getKeyId() ); if ( property != null ) { return property; } throw new NotFoundException( "Property not found: " + index.getKey() ); } // caller is responsible for acquiring lock Property doChangeProperty( PropertyIndex index, Property newValue ) throws IllegalValueException, NotFoundException { Property property = propertyMap.get( index.getKeyId() ); if ( property != null ) { Property oldProperty = new Property( property.getId(), property.getValue() ); property.setNewValue( newValue.getValue() ); return oldProperty; } throw new NotFoundException( "Property not found: " + index.getKey() ); } // caller is responsible for acquiring lock Property doGetProperty( PropertyIndex index ) throws NotFoundException { Property property = propertyMap.get( index.getKeyId() ); if ( property != null ) { return property; } throw new NotFoundException( "Property not found: " + index.getKey() ); } // caller is responsible for acquiring lock // this method is only called when a relationship is created or // a relationship delete is undone or when the full node is loaded void addRelationship( RelationshipType type, int relId ) { ArrayIntSet relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet == null ) { relationshipSet = new ArrayIntSet(); relationshipMap.put( type.name(), relationshipSet ); } relationshipSet.add( relId ); } // caller is responsible for acquiring lock // this method is only called when a undo create relationship or // a relationship delete is invoked. void removeRelationship( RelationshipType type, int relId ) { ArrayIntSet relationshipSet = relationshipMap.get( type.name() ); if ( relationshipSet != null ) { if ( !relationshipSet.remove( relId ) ) { if ( ensureFullRelationships() ) { relationshipSet.remove( relId ); } } if ( relationshipSet.size() == 0 ) { relationshipMap.remove( type.name() ); } } else { if ( ensureFullRelationships() ) { removeRelationship( type, relId ); } } } boolean hasRelationships() { ensureFullRelationships(); return ( relationshipMap.size() > 0 ); } private void setRollbackOnly() { try { TransactionFactory.getTransactionManager().setRollbackOnly(); } catch ( javax.transaction.SystemException se ) { se.printStackTrace(); log.severe( "Failed to set transaction rollback only" ); } } private boolean ensureFullProperties() { if ( nodePropPhase != NodePhase.FULL_PROPERTY ) { RawPropertyData[] rawProperties = nodeManager.loadProperties( this ); ArrayIntSet addedProps = new ArrayIntSet(); ArrayMap<Integer,Property> newPropertyMap = new ArrayMap<Integer,Property>(); for ( RawPropertyData propData : rawProperties ) { int propId = propData.getId(); assert addedProps.add( propId ); Property property = new Property( propId, propData.getValue() ); newPropertyMap.put( propData.getIndex(), property ); } if ( propertyMap != null ) { for ( int index : this.propertyMap.keySet() ) { Property prop = propertyMap.get( index ); if ( !addedProps.contains( prop.getId() ) ) { newPropertyMap.put( index, prop ); } } } this.propertyMap = newPropertyMap; nodePropPhase = NodePhase.FULL_PROPERTY; return true; } else { if ( propertyMap == null ) { propertyMap = new ArrayMap<Integer,Property>( 9, false, true ); } } return false; } private boolean ensureFullRelationships() { if ( nodeRelPhase != NodePhase.FULL_REL ) { List<Relationship> fullRelationshipList = nodeManager.loadRelationships( this ); ArrayIntSet addedRels = new ArrayIntSet(); ArrayMap<String,ArrayIntSet> newRelationshipMap = new ArrayMap<String,ArrayIntSet>(); for ( Relationship rel : fullRelationshipList ) { int relId = (int) rel.getId(); addedRels.add( relId ); RelationshipType type = rel.getType(); ArrayIntSet relationshipSet = newRelationshipMap.get( type.name() ); if ( relationshipSet == null ) { relationshipSet = new ArrayIntSet(); newRelationshipMap.put( type.name(), relationshipSet ); } relationshipSet.add( relId ); } for ( String typeName : this.relationshipMap.keySet() ) { ArrayIntSet relationshipSet = this.relationshipMap.get( typeName ); for ( Integer relId : relationshipSet.values() ) { if ( !addedRels.contains( relId ) ) { ArrayIntSet newRelationshipSet = newRelationshipMap.get( typeName ); if ( newRelationshipSet == null ) { newRelationshipSet = new ArrayIntSet(); newRelationshipMap.put( typeName, newRelationshipSet ); } newRelationshipSet.add( relId ); addedRels.add( relId ); } } } this.relationshipMap = newRelationshipMap; nodeRelPhase = NodePhase.FULL_REL; return true; } return false; } private void acquireLock( Object resource, LockType lockType ) { try { if ( lockType == LockType.READ ) { lockManager.getReadLock( resource ); } else if ( lockType == LockType.WRITE ) { lockManager.getWriteLock( resource ); } else { throw new RuntimeException( "Unkown lock type: " + lockType ); } } catch ( NotInTransactionException e ) { throw new RuntimeException( "Unable to get transaction isolation level.", e ); } catch ( IllegalResourceException e ) { throw new RuntimeException( e ); } } private void releaseLock( Object resource, LockType lockType ) { releaseLock( resource, lockType, false ); } private void releaseLock( Object resource, LockType lockType, boolean forceRelease ) { try { if ( lockType == LockType.READ ) { lockManager.releaseReadLock( resource ); } else if ( lockType == LockType.WRITE ) { if ( forceRelease ) { lockManager.releaseWriteLock( resource ); } else { lockReleaser.addLockToTransaction( resource, lockType ); } } else { throw new RuntimeException( "Unkown lock type: " + lockType ); } } catch ( NotInTransactionException e ) { e.printStackTrace(); throw new RuntimeException( "Unable to get transaction isolation level.", e ); } catch ( LockNotFoundException e ) { throw new RuntimeException( "Unable to release locks.", e ); } catch ( IllegalResourceException e ) { throw new RuntimeException( "Unable to release locks.", e ); } } boolean isDeleted() { return isDeleted; } void setIsDeleted( boolean flag ) { isDeleted = flag; } public Relationship createRelationshipTo( Node otherNode, RelationshipType type ) { return nodeManager.createRelationship( this, otherNode, type ); } public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction ) { return travFactory.createTraverser( traversalOrder, this, relationshipType, direction, stopEvaluator, returnableEvaluator ); } public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection ) { RelationshipType[] types = new RelationshipType[2]; Direction[] dirs = new Direction[2]; types[0] = firstRelationshipType; types[1] = secondRelationshipType; dirs[0] = firstDirection; dirs[1] = secondDirection; return travFactory.createTraverser( traversalOrder, this, types, dirs, stopEvaluator, returnableEvaluator ); } public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections ) { int length = relationshipTypesAndDirections.length; if ( (length % 2) != 0 || length == 0 ) { throw new IllegalArgumentException( "Variable argument should " + " consist of [RelationshipType,Direction] pairs" ); } int elements = relationshipTypesAndDirections.length / 2; RelationshipType[] types = new RelationshipType[ elements ]; Direction[] dirs = new Direction[ elements ]; int j = 0; for ( int i = 0; i < elements; i++ ) { Object relType = relationshipTypesAndDirections[j++]; if ( !(relType instanceof RelationshipType) ) { throw new IllegalArgumentException( "Expected RelationshipType at var args pos " + (j - 1) + ", found " + relType ); } types[i] = ( RelationshipType ) relType; Object direction = relationshipTypesAndDirections[j++]; if ( !(direction instanceof Direction) ) { throw new IllegalArgumentException( "Expected Direction at var args pos " + (j - 1) + ", found " + direction ); } dirs[i] = ( Direction ) direction; } return travFactory.createTraverser( traversalOrder, this, types, dirs, stopEvaluator, returnableEvaluator ); } }
package com.jme3.gde.core.util; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * * @author Nehon */ public class PropertyUtils { public static PropertyDescriptor getPropertyDescriptor(Class c, Field field) { try { PropertyDescriptor prop = new PropertyDescriptor(field.getName(), c); prop.setDisplayName(splitCamelCase(field.getName())); return prop; } catch (IntrospectionException ex) { //System.out.println(ex.getMessage()); return null; } } public static PropertyDescriptor getPropertyDescriptor(Class c, Method meth) { try { String name = meth.getName(); if (name.startsWith("get") || name.startsWith("set")) { name = name.substring(3); if (name.length() > 0) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } } else if (name.startsWith("is")) { name = name.substring(2); if (name.length() > 0) { name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } } else { return null; } PropertyDescriptor prop = new PropertyDescriptor(name, c); prop.setDisplayName(splitCamelCase(meth.getName())); return prop; } catch (IntrospectionException ex) { //System.out.println(ex.getMessage()); return null; } } static String splitCamelCase(String s) { s = capitalizeString(s); return s.replaceAll( String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"), " "); } public static String capitalizeString(String string) { char[] chars = string.toCharArray(); chars[0] = Character.toUpperCase(chars[0]); return String.valueOf(chars); } }
package org.zstack.sdk; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class CreateAccessKeyAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.CreateAccessKeyResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, maxLength = 32, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String accountUuid; @Param(required = true, maxLength = 32, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String userUuid; @Param(required = false, maxLength = 2048, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String description; @Param(required = false, maxLength = 20, minLength = 12, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String AccessKeyID; @Param(required = false, maxLength = 40, minLength = 24, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String AccessKeySecret; @Param(required = false) public java.lang.String resourceUuid; @Param(required = false, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.util.List tagUuids; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = false) public String sessionId; @Param(required = false) public String accessKeyId; @Param(required = false) public String accessKeySecret; @Param(required = false) public String requestIp; @NonAPIParam public long timeout = -1; @NonAPIParam public long pollingInterval = -1; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.CreateAccessKeyResult value = res.getResult(org.zstack.sdk.CreateAccessKeyResult.class); ret.value = value == null ? new org.zstack.sdk.CreateAccessKeyResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "POST"; info.path = "/accesskeys"; info.needSession = true; info.needPoll = true; info.parameterName = "params"; return info; } }
package com.openxc.messages.formatters; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import android.util.Log; import com.google.common.base.CharMatcher; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSyntaxException; import com.openxc.messages.DiagnosticRequest; import com.openxc.messages.DiagnosticResponse; import com.openxc.messages.CanMessage; import com.openxc.messages.Command; import com.openxc.messages.CommandResponse; import com.openxc.messages.NamedVehicleMessage; import com.openxc.messages.EventedSimpleVehicleMessage; import com.openxc.messages.SimpleVehicleMessage; import com.openxc.messages.UnrecognizedMessageTypeException; import com.openxc.messages.VehicleMessage; public class JsonFormatter { private static final String TAG = "JsonFormatter"; private static Gson sGson = new Gson(); public static String serialize(VehicleMessage message) { return sGson.toJson(message); } public static VehicleMessage deserialize(String data) throws UnrecognizedMessageTypeException { JsonObject root; try { JsonParser parser = new JsonParser(); root = parser.parse(data).getAsJsonObject(); } catch(JsonSyntaxException | IllegalStateException e) { throw new UnrecognizedMessageTypeException( "Unable to parse JSON from \"" + data + "\": " + e); } Set<String> fields = new HashSet<>(); for(Map.Entry<String, JsonElement> entry : root.entrySet()) { fields.add(entry.getKey()); } Gson gson = new Gson(); VehicleMessage message = new VehicleMessage(); if(CanMessage.containsRequiredFields(fields)) { message = sGson.fromJson(root, CanMessage.class); } else if(DiagnosticResponse.containsRequiredFields(fields)) { message = sGson.fromJson(root, DiagnosticResponse.class); } else if(DiagnosticRequest.containsRequiredFields(fields)) { message = sGson.fromJson(root, DiagnosticRequest.class); } else if(Command.containsRequiredFields(fields)) { message = sGson.fromJson(root, Command.class); } else if(CommandResponse.containsRequiredFields(fields)) { message = sGson.fromJson(root, CommandResponse.class); } else if(EventedSimpleVehicleMessage.containsRequiredFields(fields)) { message = sGson.fromJson(root, EventedSimpleVehicleMessage.class); } else if(SimpleVehicleMessage.containsRequiredFields(fields)) { message = sGson.fromJson(root, SimpleVehicleMessage.class); } else if(NamedVehicleMessage.containsRequiredFields(fields)) { message = sGson.fromJson(root, NamedVehicleMessage.class); } else if(fields.contains(VehicleMessage.EXTRAS_KEY)) { message = sGson.fromJson(root, VehicleMessage.class); } else { throw new UnrecognizedMessageTypeException( "Unrecognized combination of fields: " + fields); } return message; } }
package org.postgresql.ds.jdbc23; import javax.sql.*; import java.sql.*; import java.util.*; import java.lang.reflect.*; import org.postgresql.PGConnection; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; /** * PostgreSQL implementation of the PooledConnection interface. This shouldn't * be used directly, as the pooling client should just interact with the * ConnectionPool instead. * @see org.postgresql.ds.PGConnectionPoolDataSource * * @author Aaron Mulder (ammulder@chariotsolutions.com) * @author Csaba Nagy (ncsaba@yahoo.com) */ public abstract class AbstractJdbc23PooledConnection { private List listeners = new LinkedList(); private Connection con; private ConnectionHandler last; private final boolean autoCommit; private final boolean isXA; /** * Creates a new PooledConnection representing the specified physical * connection. */ public AbstractJdbc23PooledConnection(Connection con, boolean autoCommit, boolean isXA) { this.con = con; this.autoCommit = autoCommit; this.isXA = isXA; } /** * Adds a listener for close or fatal error events on the connection * handed out to a client. */ public void addConnectionEventListener(ConnectionEventListener connectionEventListener) { listeners.add(connectionEventListener); } /** * Removes a listener for close or fatal error events on the connection * handed out to a client. */ public void removeConnectionEventListener(ConnectionEventListener connectionEventListener) { listeners.remove(connectionEventListener); } /** * Closes the physical database connection represented by this * PooledConnection. If any client has a connection based on * this PooledConnection, it is forcibly closed as well. */ public void close() throws SQLException { if (last != null) { last.close(); if (!con.getAutoCommit()) { try { con.rollback(); } catch (SQLException e) { } } } try { con.close(); } finally { con = null; } } /** * Gets a handle for a client to use. This is a wrapper around the * physical connection, so the client can call close and it will just * return the connection to the pool without really closing the * pgysical connection. * * <p>According to the JDBC 2.0 Optional Package spec (6.2.3), only one * client may have an active handle to the connection at a time, so if * there is a previous handle active when this is called, the previous * one is forcibly closed and its work rolled back.</p> */ public Connection getConnection() throws SQLException { if (con == null) { // Before throwing the exception, let's notify the registered listeners about the error PSQLException sqlException = new PSQLException(GT.tr("This PooledConnection has already been closed."), PSQLState.CONNECTION_DOES_NOT_EXIST); fireConnectionFatalError(sqlException); throw sqlException; } // If any error occures while opening a new connection, the listeners // have to be notified. This gives a chance to connection pools to // elliminate bad pooled connections. try { // Only one connection can be open at a time from this PooledConnection. See JDBC 2.0 Optional Package spec section 6.2.3 if (last != null) { last.close(); if (!con.getAutoCommit()) { try { con.rollback(); } catch (SQLException e) { } } con.clearWarnings(); } con.setAutoCommit(autoCommit); } catch (SQLException sqlException) { fireConnectionFatalError(sqlException); throw (SQLException)sqlException.fillInStackTrace(); } ConnectionHandler handler = new ConnectionHandler(con); last = handler; Connection proxyCon = (Connection)Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Connection.class, PGConnection.class}, handler); last.setProxy(proxyCon); return proxyCon; } /** * Used to fire a connection closed event to all listeners. */ void fireConnectionClosed() { ConnectionEvent evt = null; // Copy the listener list so the listener can remove itself during this method call ConnectionEventListener[] local = (ConnectionEventListener[]) listeners.toArray(new ConnectionEventListener[listeners.size()]); for (int i = 0; i < local.length; i++) { ConnectionEventListener listener = local[i]; if (evt == null) { evt = createConnectionEvent(null); } listener.connectionClosed(evt); } } /** * Used to fire a connection error event to all listeners. */ void fireConnectionFatalError(SQLException e) { ConnectionEvent evt = null; // Copy the listener list so the listener can remove itself during this method call ConnectionEventListener[] local = (ConnectionEventListener[])listeners.toArray(new ConnectionEventListener[listeners.size()]); for (int i = 0; i < local.length; i++) { ConnectionEventListener listener = local[i]; if (evt == null) { evt = createConnectionEvent(e); } listener.connectionErrorOccurred(evt); } } protected abstract ConnectionEvent createConnectionEvent(SQLException e); // Classes we consider fatal. private static String[] fatalClasses = { "08", // connection error "53", // insufficient resources // nb: not just "57" as that includes query cancel which is nonfatal "57P01", // admin shutdown "57P02", // crash shutdown "57P03", // cannot connect now "58", // system error (backend) "60", // system error (driver) "99", // unexpected error "F0", // configuration file error (backend) "XX", // internal error (backend) }; private static boolean isFatalState(String state) { if (state == null) // no info, assume fatal return true; if (state.length() < 2) // no class info, assume fatal return true; for (int i = 0; i < fatalClasses.length; ++i) if (state.startsWith(fatalClasses[i])) return true; // fatal return false; } /** * Fires a connection error event, but only if we * think the exception is fatal. * * @param e the SQLException to consider */ private void fireConnectionError(SQLException e) { if (!isFatalState(e.getSQLState())) return; fireConnectionFatalError(e); } /** * Instead of declaring a class implementing Connection, which would have * to be updated for every JDK rev, use a dynamic proxy to handle all * calls through the Connection interface. This is the part that * requires JDK 1.3 or higher, though JDK 1.2 could be supported with a * 3rd-party proxy package. */ private class ConnectionHandler implements InvocationHandler { private Connection con; private Connection proxy; // the Connection the client is currently using, which is a proxy private boolean automatic = false; public ConnectionHandler(Connection con) { this.con = con; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // From Object if (method.getDeclaringClass().getName().equals("java.lang.Object")) { if (method.getName().equals("toString")) { return "Pooled connection wrapping physical connection " + con; } if (method.getName().equals("hashCode")) { return new Integer(con.hashCode()); } if (method.getName().equals("equals")) { if (args[0] == null) { return Boolean.FALSE; } try { return Proxy.isProxyClass(args[0].getClass()) && ((ConnectionHandler) Proxy.getInvocationHandler(args[0])).con == con ? Boolean.TRUE : Boolean.FALSE; } catch (ClassCastException e) { return Boolean.FALSE; } } try { return method.invoke(con, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } // All the rest is from the Connection or PGConnection interface if (method.getName().equals("isClosed")) { return con == null ? Boolean.TRUE : Boolean.FALSE; } if (con == null && !method.getName().equals("close")) { throw new PSQLException(automatic ? GT.tr("Connection has been closed automatically because a new connection was opened for the same PooledConnection or the PooledConnection has been closed.") : GT.tr("Connection has been closed."), PSQLState.CONNECTION_DOES_NOT_EXIST); } if (method.getName().equals("close")) { // we are already closed and a double close // is not an error. if (con == null) return null; SQLException ex = null; if (!isXA && !con.getAutoCommit()) { try { con.rollback(); } catch (SQLException e) { ex = e; } } con.clearWarnings(); con = null; this.proxy = null; last = null; fireConnectionClosed(); if (ex != null) { throw ex; } return null; } // From here on in, we invoke via reflection, catch exceptions, // and check if they're fatal before rethrowing. try { if (method.getName().equals("createStatement")) { Statement st = (Statement)method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Statement.class, org.postgresql.PGStatement.class}, new StatementHandler(this, st)); } else if (method.getName().equals("prepareCall")) { Statement st = (Statement)method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{CallableStatement.class, org.postgresql.PGStatement.class}, new StatementHandler(this, st)); } else if (method.getName().equals("prepareStatement")) { Statement st = (Statement)method.invoke(con, args); return Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{PreparedStatement.class, org.postgresql.PGStatement.class}, new StatementHandler(this, st)); } else { return method.invoke(con, args); } } catch (InvocationTargetException e) { Throwable te = e.getTargetException(); if (te instanceof SQLException) fireConnectionError((SQLException)te); // Tell listeners about exception if it's fatal throw te; } } Connection getProxy() { return proxy; } void setProxy(Connection proxy) { this.proxy = proxy; } public void close() { if (con != null) { automatic = true; } con = null; proxy = null; // No close event fired here: see JDBC 2.0 Optional Package spec section 6.3 } public boolean isClosed() { return con == null; } } /** * Instead of declaring classes implementing Statement, PreparedStatement, * and CallableStatement, which would have to be updated for every JDK rev, * use a dynamic proxy to handle all calls through the Statement * interfaces. This is the part that requires JDK 1.3 or higher, though * JDK 1.2 could be supported with a 3rd-party proxy package. * * The StatementHandler is required in order to return the proper * Connection proxy for the getConnection method. */ private class StatementHandler implements InvocationHandler { private AbstractJdbc23PooledConnection.ConnectionHandler con; private Statement st; public StatementHandler(AbstractJdbc23PooledConnection.ConnectionHandler con, Statement st) { this.con = con; this.st = st; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // From Object if (method.getDeclaringClass().getName().equals("java.lang.Object")) { if (method.getName().equals("toString")) { return "Pooled statement wrapping physical statement " + st; } if (method.getName().equals("hashCode")) { return new Integer(st.hashCode()); } if (method.getName().equals("equals")) { if (args[0] == null) { return Boolean.FALSE; } try { return Proxy.isProxyClass(args[0].getClass()) && ((StatementHandler) Proxy.getInvocationHandler(args[0])).st == st ? Boolean.TRUE : Boolean.FALSE; } catch (ClassCastException e) { return Boolean.FALSE; } } return method.invoke(st, args); } // All the rest is from the Statement interface if (method.getName().equals("close")) { // closing an already closed object is a no-op if (st == null || con.isClosed()) return null; try { st.close(); } finally { con = null; st = null; } return null; } if (st == null || con.isClosed()) { throw new PSQLException(GT.tr("Statement has been closed."), PSQLState.OBJECT_NOT_IN_STATE); } if (method.getName().equals("getConnection")) { return con.getProxy(); // the proxied connection, not a physical connection } try { return method.invoke(st, args); } catch (InvocationTargetException e) { Throwable te = e.getTargetException(); if (te instanceof SQLException) fireConnectionError((SQLException)te); // Tell listeners about exception if it's fatal throw te; } } } }
package geopackage; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Random; import org.junit.Test; import com.rgi.android.geopackage.utility.DatabaseUtility; /** * @author Jenifer Cochran * */ @SuppressWarnings("static-method") public class DatabaseUtilityTest { private final Random randomGenerator = new Random(); /** * Tests if the DatabaseUtility will return the expected application Id. * * @throws SQLException * throws if an SQLException occurs * @throws Exception * can throw an SecurityException when accessing the file and * other various Exceptions */ @Test public void getApplicationID() throws SQLException, Exception { final File testFile = this.getRandomFile(4); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { final int appId = DatabaseUtility.getApplicationId(con); assertTrue("DatabaseUtility did not return the expected application Id.",appId == 0); } finally { con.close(); this.deleteFile(testFile); } } /** * Tests if the application Id can be set correctly through the * DatabaseUtility * * @throws SQLException * throws if an SQLException occurs * @throws Exception * throws if cannot access file */ @Test public void setApplicationID() throws SQLException, Exception { final File testFile = this.getRandomFile(4); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { DatabaseUtility.setApplicationId(con, 12345); assertTrue("DatabaseUtility did not return the expected application Id.", DatabaseUtility.getApplicationId(con) == 12345); } finally { this.deleteFile(testFile); } } /** * Verifies if the Database BoundsUtility setPragmaForeinKeys can set it to off. * * @throws Exception throws when an Exception occurs */ @Test public void databaseUtilitySetPragmaForiegnKeys() throws Exception { final File testFile = this.getRandomFile(5); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { //set it false using database utility DatabaseUtility.setPragmaForeignKeys(con, false); //pragma the database final String query = "PRAGMA foreign_keys;"; Statement stmt = con.createStatement(); try { ResultSet fkPragma = stmt.executeQuery(query); try { final int off = fkPragma.getInt("foreign_keys"); assertTrue("Database BoundsUtility set pragma foreign keys didn't set the foreign_keys to off when given the parameter false.", off == 0); } finally { fkPragma.close(); } } finally { stmt.close(); } } finally { con.close(); this.deleteFile(testFile); } } /** * Verifies if the Database BoundsUtility setPragmaForeinKeys can set it to on. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilitySetPragmaForiegnKeys2() throws Exception { final File testFile = this.getRandomFile(5); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { //set it false using database utility DatabaseUtility.setPragmaForeignKeys(con, true); //pragma the database final String query = "PRAGMA foreign_keys;"; Statement stmt = con.createStatement(); try { ResultSet fkPragma = stmt.executeQuery(query); try { final int on = fkPragma.getInt("foreign_keys"); assertTrue("Database BoundsUtility set pragma foreign keys didn't set the foreign_keys to on when given the parameter true.", on == 1); } finally { fkPragma.close(); } } finally { stmt.close(); } } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would accurately detect if a table * does not exists with the tableOrViewExists method. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilityTableorViewExists() throws Exception { final File testFile = this.getRandomFile(12); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { final boolean tableFound = DatabaseUtility.tableOrViewExists(con, "non_existant_table"); assertTrue("The Database BoundsUtility method table or view exists method returned true when it should have returned false.", !tableFound); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would accurately detect if a table * does exists with the tableOrViewExists method. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilityTableorViewExists2() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); final String tableName = "gpkg_tile_matrix"; Connection con = this.getConnection(testFile.getAbsolutePath()); try { this.addTable(con, tableName); assertTrue("The Database BoundsUtility method table or view exists method returned false when it should have returned true.", DatabaseUtility.tableOrViewExists(con, tableName)); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would accurately detect if a table * does exists with the tableOrViewExists method. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilityTableorViewExists3() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { final boolean tableFound = DatabaseUtility.tableOrViewExists(con, null); assertTrue("The Database BoundsUtility method table or view exists method returned true when it should have returned false.", !tableFound); } finally { con.close(); this.deleteFile(testFile); } } @Test(expected = IllegalArgumentException.class) public void databaseUtilityTableorViewExists4() throws Exception { DatabaseUtility.tableOrViewExists(null, null); fail("DatabaseUtility should have thrown an IllegalArgumentException when connection is null."); } @Test(expected = IllegalArgumentException.class) public void databaseUtilityTableorViewExists5() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { con.close(); DatabaseUtility.tableOrViewExists(con, null); fail("Database BoundsUtility should have thrown an IllegalArgumentException when given a closed connection."); } finally { this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would accurately detect if a table * does exists with the tablesOrViewsExists method. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilityTablesorViewsExists() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { final String tableName = "gpkg_tile_matrix"; this.addTable(con, tableName); final String[] tables = {tableName, "non_existant_table"}; assertTrue("The Database BoundsUtility method table or view exists method returned true when it should have returned false.", !DatabaseUtility.tablesOrViewsExists(con, tables)); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would accurately detect if a table * does exists with the tablesOrViewsExists method. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilityTablesorViewsExists2() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { final String tableName = "gpkg_tile_matrix"; this.addTable(con, tableName); final String[] tables = {tableName, tableName}; assertTrue("The Database BoundsUtility method table or view exists method returned false when it should have returned true.", DatabaseUtility.tablesOrViewsExists(con, tables)); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would accurately detect if a table * does exists with the tablesOrViewsExists method. * * @throws Exception * throws when an Exception occurs */ @Test public void databaseUtilityTablesorViewsExists3() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { final String tableName1 = "gpkg_tile_matrix"; final String tableName2 = "gpkg_contents"; this.addTable(con, tableName1); this.addTable(con, tableName2); final String[] tables = {tableName1, tableName2}; assertTrue("The Database BoundsUtility method table or view exists method returned false when it should have returned true.", DatabaseUtility.tablesOrViewsExists(con, tables)); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would throw an exception when * receiving a file that is less than 100 bytes. * * @throws Exception * throws when an Exception occurs */ @Test(expected= IllegalArgumentException.class) public void getSqliteVersion() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { DatabaseUtility.getSqliteVersion(testFile); fail("Expected an IllegalArgumentException from DatabaseUtility when gave an empty file to getSqliteVersion"); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility gets correct sqlite version of a * file. * * @throws Exception * throws when an Exception occurs */ @Test public void getSqliteVersion2() throws Exception { final File testFile = this.getRandomFile(3); testFile.createNewFile(); Connection con = this.getConnection(testFile.getAbsolutePath()); try { this.addTable(con, "foo"); final String sqliteVersion = DatabaseUtility.getSqliteVersion(testFile); assertTrue(String.format("The SQLite Version was different from expected. Expected: %s, Actual: %s", geopackageSqliteVersion, sqliteVersion), geopackageSqliteVersion.equals(sqliteVersion)); } finally { con.close(); this.deleteFile(testFile); } } /** * Checks to see if the Database BoundsUtility would throw an exception when * receiving a file that is null. * * @throws IOException * throws when DatabaseUtility cannot read sqliteVersion from a * file */ @Test(expected= IllegalArgumentException.class) public void getSqliteVersion3() throws IOException { DatabaseUtility.getSqliteVersion(null); fail("Expected an IllegalArgumentException from DatabaseUtility when gave file that was null to getSqliteVersion"); } /** * Checks to see if the Database BoundsUtility would throw an exception when * receiving a file that is null. * * @throws IOException * throws when DatabaseUtility cannot read sqliteVersion from a * file */ @Test(expected= FileNotFoundException.class) public void getSqliteVersion4() throws IOException { DatabaseUtility.getSqliteVersion(this.getRandomFile(4)); fail("Expected an IllegalArgumentException from DatabaseUtility when gave file that does not exist to getSqliteVersion"); } private Connection getConnection(final String filePath) throws Exception { Class.forName("org.sqlite.JDBC"); // Register the driver return DriverManager.getConnection("jdbc:sqlite:" + filePath); } private File getRandomFile(final int length) { File testFile; do { testFile = new File(String.format(FileSystems.getDefault().getPath(this.getRandomString(length)).toString() + ".gpkg")); } while (testFile.exists()); return testFile; } private String getRandomString(final int length) { final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; final char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(this.randomGenerator.nextInt(characters.length())); } return new String(text); } private void deleteFile(final File testFile) { if(testFile.exists()) { testFile.delete(); } } private void addTable(final Connection con, final String tableName) throws Exception { Statement statement = con.createStatement(); try { statement.executeUpdate("CREATE TABLE " + tableName + " (foo INTEGER);"); } finally { statement.close(); } } /** * The Sqlite version required for a GeoPackage shall contain SQLite 3 * format */ private final static String geopackageSqliteVersion = "3.8.7"; }
package org.jasig.portal.layout; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.Vector; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import org.apache.xpath.XPathAPI; import org.jasig.portal.IUserLayoutStore; import org.jasig.portal.PortalException; import org.jasig.portal.UserProfile; import org.jasig.portal.security.IPerson; import org.jasig.portal.services.LogService; import org.jasig.portal.utils.IPortalDocument; import org.jasig.portal.utils.XSLT; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; /** * An implementation of a user layout manager that uses 2.0-release store implementations. * * @author <a href="mailto:pkharchenko@interactivebusiness.com">Peter Kharchenko</a> * @version 1.0 */ public class SimpleUserLayoutManager implements IUserLayoutManager { protected final IPerson owner; protected final UserProfile profile; protected IUserLayoutStore store=null; protected Set listeners=new HashSet(); protected Document userLayoutDocument=null; protected Document markedUserLayout=null; protected static Random rnd=new Random(); protected String cacheKey="initialKey"; protected String rootNodeId; private boolean dirtyState=false; // marking mode variables private String markingMode=null; // null means markings are turned off private String markingNode; // The names for marking nodes private static final String ADD_COMMAND = "add"; private static final String MOVE_COMMAND = "move"; // marking stylesheet private static final String MARKING_XSLT_URI="/org/jasig/portal/layout/MarkUserLayout.xsl"; public SimpleUserLayoutManager(IPerson owner, UserProfile profile, IUserLayoutStore store) throws PortalException { if(owner==null) { throw new PortalException("A non-null owner needs to be specified."); } if(profile==null) { throw new PortalException("A non-null profile needs to be specified."); } this.owner=owner; this.profile=profile; this.rootNodeId = null; this.setLayoutStore(store); this.loadUserLayout(); this.markingMode=null; this.markingNode=null; } private void setUserLayoutDOM(Document doc) { this.userLayoutDocument=doc; this.markedUserLayout=null; this.updateCacheKey(); } public Document getUserLayoutDOM() { return this.userLayoutDocument; } public void getUserLayout(ContentHandler ch) throws PortalException { Document ulm=this.getUserLayoutDOM(); if(ulm==null) { throw new PortalException("User layout has not been initialized"); } else { getUserLayout(ulm,ch); } } public void getUserLayout(String nodeId, ContentHandler ch) throws PortalException { Document ulm=this.getUserLayoutDOM(); if(ulm==null) { throw new PortalException("User layout has not been initialized"); } else { Node rootNode=ulm.getElementById(nodeId); if(rootNode==null) { throw new PortalException("A requested root node (with id=\""+nodeId+"\") is not in the user layout."); } else { getUserLayout(rootNode,ch); } } } protected void getUserLayout(Node n,ContentHandler ch) throws PortalException { // do a DOM2SAX transformation, invoking marking transformation if necessary try { if(markingMode!=null) { Hashtable stylesheetParams=new Hashtable(1); stylesheetParams.put("operation",markingMode); if(markingNode!=null) { stylesheetParams.put("targetId",markingNode); } XSLT xslt=new XSLT(this); xslt.setXML(n); xslt.setTarget(ch); xslt.setStylesheetParameters(stylesheetParams); xslt.setXSL(MARKING_XSLT_URI); xslt.transform(); } else { Transformer emptyt=TransformerFactory.newInstance().newTransformer(); emptyt.transform(new DOMSource(n), new SAXResult(ch)); } } catch (Exception e) { throw new PortalException("Encountered an exception trying to output user layout",e); } } public void setLayoutStore(IUserLayoutStore store) { this.store=store; } protected IUserLayoutStore getLayoutStore() { return this.store; } public void loadUserLayout() throws PortalException { if(this.getLayoutStore()==null) { throw new PortalException("Store implementation has not been set."); } else { try { Document uli=this.getLayoutStore().getUserLayout(this.owner,this.profile); if(uli!=null) { this.setUserLayoutDOM(uli); clearDirtyFlag(); // inform listeners for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); lel.layoutLoaded(); } } else { throw new PortalException("Null user layout returned for ownerId=\""+owner.getID()+"\", profileId=\""+profile.getProfileId()+"\", layoutId=\""+profile.getLayoutId()+"\""); } } catch (PortalException pe) { throw pe; } catch (Exception e) { throw new PortalException("Exception encountered while reading a layout for userId="+this.owner.getID()+", profileId="+this.profile.getProfileId(),e); } } } public void saveUserLayout() throws PortalException{ if(isLayoutDirty()) { Document ulm=this.getUserLayoutDOM(); if(ulm==null) { throw new PortalException("UserLayout has not been initialized."); } else { if(this.getLayoutStore()==null) { throw new PortalException("Store implementation has not been set."); } else { try { this.getLayoutStore().setUserLayout(this.owner,this.profile,ulm,true); // inform listeners for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); lel.layoutSaved(); } } catch (PortalException pe) { throw pe; } catch (Exception e) { throw new PortalException("Exception encountered while trying to save a layout for userId="+this.owner.getID()+", profileId="+this.profile.getProfileId(),e); } } } } } public IUserLayoutNodeDescription getNode(String nodeId) throws PortalException { Document ulm=this.getUserLayoutDOM(); if(ulm==null) { throw new PortalException("UserLayout has not been initialized."); } // find an element with a given id Element element = (Element) ulm.getElementById(nodeId); if(element==null) { throw new PortalException("Element with ID=\""+nodeId+"\" doesn't exist."); } return UserLayoutNodeDescription.createUserLayoutNodeDescription(element); } public IUserLayoutNodeDescription addNode(IUserLayoutNodeDescription node, String parentId, String nextSiblingId) throws PortalException { boolean isChannel=false; IUserLayoutNodeDescription parent=this.getNode(parentId); if(canAddNode(node,parent,nextSiblingId)) { // assign new Id if(this.getLayoutStore()==null) { throw new PortalException("Store implementation has not been set."); } else { try { if(node instanceof IUserLayoutChannelDescription) { isChannel=true; node.setId(this.getLayoutStore().generateNewChannelSubscribeId(owner)); } else { node.setId(this.getLayoutStore().generateNewFolderId(owner)); } } catch (PortalException pe) { throw pe; } catch (Exception e) { throw new PortalException("Exception encountered while generating new usre layout node Id for userId="+this.owner.getID()); } } Document ulm=this.getUserLayoutDOM(); Element childElement=node.getXML(ulm); Element parentElement=(Element)ulm.getElementById(parentId); if(nextSiblingId==null) { parentElement.appendChild(childElement); } else { Node nextSibling=ulm.getElementById(nextSiblingId); parentElement.insertBefore(childElement,nextSibling); } markLayoutDirty(); // register element id if (ulm instanceof IPortalDocument) { ((IPortalDocument)ulm).putIdentifier( node.getId(),childElement); } else { StringBuffer msg = new StringBuffer(128); msg.append("SimpleUserLayoutManager::addNode() : "); msg.append("User Layout does not implement IPortalDocument, "); msg.append("so element caching cannot be performed."); LogService.log(LogService.ERROR, msg.toString()); } this.updateCacheKey(); this.clearMarkings(); // inform the listeners LayoutEvent ev=new LayoutEvent(this,node); for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); if(isChannel) { lel.channelAdded(ev); } else { lel.folderAdded(ev); } } return node; } return null; } public void clearMarkings() { markingMode=null; markingNode=null; } public boolean moveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException { IUserLayoutNodeDescription parent=this.getNode(parentId); IUserLayoutNodeDescription node=this.getNode(nodeId); String oldParentNodeId=getParentId(nodeId); if(canMoveNode(node,parent,nextSiblingId)) { // must be a folder Document ulm=this.getUserLayoutDOM(); Element childElement=(Element)ulm.getElementById(nodeId); Element parentElement=(Element)ulm.getElementById(parentId); if(nextSiblingId==null) { parentElement.appendChild(childElement); } else { Node nextSibling=ulm.getElementById(nextSiblingId); parentElement.insertBefore(childElement,nextSibling); } markLayoutDirty(); clearMarkings(); updateCacheKey(); // inform the listeners boolean isChannel=false; if(node instanceof IUserLayoutChannelDescription) { isChannel=true; } LayoutMoveEvent ev=new LayoutMoveEvent(this,node,oldParentNodeId); for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); if(isChannel) { lel.channelMoved(ev); } else { lel.folderMoved(ev); } } return true; } else { return false; } } public boolean deleteNode(String nodeId) throws PortalException { if(canDeleteNode(nodeId)) { IUserLayoutNodeDescription nodeDescription=this.getNode(nodeId); String parentNodeId=this.getParentId(nodeId); Document ulm=this.getUserLayoutDOM(); Element childElement=(Element)ulm.getElementById(nodeId); Node parent=childElement.getParentNode(); if(parent!=null) { parent.removeChild(childElement); } else { throw new PortalException("Node \""+nodeId+"\" has a NULL parent !"); } markLayoutDirty(); // clearMarkings(); // this one is questionable this.updateCacheKey(); // inform the listeners boolean isChannel=false; if(nodeDescription instanceof IUserLayoutChannelDescription) { isChannel=true; } LayoutMoveEvent ev=new LayoutMoveEvent(this,nodeDescription,parentNodeId); for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); if(isChannel) { lel.channelDeleted(ev); } else { lel.folderDeleted(ev); } } return true; } else { return false; } } public String getRootFolderId() { try { if ( rootNodeId == null ) { Element rootNode = (Element) XPathAPI.selectSingleNode(this.getUserLayoutDOM(),"//layout/folder"); rootNodeId = rootNode.getAttribute("ID"); } } catch ( Exception e ) { LogService.log(LogService.ERROR, e); } return rootNodeId; } public synchronized boolean updateNode(IUserLayoutNodeDescription node) throws PortalException { boolean isChannel=false; if(canUpdateNode(node)) { // normally here, one would determine what has changed // but we'll just make sure that the node type has not // changed and then regenerate the node Element from scratch, // and attach any children it might have had to it. String nodeId=node.getId(); String nextSiblingId=getNextSiblingId(nodeId); Element nextSibling=null; if(nextSiblingId!=null) { Document ulm=this.getUserLayoutDOM(); nextSibling=ulm.getElementById(nextSiblingId); } IUserLayoutNodeDescription oldNode=getNode(nodeId); if(oldNode instanceof IUserLayoutChannelDescription) { IUserLayoutChannelDescription oldChannel=(IUserLayoutChannelDescription) oldNode; if(node instanceof IUserLayoutChannelDescription) { isChannel=true; Document ulm=this.getUserLayoutDOM(); // generate new XML Element Element newChannelElement=node.getXML(ulm); Element oldChannelElement=(Element)ulm.getElementById(nodeId); Node parent=oldChannelElement.getParentNode(); parent.removeChild(oldChannelElement); parent.insertBefore(newChannelElement,nextSibling); // register new child instead if (ulm instanceof IPortalDocument) { ((IPortalDocument)ulm).putIdentifier( node.getId(),newChannelElement); } else { StringBuffer msg = new StringBuffer(128); msg.append("SimpleUserLayoutManager::updateNode() : "); msg.append("User Layout does not implement "); msg.append("IPortalDocument, "); msg.append("so element caching cannot be performed."); LogService.log(LogService.ERROR, msg.toString()); } // inform the listeners LayoutEvent ev=new LayoutEvent(this,node); for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); lel.channelUpdated(ev); } } else { throw new PortalException("Change channel to folder is not allowed by updateNode() method!"); } } else { // must be a folder IUserLayoutFolderDescription oldFolder=(IUserLayoutFolderDescription) oldNode; if(node instanceof IUserLayoutFolderDescription) { Document ulm=this.getUserLayoutDOM(); // generate new XML Element Element newFolderElement=node.getXML(ulm); Element oldFolderElement=(Element)ulm.getElementById(nodeId); Node parent=oldFolderElement.getParentNode(); // move children Vector children=new Vector(); for(Node n=oldFolderElement.getFirstChild(); n!=null;n=n.getNextSibling()) { children.add(n); } for(int i=0;i<children.size();i++) { newFolderElement.appendChild((Node)children.get(i)); } // replace the actual node parent.removeChild(oldFolderElement); parent.insertBefore(newFolderElement,nextSibling); // register new child instead if (ulm instanceof IPortalDocument) { ((IPortalDocument)ulm).putIdentifier( node.getId(), newFolderElement); } else { StringBuffer msg = new StringBuffer(128); msg.append("SimpleUserLayoutManager::updateNode() : "); msg.append("User Layout does not implement "); msg.append("IPortalDocument, "); msg.append("so element caching cannot be performed."); LogService.log(LogService.ERROR, msg.toString()); } // inform the listeners LayoutEvent ev=new LayoutEvent(this,node); for(Iterator i=listeners.iterator();i.hasNext();) { LayoutEventListener lel=(LayoutEventListener)i.next(); lel.folderUpdated(ev); } } } markLayoutDirty(); this.updateCacheKey(); return true; } else { return false; } } public boolean canAddNode(IUserLayoutNodeDescription node, String parentId, String nextSiblingId) throws PortalException { return this.canAddNode(node,this.getNode(parentId),nextSiblingId); } protected boolean canAddNode(IUserLayoutNodeDescription node,IUserLayoutNodeDescription parent, String nextSiblingId) throws PortalException { // make sure sibling exists and is a child of nodeId if(nextSiblingId!=null) { IUserLayoutNodeDescription sibling=getNode(nextSiblingId); if(sibling==null) { throw new PortalException("Unable to find a sibling node with id=\""+nextSiblingId+"\""); } if(!parent.getId().equals(getParentId(nextSiblingId))) { throw new PortalException("Given sibling (\""+nextSiblingId+"\") is not a child of a given parentId (\""+parent.getId()+"\")"); } } return (parent!=null && parent instanceof IUserLayoutFolderDescription && !parent.isImmutable()); } public boolean canMoveNode(String nodeId, String parentId,String nextSiblingId) throws PortalException { return this.canMoveNode(this.getNode(nodeId),this.getNode(parentId),nextSiblingId); } protected boolean canMoveNode(IUserLayoutNodeDescription node,IUserLayoutNodeDescription parent, String nextSiblingId) throws PortalException { // is the current parent immutable ? IUserLayoutNodeDescription currentParent=getNode(getParentId(node.getId())); if(currentParent==null) { throw new PortalException("Unable to determine a parent node for node with id=\""+node.getId()+"\""); } return (!currentParent.isImmutable() && canAddNode(node,parent,nextSiblingId)); } public boolean canDeleteNode(String nodeId) throws PortalException { return canDeleteNode(this.getNode(nodeId)); } protected boolean canDeleteNode(IUserLayoutNodeDescription node) throws PortalException { return !(node==null || node.isUnremovable()); } public boolean canUpdateNode(String nodeId) throws PortalException { return canUpdateNode(this.getNode(nodeId)); } public boolean canUpdateNode(IUserLayoutNodeDescription node) { return !(node==null || node.isImmutable()); } public void markAddTargets(IUserLayoutNodeDescription node) throws PortalException { if(node!=null) { this.markingMode=ADD_COMMAND; } else { clearMarkings(); } } public void markMoveTargets(String nodeId) throws PortalException { if(nodeId!=null) { this.markingMode=MOVE_COMMAND; this.markingNode=nodeId; } else { clearMarkings(); } } public String getParentId(String nodeId) throws PortalException { Document ulm=this.getUserLayoutDOM(); Element nelement=(Element)ulm.getElementById(nodeId); if(nelement!=null) { Node parent=nelement.getParentNode(); if(parent!=null) { if(parent.getNodeType()!=Node.ELEMENT_NODE) { throw new PortalException("Node with id=\""+nodeId+"\" is attached to something other then an element node."); } else { Element e=(Element) parent; return e.getAttribute("ID"); } } else { return null; } } else { throw new PortalException("Node with id=\""+nodeId+"\" doesn't exist."); } } public String getNextSiblingId(String nodeId) throws PortalException { Document ulm=this.getUserLayoutDOM(); Element nelement=(Element)ulm.getElementById(nodeId); if(nelement!=null) { Node nsibling=nelement.getNextSibling(); // scroll to the next element node while(nsibling!=null && nsibling.getNodeType()!=Node.ELEMENT_NODE){ nsibling=nsibling.getNextSibling(); } if(nsibling!=null) { Element e=(Element) nsibling; return e.getAttribute("ID"); } else { return null; } } else { throw new PortalException("Node with id=\""+nodeId+"\" doesn't exist."); } } public String getPreviousSiblingId(String nodeId) throws PortalException { Document ulm=this.getUserLayoutDOM(); Element nelement=(Element)ulm.getElementById(nodeId); if(nelement!=null) { Node nsibling=nelement.getPreviousSibling(); // scroll to the next element node while(nsibling!=null && nsibling.getNodeType()!=Node.ELEMENT_NODE){ nsibling=nsibling.getNextSibling(); } if(nsibling!=null) { Element e=(Element) nsibling; return e.getAttribute("ID"); } else { return null; } } else { throw new PortalException("Node with id=\""+nodeId+"\" doesn't exist."); } } public List getChildIds(String nodeId) throws PortalException { Vector v=new Vector(); IUserLayoutNodeDescription node=getNode(nodeId); if(node instanceof IUserLayoutFolderDescription) { Document ulm=this.getUserLayoutDOM(); Element felement=(Element)ulm.getElementById(nodeId); for(Node n=felement.getFirstChild(); n!=null;n=n.getNextSibling()) { if(n.getNodeType()==Node.ELEMENT_NODE) { Element e=(Element)n; if(e.getAttribute("ID")!=null) { v.add(e.getAttribute("ID")); } } } } return v; } public String getCacheKey() { if(markingMode==null) { return this.cacheKey; } else { if(markingNode!=null) { return this.cacheKey+this.markingMode+this.markingNode; } else { return this.cacheKey+this.markingMode; } } } /** * This is outright cheating ! We're supposed to analyze the user layout tree * and return a key that corresponds uniqly to the composition and the sturcture of the tree. * Here we just return a different key wheneever anything changes. So if one was to move a * node back and forth, the key would always never (almost) come back to the original value, * even though the changes to the user layout are cyclic. * */ private void updateCacheKey() { this.cacheKey=Long.toString(rnd.nextLong()); } public int getLayoutId() { return profile.getLayoutId(); } /** * Returns a subscription id given a functional name. * * @param fname the functional name to lookup. * @return a <code>String</code> subscription id. */ public String getSubscribeId(String fname){ try { Element fnameNode = (Element) XPathAPI.selectSingleNode(this.getUserLayoutDOM(),"//channel[@fname=\'"+fname+"\']"); if(fnameNode!=null) { return fnameNode.getAttribute("ID"); } else { return null; } } catch (Exception e) { LogService.log(LogService.ERROR, "SimpleUserLayoutManager::getSubcribeId() : encountered the following exception, while trying to identify subscribe channel id for the fname=\""+fname+"\" : "+e); e.printStackTrace(); return null; } } public boolean addLayoutEventListener(LayoutEventListener l) { return listeners.add(l); } public boolean removeLayoutEventListener(LayoutEventListener l) { return listeners.remove(l); } /** * A factory method to create an empty <code>IUserLayoutNodeDescription</code> instance * * @param nodeType a node type value * @return an <code>IUserLayoutNodeDescription</code> instance * @exception PortalException if the error occurs. */ public IUserLayoutNodeDescription createNodeDescription( int nodeType ) throws PortalException { switch ( nodeType ) { case IUserLayoutNodeDescription.FOLDER: return new UserLayoutFolderDescription(); case IUserLayoutNodeDescription.CHANNEL: return new UserLayoutChannelDescription(); default: return null; } } protected boolean isLayoutDirty() { return dirtyState; } private void markLayoutDirty() { dirtyState=true; } private void clearDirtyFlag() { dirtyState=false; } }
package org.jfree.chart.entity; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ParamChecks; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; /** * A standard implementation of the {@link EntityCollection} interface. */ public class StandardEntityCollection implements EntityCollection, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 5384773031184897047L; /** Storage for the entities. */ private List entities; /** * Constructs a new entity collection (initially empty). */ public StandardEntityCollection() { this.entities = new java.util.ArrayList(); } /** * Returns the number of entities in the collection. * * @return The entity count. */ public int getEntityCount() { return this.entities.size(); } /** * Returns a chart entity from the collection. * * @param index the entity index. * * @return The entity. * * @see #add(ChartEntity) */ public ChartEntity getEntity(int index) { return (ChartEntity) this.entities.get(index); } /** * Clears all the entities from the collection. */ public void clear() { this.entities.clear(); } /** * Adds an entity to the collection. * * @param entity the entity (<code>null</code> not permitted). */ public void add(ChartEntity entity) { ParamChecks.nullNotPermitted(entity, "entity"); this.entities.add(entity); } /** * Adds all the entities from the specified collection. * * @param collection the collection of entities (<code>null</code> not * permitted). */ public void addAll(EntityCollection collection) { this.entities.addAll(collection.getEntities()); } /** * Returns the last entity in the list with an area that encloses the * specified coordinates, or <code>null</code> if there is no such entity. * * @param x the x coordinate. * @param y the y coordinate. * * @return The entity (possibly <code>null</code>). */ public ChartEntity getEntity(double x, double y) { int entityCount = this.entities.size(); for (int i = entityCount - 1; i >= 0; i ChartEntity entity = (ChartEntity) this.entities.get(i); if (entity.getArea().contains(x, y)) { return entity; } } return null; } /** * Returns the entities in an unmodifiable collection. * * @return The entities. */ public Collection getEntities() { return Collections.unmodifiableCollection(this.entities); } /** * Returns an iterator for the entities in the collection. * * @return An iterator. */ public Iterator iterator() { return this.entities.iterator(); } /** * Tests this object for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof StandardEntityCollection) { StandardEntityCollection that = (StandardEntityCollection) obj; return ObjectUtilities.equal(this.entities, that.entities); } return false; } /** * Returns a clone of this entity collection. * * @return A clone. * * @throws CloneNotSupportedException if the object cannot be cloned. */ public Object clone() throws CloneNotSupportedException { StandardEntityCollection clone = (StandardEntityCollection) super.clone(); clone.entities = new java.util.ArrayList(this.entities.size()); for (int i = 0; i < this.entities.size(); i++) { ChartEntity entity = (ChartEntity) this.entities.get(i); clone.entities.add(entity.clone()); } return clone; } }
/** * A person on the map that can move around and interact within the saloon. */ package games.saloon; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.json.JSONObject; import joueur.Client; import joueur.BaseGame; import joueur.BaseGameObject; // <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional import(s) here // <<-- /Creer-Merge: imports -->> /** * A person on the map that can move around and interact within the saloon. */ public class Cowboy extends GameObject { /** * If the Cowboy can be moved this turn via its owner. */ public boolean canMove; /** * The direction this Cowboy is moving while drunk. Will be 'North', 'East', 'South', or 'West' when drunk; or '' (empty string) when not drunk. */ public String drunkDirection; /** * How much focus this Cowboy has. Different Jobs do different things with their Cowboy's focus. */ public int focus; /** * How much health this Cowboy currently has. */ public int health; /** * If this Cowboy is dead and has been removed from the game. */ public boolean isDead; /** * If this Cowboy is drunk, and will automatically walk. */ public boolean isDrunk; /** * The job that this Cowboy does, and dictates how they fight and interact within the Saloon. */ public String job; /** * The Player that owns and can control this Cowboy. */ public Player owner; /** * The Tile that this Cowboy is located on. */ public Tile tile; /** * How many times this unit has been drunk before taking their siesta and reseting this to 0. */ public int tolerance; /** * How many turns this unit has remaining before it is no longer busy and can `act()` or `play()` again. */ public int turnsBusy; // <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional field(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: fields -->> /** * Creates a new instance of a Cowboy. Used during game initialization, do not call directly. */ public Cowboy() { super(); } /** * Defaults the value for the optional arg 'drunkDirection' to '""' * * @see Cowboy#act(Tile, String) */ public boolean act(Tile tile) { return this.act(tile, ""); } /** * Does their job's action on a Tile. * * @param tile The Tile you want this Cowboy to act on. * @param drunkDirection The direction the bottle will cause drunk cowboys to be in, can be 'North', 'East', 'South', or 'West'. * @return True if the act worked, false otherwise. */ public boolean act(Tile tile, String drunkDirection) { JSONObject args = new JSONObject(); args.put("tile", Client.getInstance().gameManager.serializeSafe(tile)); args.put("drunkDirection", Client.getInstance().gameManager.serializeSafe(drunkDirection)); return (boolean)this.runOnServer("act", args); } /** * Moves this Cowboy from its current Tile to an adjacent Tile. * * @param tile The Tile you want to move this Cowboy to. * @return True if the move worked, false otherwise. */ public boolean move(Tile tile) { JSONObject args = new JSONObject(); args.put("tile", Client.getInstance().gameManager.serializeSafe(tile)); return (boolean)this.runOnServer("move", args); } /** * Sits down and plays a piano. * * @param piano The Furnishing that is a piano you want to play. * @return True if the play worked, false otherwise. */ public boolean play(Furnishing piano) { JSONObject args = new JSONObject(); args.put("piano", Client.getInstance().gameManager.serializeSafe(piano)); return (boolean)this.runOnServer("play", args); } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add addtional method(s) here. // <<-- /Creer-Merge: methods -->> }
package satori.metadata; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import satori.blob.SBlob; import satori.common.SException; import satori.type.SBlobType; import satori.type.SSizeType; import satori.type.STextType; import satori.type.STimeType; import satori.type.SType; public class SJudgeParser { @SuppressWarnings("serial") public static class ParseException extends SException { ParseException(String msg) { super(msg); } ParseException(Exception ex) { super(ex); } } private static SInputMetadata parseInputParam(Element node) throws ParseException { String type_str = node.getAttribute("type"); if (type_str.isEmpty()) throw new ParseException("Input type undefined"); SType type; if (type_str.equals("text")) type = STextType.INSTANCE; else if (type_str.equals("time")) type = STimeType.INSTANCE; else if (type_str.equals("size")) type = SSizeType.INSTANCE; else if (type_str.equals("blob")) type = SBlobType.INSTANCE; else throw new ParseException("Unsupported input type: " + type_str); String name = node.getAttribute("name"); if (name.isEmpty()) throw new ParseException("Input name undefined"); String desc = node.getAttribute("description"); if (desc.isEmpty()) throw new ParseException("Input description undefined"); String required = node.getAttribute("required"); if (required.isEmpty()) throw new ParseException("Input required mode undefined"); if (!required.equals("true") && !required.equals("false")) throw new ParseException("Invalid input required mode: " + required); String def_value = node.getAttribute("default"); if (def_value.isEmpty()) def_value = null; if (def_value != null && type == SBlobType.INSTANCE) throw new ParseException("Default value for blob inputs not supported"); return new SInputMetadata(name, desc, type, required.equals("true"), def_value); } private static SOutputMetadata parseOutputParam(Element node) throws ParseException { String type_str = node.getAttribute("type"); if (type_str.isEmpty()) throw new ParseException("Output type undefined"); SType type; if (type_str.equals("text")) type = STextType.INSTANCE; else if (type_str.equals("time")) type = STimeType.INSTANCE; else if (type_str.equals("size")) type = SSizeType.INSTANCE; else if (type_str.equals("blob")) type = SBlobType.INSTANCE; else throw new ParseException("Unsupported output type: " + type_str); String name = node.getAttribute("name"); if (name.isEmpty()) throw new ParseException("Output name undefined"); String desc = node.getAttribute("description"); if (desc.isEmpty()) throw new ParseException("Output description undefined"); return new SOutputMetadata(name, desc, type); } private static List<SInputMetadata> parseInputs(Element node) throws ParseException { List<SInputMetadata> result = new ArrayList<SInputMetadata>(); NodeList children = node.getElementsByTagName("param"); for (int i = 0; i < children.getLength(); ++i) result.add(parseInputParam((Element)children.item(i))); return Collections.unmodifiableList(result); } private static void verifyInputs(List<SInputMetadata> inputs) throws ParseException { Set<String> names = new HashSet<String>(); for (SInputMetadata input : inputs) { if (input.getName().equals("judge")) throw new ParseException("Illegal input name: judge"); if (names.contains(input.getName())) throw new ParseException("Duplicate input name: " + input.getName()); names.add(input.getName()); } } private static List<SOutputMetadata> parseOutputs(Element node) throws ParseException { List<SOutputMetadata> result = new ArrayList<SOutputMetadata>(); NodeList children = node.getElementsByTagName("param"); for (int i = 0; i < children.getLength(); ++i) result.add(parseOutputParam((Element)children.item(i))); return Collections.unmodifiableList(result); } private static void verifyOutputs(List<SOutputMetadata> outputs) throws ParseException { Set<String> names = new HashSet<String>(); for (SOutputMetadata output : outputs) { if (names.contains(output.getName())) throw new ParseException("Duplicate output name: " + output.getName()); names.add(output.getName()); } } private static void parse(Document doc, SJudge judge) throws ParseException { doc.normalizeDocument(); Element node = doc.getDocumentElement(); judge.setName(node.getAttribute("name")); NodeList input_children = node.getElementsByTagName("input"); List<SInputMetadata> input_meta; if (input_children.getLength() == 0) input_meta = Collections.emptyList(); else if (input_children.getLength() == 1) input_meta = parseInputs((Element)input_children.item(0)); else throw new ParseException("Too many input groups"); verifyInputs(input_meta); NodeList output_children = node.getElementsByTagName("output"); judge.setInputMetadata(input_meta); List<SOutputMetadata> output_meta; if (output_children.getLength() == 0) output_meta = Collections.emptyList(); else if (output_children.getLength() == 1) output_meta = parseOutputs((Element)output_children.item(0)); else throw new ParseException("Too many output groups"); verifyOutputs(output_meta); judge.setOutputMetadata(output_meta); } private static void parse(String str, SJudge judge) throws ParseException { InputSource is = new InputSource(); is.setCharacterStream(new StringReader(str)); try { parse(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is), judge); } catch(IOException ex) { throw new ParseException(ex); } catch(SAXException ex) { throw new ParseException(ex); } catch(ParserConfigurationException ex) { throw new ParseException(ex); } } private static void parse(File file, SJudge judge) throws ParseException { StringBuilder xml = new StringBuilder(); LineIterator line_iter = null; try { line_iter = FileUtils.lineIterator(file); while (line_iter.hasNext()) { String line = line_iter.next(); if (line.startsWith("#@")) xml.append(line.substring(2)); } } catch(IOException ex) { throw new ParseException(ex); } finally { LineIterator.closeQuietly(line_iter); } parse(xml.toString(), judge); } private static Map<SBlob, SJudge> judges = new HashMap<SBlob, SJudge>(); public static SJudge parseJudge(SBlob judge) throws SException { if (judges.containsKey(judge)) return judges.get(judge); File file = judge.getFile(); boolean delete = false; if (file == null) { try { file = File.createTempFile("satori", null); } catch(IOException ex) { throw new SException(ex); } judge.saveLocal(file); delete = true; } SJudge result = new SJudge(); result.setBlob(judge); try { parse(file, result); } finally { if (delete) file.delete(); } judges.put(judge, result); return result; } }
package org.gem.calc; import java.io.File; import java.rmi.RemoteException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.collections.Closure; import org.opensha.commons.data.Site; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.commons.data.function.DiscretizedFuncAPI; import org.opensha.commons.geo.Location; import org.opensha.commons.geo.LocationList; import org.opensha.commons.geo.LocationUtils; import org.opensha.commons.param.DoubleParameter; import org.opensha.sha.calc.HazardCurveCalculator; import org.opensha.sha.earthquake.EqkRupForecastAPI; import org.opensha.sha.earthquake.ProbEqkRupture; import org.opensha.sha.earthquake.ProbEqkSource; import org.opensha.sha.earthquake.rupForecastImpl.GEM1.GEM1ERF; import org.opensha.sha.imr.ScalarIntensityMeasureRelationshipAPI; import org.opensha.sha.imr.param.OtherParams.StdDevTypeParam; import org.opensha.sha.imr.param.SiteParams.DepthTo2pt5kmPerSecParam; import org.opensha.sha.imr.param.SiteParams.Vs30_Param; import org.opensha.sha.util.TectonicRegionType; import static org.apache.commons.collections.CollectionUtils.forAllDo; import org.gem.calc.DisaggregationResult; import org.gem.hdf5.HDF5Util; public class DisaggregationCalculator { /** * Dataset for the full disagg matrix (for HDF5 ouput). */ public static final String FULLDISAGGMATRIX = "fulldisaggmatrix"; private final Double[] latBinLims; private final Double[] lonBinLims; private final Double[] magBinLims; private final Double[] epsilonBinLims; private static final TectonicRegionType[] tectonicRegionTypes = TectonicRegionType.values(); /** * Dimensions for matrices produced by this calculator, based on the length * of the bin limits passed to the constructor. */ private final long[] dims; /** * Used for checking that bin edge lists are not null; */ private static final Closure notNull = new Closure() { public void execute(Object o) { if (o == null) { throw new IllegalArgumentException("Bin edges should not be null"); } } }; /** * Used for checking that bin edge lists have a length greater than or equal * to 2. */ private static final Closure lenGE2 = new Closure() { public void execute(Object o) { if (o instanceof Object[]) { Object[] oArray = (Object[]) o; if (oArray.length < 2) { throw new IllegalArgumentException("Bin edge arrays must have a length >= 2"); } } } }; private static final Closure isSorted = new Closure() { public void execute(Object o) { if (o instanceof Object[]) { Object[] oArray = (Object[]) o; Object[] sorted = Arrays.copyOf(oArray, oArray.length); Arrays.sort(sorted); if (!Arrays.equals(sorted, oArray)) { throw new IllegalArgumentException("Bin edge arrays must arranged in ascending order"); } } } }; public DisaggregationCalculator( Double[] latBinEdges, Double[] lonBinEdges, Double[] magBinEdges, Double[] epsilonBinEdges) { List binEdges = Arrays.asList(latBinEdges, lonBinEdges, magBinEdges, epsilonBinEdges); // Validation for the bin edges: forAllDo(binEdges, notNull); forAllDo(binEdges, lenGE2); forAllDo(binEdges, isSorted); this.latBinLims = latBinEdges; this.lonBinLims = lonBinEdges; this.magBinLims = magBinEdges; this.epsilonBinLims = epsilonBinEdges; this.dims = new long[5]; this.dims[0] = this.latBinLims.length - 1; this.dims[1] = this.lonBinLims.length - 1; this.dims[2] = this.magBinLims.length - 1; this.dims[3] = this.epsilonBinLims.length - 1; this.dims[4] = tectonicRegionTypes.length; } /** * Compute the full disaggregation matrix and write it to an HDF5 file. * * The result is a DisaggregationResult object, containing the GMV, the full * 5D matrix, and the absolute path the HDF5 file. * * @param path directory where the matrix should be written to * @throws Exception */ public DisaggregationResult computeAndWriteMatrix( double lat, double lon, GEM1ERF erf, Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap, double poe, List<Double> imls, double vs30Value, double depthTo2pt5KMPS, String path) throws Exception { DisaggregationResult daResult = computeMatrix(lat, lon, erf, imrMap, poe, imls, vs30Value, depthTo2pt5KMPS); String fileName = UUID.randomUUID().toString() + ".h5"; String fullPath = new File(path, fileName).getAbsolutePath(); HDF5Util.writeMatrix(fullPath, FULLDISAGGMATRIX, dims, daResult.getMatrix()); daResult.setMatrixPath(fullPath); return daResult; } /** * Simplified computeMatrix method for convenient calls from the Python * code. */ public DisaggregationResult computeMatrix( double lat, double lon, GEM1ERF erf, Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap, double poe, List<Double> imls, double vs30Value, double depthTo2pt5KMPS) { Site site = new Site(new Location(lat, lon)); site.addParameter(new DoubleParameter(Vs30_Param.NAME, vs30Value)); site.addParameter(new DoubleParameter(DepthTo2pt5kmPerSecParam.NAME, depthTo2pt5KMPS)); DiscretizedFuncAPI hazardCurve = new ArbitrarilyDiscretizedFunc(); // initialize the hazard curve with the number of points == the number of IMLs for (double d : imls) { hazardCurve.set(d, 0.0); } try { HazardCurveCalculator hcc = new HazardCurveCalculator(); hcc.getHazardCurve(hazardCurve, site, imrMap, erf); } catch (RemoteException e) { throw new RuntimeException(e); } double minMag = (Double) erf.getParameter(GEM1ERF.MIN_MAG_NAME).getValue(); return computeMatrix(site, erf, imrMap, poe, hazardCurve, minMag); } public DisaggregationResult computeMatrix( Site site, EqkRupForecastAPI erf, Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap, double poe, DiscretizedFuncAPI hazardCurve, double minMag) // or just pass a List<double> of IML values and compute the curve inside here? { assertPoissonian(erf); assertNonZeroStdDev(imrMap); double disaggMatrix[][][][][] = new double[(int) dims[0]] [(int) dims[1]] [(int) dims[2]] [(int) dims[3]] [(int) dims[4]]; // value by which to normalize the final matrix double totalAnnualRate = 0.0; double logGMV = getGMV(hazardCurve, poe); for (int srcCnt = 0; srcCnt < erf.getNumSources(); srcCnt++) { ProbEqkSource source = erf.getSource(srcCnt); double totProb = source.computeTotalProbAbove(minMag); double totRate = -Math.log(1 - totProb); TectonicRegionType trt = source.getTectonicRegionType(); ScalarIntensityMeasureRelationshipAPI imr = imrMap.get(trt); imr.setSite(site); imr.setIntensityMeasureLevel(logGMV); for(int rupCnt = 0; rupCnt < source.getNumRuptures(); rupCnt++) { ProbEqkRupture rupture = source.getRupture(rupCnt); imr.setEqkRupture(rupture); Location location = closestLocation(rupture.getRuptureSurface().getLocationList(), site.getLocation()); double lat, lon, mag, epsilon; lat = location.getLatitude(); lon = location.getLongitude(); mag = rupture.getMag(); epsilon = imr.getEpsilon(); if (!allInRange(lat, lon, mag, epsilon)) { // one or more of the parameters is out of range; // skip this rupture continue; } int[] binIndices = getBinIndices(lat, lon, mag, epsilon, trt); double annualRate = totRate * imr.getExceedProbability() * rupture.getProbability(); disaggMatrix[binIndices[0]][binIndices[1]][binIndices[2]][binIndices[3]][binIndices[4]] += annualRate; totalAnnualRate += annualRate; } // end rupture loop } // end source loop disaggMatrix = normalize(disaggMatrix, totalAnnualRate); DisaggregationResult daResult = new DisaggregationResult(); daResult.setGMV(Math.exp(logGMV)); daResult.setMatrix(disaggMatrix); return daResult; } public boolean allInRange( double lat, double lon, double mag, double epsilon) { return inRange(this.latBinLims, lat) && inRange(this.lonBinLims, lon) && inRange(this.magBinLims, mag) && inRange(this.epsilonBinLims, epsilon); } public static void assertPoissonian(EqkRupForecastAPI erf) { for (int i = 0; i < erf.getSourceList().size(); i++) { ProbEqkSource source = erf.getSource(i); if (!source.isPoissonianSource()) { throw new RuntimeException( "Sources must be Poissonian. (Non-Poissonian source are not currently supported.)"); } } } public static void assertNonZeroStdDev( Map<TectonicRegionType, ScalarIntensityMeasureRelationshipAPI> imrMap) { for (ScalarIntensityMeasureRelationshipAPI imr : imrMap.values()) { String stdDevType = (String) imr.getParameter(StdDevTypeParam.NAME).getValue(); if (stdDevType.equalsIgnoreCase(StdDevTypeParam.STD_DEV_TYPE_NONE)) { throw new RuntimeException( "Attenuation relationship must have a non-zero standard deviation."); } } } public static boolean inRange(Double[] bins, Double value) { return value >= bins[0] && value < bins[bins.length - 1]; } /** * Figure out which bins each input parameter fits into. The returned array * of indices represent the 5 dimensional coordinates in the disaggregation * matrix. * @param lat * @param lon * @param mag * @param epsilon * @param trt */ public int[] getBinIndices( double lat, double lon, double mag, double epsilon, TectonicRegionType trt) { int[] result = new int[5]; result[0] = digitize(this.latBinLims, lat); result[1] = digitize(this.lonBinLims, lon); result[2] = digitize(this.magBinLims, mag); result[3] = digitize(this.epsilonBinLims, epsilon); result[4] = Arrays.asList(TectonicRegionType.values()).indexOf(trt); return result; } public static int digitize(Double[] bins, Double value) { for (int i = 0; i < bins.length - 1; i++) { if (value >= bins[i] && value < bins[i + 1]) { return i; } } throw new IllegalArgumentException( "Value '" + value + "' is outside the expected range"); } /** * Given a LocationList and a Location target, get the Location in the * LocationList which is closest to the target Location. * @param list * @param target * @return closest Location (in the input ListLocation) to the target */ public static Location closestLocation(LocationList list, Location target) { Location closest = null; double minDistance = Double.MAX_VALUE; for (Location loc : list) { double horzDist = LocationUtils.horzDistance(loc, target); double vertDist = LocationUtils.vertDistance(loc, target); double distance = Math.sqrt(Math.pow(horzDist, 2) + Math.pow(vertDist, 2)); if (distance < minDistance) { minDistance = distance; closest = loc; } } return closest; } /** * Extract a GMV (Ground Motion Value) for a given curve and PoE * (Probability of Exceedance) value. * * IML (Intensity Measure Level) values make up the X-axis of the curve. * IMLs are arranged in ascending order. The lower the IML value, the * higher the PoE value (Y value) on the curve. Thus, it is assumed that * hazard curves will always have a negative slope. * * If the input poe value is > the max Y value in the curve, extrapolate * and return the X value corresponding to the max Y value (the first Y * value). * If the input poe value is < the min Y value in the curve, extrapolate * and return the X value corresponding to the min Y value (the last Y * value). * Otherwise, interpolate an X value in the curve given the input PoE. * @param hazardCurve * @param poe Probability of Exceedance value * @return GMV corresponding to the input poe */ public static Double getGMV(DiscretizedFuncAPI hazardCurve, double poe) { if (poe > hazardCurve.getY(0)) { return hazardCurve.getX(0); } else if (poe < hazardCurve.getY(hazardCurve.getNum() - 1)) { return hazardCurve.getX(hazardCurve.getNum() - 1); } else { return hazardCurve.getFirstInterpolatedX(poe); } } /** * Normalize a 5D matrix by the given value. * @param matrix * @param normFactor */ public static double[][][][][] normalize(double[][][][][] matrix, double normFactor) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { for (int k = 0; k < matrix[i][j].length; k++) { for (int l = 0; l < matrix[i][j][k].length; l++) { for (int m = 0; m < matrix[i][j][k][l].length; m++) { matrix[i][j][k][l][m] /= normFactor; } } } } } return matrix; } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // 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 jodd.io; import static jodd.core.JoddCore.ioBufferSize; import jodd.core.JoddCore; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; /** * Optimized byte and character stream utilities. */ public class StreamUtil { /** * Closes silently the closable object. If it is <code>FLushable</code>, it * will be flushed first. No exception will be thrown if an I/O error occurs. */ public static void close(Closeable closeable) { if (closeable != null) { if (closeable instanceof Flushable) { try { ((Flushable)closeable).flush(); } catch (IOException ignored) { } } try { closeable.close(); } catch (IOException ignored) { } } } /** * Copies input stream to output stream using buffer. Streams don't have * to be wrapped to buffered, since copying is already optimized. */ public static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[ioBufferSize]; int count = 0; int read; while (true) { read = input.read(buffer, 0, ioBufferSize); if (read == -1) { break; } output.write(buffer, 0, read); count += read; } return count; } /** * Copies specified number of bytes from input stream to output stream using buffer. */ public static int copy(InputStream input, OutputStream output, int byteCount) throws IOException { int bufferSize = (byteCount > ioBufferSize) ? ioBufferSize : byteCount; byte[] buffer = new byte[bufferSize]; int count = 0; int read; while (byteCount > 0) { if (byteCount < bufferSize) { read = input.read(buffer, 0, byteCount); } else { read = input.read(buffer, 0, bufferSize); } if (read == -1) { break; } byteCount -= read; count += read; output.write(buffer, 0, read); } return count; } /** * Copies input stream to writer using buffer - using jodds default encoding. * * @see JoddCore#encoding */ public static void copy(InputStream input, Writer output) throws IOException { copy(input, output, JoddCore.encoding); } /** * Copies specified number of bytes from input stream to writer using buffer - using jodds default encoding. * * @see JoddCore#encoding */ public static void copy(InputStream input, Writer output, int byteCount) throws IOException { copy(input, output, JoddCore.encoding, byteCount); } /** * Copies input stream to writer using buffer and specified encoding. */ public static void copy(InputStream input, Writer output, String encoding) throws IOException { copy(new InputStreamReader(input, encoding), output); } /** * Copies specified number of bytes from input stream to writer using buffer and specified encoding. */ public static void copy(InputStream input, Writer output, String encoding, int byteCount) throws IOException { copy(new InputStreamReader(input, encoding), output, byteCount); } /** * Copies reader to writer using buffer. * Streams don't have to be wrapped to buffered, since copying is already optimized. */ public static int copy(Reader input, Writer output) throws IOException { char[] buffer = new char[ioBufferSize]; int count = 0; int read; while ((read = input.read(buffer, 0, ioBufferSize)) >= 0) { output.write(buffer, 0, read); count += read; } output.flush(); return count; } /** * Copies specified number of characters from reader to writer using buffer. */ public static int copy(Reader input, Writer output, int charCount) throws IOException { int bufferSize = (charCount > ioBufferSize) ? ioBufferSize : charCount; char[] buffer = new char[bufferSize]; int count = 0; int read; while (charCount > 0) { if (charCount < bufferSize) { read = input.read(buffer, 0, charCount); } else { read = input.read(buffer, 0, bufferSize); } if (read == -1) { break; } charCount -= read; count += read; output.write(buffer, 0, read); } return count; } /** * Copies reader to output stream using buffer - using jodd default encoding. * * @see JoddCore#encoding */ public static void copy(Reader input, OutputStream output) throws IOException { copy(input, output, JoddCore.encoding); } /** * Copies specified number of characters from reader to output stream using buffer - using jodd default encoding. * * @see JoddCore#encoding */ public static void copy(Reader input, OutputStream output, int charCount) throws IOException { copy(input, output, JoddCore.encoding, charCount); } /** * Copies reader to output stream using buffer and specified encoding. */ public static void copy(Reader input, OutputStream output, String encoding) throws IOException { Writer out = new OutputStreamWriter(output, encoding); copy(input, out); out.flush(); } /** * Copies specified number of characters from reader to output stream using buffer and specified encoding. */ public static void copy(Reader input, OutputStream output, String encoding, int charCount) throws IOException { Writer out = new OutputStreamWriter(output, encoding); copy(input, out, charCount); out.flush(); } /** * Reads all available bytes from InputStream as a byte array. * Uses <code>in.available()</code> to determine the size of input stream. * This is the fastest method for reading input stream to byte array, but * depends on stream implementation of <code>available()</code>. * Buffered internally. */ public static byte[] readAvailableBytes(InputStream in) throws IOException { int l = in.available(); byte[] byteArray = new byte[l]; int i = 0, j; while ((i < l) && (j = in.read(byteArray, i, l - i)) >= 0) { i +=j; } if (i < l) { throw new IOException("Failed to completely read input stream"); } return byteArray; } public static byte[] readBytes(InputStream input) throws IOException { FastByteArrayOutputStream output = new FastByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } public static byte[] readBytes(InputStream input, int byteCount) throws IOException { FastByteArrayOutputStream output = new FastByteArrayOutputStream(); copy(input, output, byteCount); return output.toByteArray(); } public static byte[] readBytes(Reader input) throws IOException { FastByteArrayOutputStream output = new FastByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } public static byte[] readBytes(Reader input, int byteCount) throws IOException { FastByteArrayOutputStream output = new FastByteArrayOutputStream(); copy(input, output, byteCount); return output.toByteArray(); } public static byte[] readBytes(Reader input, String encoding) throws IOException { FastByteArrayOutputStream output = new FastByteArrayOutputStream(); copy(input, output, encoding); return output.toByteArray(); } public static byte[] readBytes(Reader input, String encoding, int byteCount) throws IOException { FastByteArrayOutputStream output = new FastByteArrayOutputStream(); copy(input, output, encoding, byteCount); return output.toByteArray(); } public static char[] readChars(InputStream input) throws IOException { FastCharArrayWriter output = new FastCharArrayWriter(); copy(input, output); return output.toCharArray(); } public static char[] readChars(InputStream input, int charCount) throws IOException { FastCharArrayWriter output = new FastCharArrayWriter(); copy(input, output, charCount); return output.toCharArray(); } public static char[] readChars(InputStream input, String encoding) throws IOException { FastCharArrayWriter output = new FastCharArrayWriter(); copy(input, output, encoding); return output.toCharArray(); } public static char[] readChars(InputStream input, String encoding, int charCount) throws IOException { FastCharArrayWriter output = new FastCharArrayWriter(); copy(input, output, encoding, charCount); return output.toCharArray(); } public static char[] readChars(Reader input) throws IOException { FastCharArrayWriter output = new FastCharArrayWriter(); copy(input, output); return output.toCharArray(); } public static char[] readChars(Reader input, int charCount) throws IOException { FastCharArrayWriter output = new FastCharArrayWriter(); copy(input, output, charCount); return output.toCharArray(); } /** * Compares the content of two byte streams. * * @return <code>true</code> if the content of the first stream is equal * to the content of the second stream. */ public static boolean compare(InputStream input1, InputStream input2) throws IOException { if (!(input1 instanceof BufferedInputStream)) { input1 = new BufferedInputStream(input1); } if (!(input2 instanceof BufferedInputStream)) { input2 = new BufferedInputStream(input2); } int ch = input1.read(); while (ch != -1) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return (ch2 == -1); } /** * Compares the content of two character streams. * * @return <code>true</code> if the content of the first stream is equal * to the content of the second stream. */ public static boolean compare(Reader input1, Reader input2) throws IOException { if (!(input1 instanceof BufferedReader)) { input1 = new BufferedReader(input1); } if (!(input2 instanceof BufferedReader)) { input2 = new BufferedReader(input2); } int ch = input1.read(); while (ch != -1) { int ch2 = input2.read(); if (ch != ch2) { return false; } ch = input1.read(); } int ch2 = input2.read(); return (ch2 == -1); } }
public class Solution { public int maxSubArray(int[] A) { int max = Integer.MIN_VALUE, sum = 0; for (int a : A) { sum += a; if (sum > max) max = sum; if (sum < 0) sum = 0; } return max; } } /** * divide and conque */ public class Solution { public int maxSubArray(int[] A) { if (A.length == 0) return 0; return maxHelper(A, 0, A.length - 1); } private int maxHelper(int[] num, int low, int high) { if (low == high) return num[low]; int mid = low + (high - low) / 2; int leftans = maxHelper(num, low, mid); int rightans = maxHelper(num, mid + 1, high); int temp = 0, leftmax = Integer.MIN_VALUE, rightmax = Integer.MIN_VALUE; for (int i = mid; i >= low; i temp += num[i]; leftmax = Math.max(temp, leftmax); } temp = 0; for (int i = mid + 1; i <= high; i++) { temp += num[i]; rightmax = Math.max(temp, rightmax); } return Math.max(Math.max(leftans, rightans), leftmax+rightmax); } }
package com.google.refine.importers; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import org.odftoolkit.odfdom.doc.OdfDocument; import org.odftoolkit.odfdom.doc.table.OdfTable; import org.odftoolkit.odfdom.doc.table.OdfTableCell; import org.odftoolkit.odfdom.doc.table.OdfTableRow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.refine.ProjectMetadata; import com.google.refine.importing.ImportingJob; import com.google.refine.importing.ImportingUtilities; import com.google.refine.model.Cell; import com.google.refine.model.Project; import com.google.refine.model.Recon; import com.google.refine.model.ReconCandidate; import com.google.refine.model.Recon.Judgment; import com.google.refine.util.JSONUtilities; public class OdsImporter extends TabularImportingParserBase { final static Logger logger = LoggerFactory.getLogger("open office"); public OdsImporter() { super(true); } @Override public JSONObject createParserUIInitializationData( ImportingJob job, List<JSONObject> fileRecords, String format) { JSONObject options = super.createParserUIInitializationData(job, fileRecords, format); JSONArray sheetRecords = new JSONArray(); JSONUtilities.safePut(options, "sheetRecords", sheetRecords); OdfDocument odfDoc = null; try { JSONObject firstFileRecord = fileRecords.get(0); File file = ImportingUtilities.getFile(job, firstFileRecord); InputStream is = new FileInputStream(file); odfDoc = OdfDocument.loadDocument(is); List<OdfTable> tables = odfDoc.getTableList(); int sheetCount = tables.size(); boolean hasData = false; for (int i = 0; i < sheetCount; i++) { OdfTable sheet = tables.get(i); int rows = sheet.getRowCount(); JSONObject sheetRecord = new JSONObject(); JSONUtilities.safePut(sheetRecord, "name", sheet.getTableName()); JSONUtilities.safePut(sheetRecord, "rows", rows); if (hasData) { JSONUtilities.safePut(sheetRecord, "selected", false); } else if (rows > 0) { JSONUtilities.safePut(sheetRecord, "selected", true); hasData = true; } JSONUtilities.append(sheetRecords, sheetRecord); } } catch (FileNotFoundException e) { logger.info("File not found",e); } catch (Exception e) { // ODF throws *VERY* wide exceptions logger.info("Error reading ODF spreadsheet",e); } finally { if (odfDoc != null) { odfDoc.close(); } } return options; } @Override public void parseOneFile( Project project, ProjectMetadata metadata, ImportingJob job, String fileSource, InputStream inputStream, int limit, JSONObject options, List<Exception> exceptions ) { OdfDocument odfDoc; try { odfDoc = OdfDocument.loadDocument(inputStream); } catch (Exception e) { // Ugh! could they throw any wider exception? exceptions.add(e); return; } List<OdfTable> tables = odfDoc.getTableList(); int[] sheets = JSONUtilities.getIntArray(options, "sheets"); for (int sheetIndex : sheets) { final OdfTable table = tables.get(sheetIndex); final int lastRow = table.getRowCount(); TableDataReader dataReader = new TableDataReader() { int nextRow = 0; Map<String, Recon> reconMap = new HashMap<String, Recon>(); @Override public List<Object> getNextRowOfCells() throws IOException { if (nextRow > lastRow) { return null; } List<Object> cells = new ArrayList<Object>(); OdfTableRow row = table.getRowByIndex(nextRow++); if (row != null) { int lastCell = row.getCellCount(); for (int cellIndex = 0; cellIndex <= lastCell; cellIndex++) { Cell cell = null; OdfTableCell sourceCell = row.getCellByIndex(cellIndex); if (sourceCell != null) { cell = extractCell(sourceCell, reconMap); } cells.add(cell); } } return cells; } }; TabularImportingParserBase.readTable( project, metadata, job, dataReader, fileSource + "#" + table.getTableName(), limit, options, exceptions ); } } static protected Serializable extractCell(OdfTableCell cell) { // TODO: how can we tell if a cell contains an error? //String formula = cell.getFormula(); Serializable value = null; // "boolean", "currency", "date", "float", "percentage", "string" or "time" String cellType = cell.getValueType(); if ("boolean".equals(cellType)) { value = cell.getBooleanValue(); } else if ("float".equals(cellType)) { value = cell.getDoubleValue(); } else if ("date".equals(cellType)) { value = cell.getDateValue(); } else if ("currency".equals(cellType)) { value = cell.getCurrencyValue(); } else if ("percentage".equals(cellType)) { value = cell.getPercentageValue(); } else if ("string".equals(cellType)) { value = cell.getStringValue(); } else if (cellType == null) { value = cell.getDisplayText(); if ("".equals(value)) { value = null; } else { logger.info("Null cell type with non-empty value: " + value); } } else { logger.info("Unexpected cell type " + cellType); value = cell.getDisplayText(); } return value; } static protected Cell extractCell(OdfTableCell cell, Map<String, Recon> reconMap) { Serializable value = extractCell(cell); if (value != null) { Recon recon = null; String hyperlink = ""; // TODO: cell.getHyperlink(); if (hyperlink != null) { String url = hyperlink; // TODO: hyperlink.getAddress(); if (url.startsWith("http: url.startsWith("https: final String sig = "freebase.com/view"; int i = url.indexOf(sig); if (i > 0) { String id = url.substring(i + sig.length()); int q = id.indexOf('?'); if (q > 0) { id = id.substring(0, q); } int h = id.indexOf(' if (h > 0) { id = id.substring(0, h); } if (reconMap.containsKey(id)) { recon = reconMap.get(id); recon.judgmentBatchSize++; } else { recon = new Recon(0, null, null); recon.service = "import"; recon.match = new ReconCandidate(id, value.toString(), new String[0], 100); recon.matchRank = 0; recon.judgment = Judgment.Matched; recon.judgmentAction = "auto"; recon.judgmentBatchSize = 1; recon.addCandidate(recon.match); reconMap.put(id, recon); } } } } return new Cell(value, recon); } else { return null; } } }
package org.zstack.sdk; public class StackParameters { public java.lang.String paramName; public void setParamName(java.lang.String paramName) { this.paramName = paramName; } public java.lang.String getParamName() { return this.paramName; } public java.lang.String type; public void setType(java.lang.String type) { this.type = type; } public java.lang.String getType() { return this.type; } public java.lang.String defaultValue; public void setDefaultValue(java.lang.String defaultValue) { this.defaultValue = defaultValue; } public java.lang.String getDefaultValue() { return this.defaultValue; } public java.lang.String description; public void setDescription(java.lang.String description) { this.description = description; } public java.lang.String getDescription() { return this.description; } public java.lang.Boolean noEcho; public void setNoEcho(java.lang.Boolean noEcho) { this.noEcho = noEcho; } public java.lang.Boolean getNoEcho() { return this.noEcho; } public java.lang.String lable; public void setLable(java.lang.String lable) { this.lable = lable; } public java.lang.String getLable() { return this.lable; } public java.lang.String constraintDescription; public void setConstraintDescription(java.lang.String constraintDescription) { this.constraintDescription = constraintDescription; } public java.lang.String getConstraintDescription() { return this.constraintDescription; } public java.lang.String resourceType; public void setResourceType(java.lang.String resourceType) { this.resourceType = resourceType; } public java.lang.String getResourceType() { return this.resourceType; } }
import java.util.ArrayList; import java.util.Scanner; public class playGame { public static int play_game(Deck deck, ArrayList<String> playerDeck, ArrayList<String> dealerDeck, int bet, int insurance) { String usr; Scanner userIn = new Scanner(System.in); boolean playig = true; System.out.println("It is your turn."); while (playing) { System.out.println("Options:\nStand\nHit\nDouble\nSplit\nSurrender"); usr = userIn.nextLine(); if (usr.toLowerCase().equals("stand")) playing = false; else if (usr.toLowerCase().equals("hit")) hit(); // create this else if (usr.toLowerCase().equals("double")) player_double(); // create this else if (usr.toLowerCase().equals("split")) split(); // create this else if (usr.toLowerCase().equals("surrender")) surrneder(); // creat this else System.out.println("I dont understand that play"); } // play out the dealers turn // check who wins // return winnings } }
package kawa.standard; import kawa.lang.*; public class Scheme extends Interpreter { final void define_proc (Named proc) { define (proc.name (), proc); } final void define_proc (String name, Named proc) { if (proc.getName() == null) proc.setName(name); define(name, proc); } /* Define a procedure to be autoloaded. */ final void define_proc (String name, String className) { define (name, new AutoloadProcedure (name, className)); } /* Define a Syntax to be autoloaded. */ final void define_syntax (String name, String className) { define (name, new AutoloadSyntax (name, className)); } static Environment null_environment; static Environment r4_environment; static Environment r5_environment; static Environment kawa_environment; public static Syntax beginSyntax; public static Syntax defineSyntax; public static SpecialType byteType = new SpecialType ("byte", "B", 1, java.lang.Byte.TYPE); public static SpecialType shortType = new SpecialType ("short", "S", 2, java.lang.Short.TYPE); public static SpecialType intType = new SpecialType ("int", "I", 4, java.lang.Integer.TYPE); public static SpecialType longType = new SpecialType ("long", "J", 8, java.lang.Long.TYPE); public static SpecialType floatType = new SpecialType ("float", "F", 4, java.lang.Float.TYPE); public static SpecialType doubleType = new SpecialType ("double", "D", 8, java.lang.Double.TYPE); public static SpecialType booleanType = new SpecialType("boolean", "Z", 1, java.lang.Boolean.TYPE); public static SpecialType charType = new SpecialType("char", "C", 2, java.lang.Character.TYPE); public static synchronized Environment builtin () { if (kawa_environment == null) new Scheme (); return kawa_environment; } public void initScheme () { kawa.lang.Named proc; kawa.lang.Named syn; kawa.lang.Procedure2 eqv; kawa.lang.Procedure2 eq; kawa.lang.Procedure2 equal; // (null-environment) null_environment = new Environment (); null_environment.setName ("null-environment"); environ = null_environment; //-- Section 4.1 -- complete define (Interpreter.quote_sym, new kawa.lang.Quote ()); define ("define", defineSyntax = new kawa.standard.define()); define_syntax ("if", "kawa.standard.ifp"); define_syntax ("set!", "kawa.standard.set_b"); // Section 4.2 -- complete define_syntax ("cond", "kawa.lib.std_syntax"); define_syntax ("case", "kawa.lib.std_syntax"); define ("and", new kawa.standard.and_or (true)); define ("or", new kawa.standard.and_or (false)); define_syntax ("%let", "kawa.standard.let"); define_syntax ("let", "kawa.lib.std_syntax"); define_syntax ("let*", "kawa.lib.std_syntax"); define_syntax ("letrec", "kawa.standard.letrec"); define ("begin", beginSyntax = new kawa.standard.begin()); define_syntax ("do", "kawa.lib.std_syntax"); define_syntax ("delay", "kawa.lib.std_syntax"); define_proc ("%make-promise", "kawa.standard.make_promise"); define_syntax ("quasiquote", "kawa.standard.quasiquote"); //-- Section 5 -- complete [except for internal definitions] define_syntax ("lambda", "kawa.lang.Lambda"); // Appendix (and R5RS) define ("define-syntax", new kawa.standard.define_syntax ()); r4_environment = new Environment (null_environment); r4_environment.setName ("r4rs-environment"); environ = r4_environment; //-- Section 6.1 -- complete define_proc ("not", "kawa.standard.not"); define_proc ("boolean?", "kawa.standard.boolean_p"); //-- Section 6.2 -- complete eqv = new kawa.standard.eqv_p(); define_proc("eqv?", eqv); eq = new kawa.standard.eq_p(); define_proc("eq?", eq); equal = new kawa.standard.equal_p(); define_proc("equal?", equal); //-- Section 6.3 -- complete define_proc("pair?", "kawa.standard.pair_p"); define_proc("cons", kawa.standard.cons.consProcedure); define_proc ("car", "kawa.standard.car"); define_proc ("cdr", "kawa.standard.cdr"); define_proc ("set-car!", "kawa.standard.setcar_b"); define_proc ("set-cdr!", "kawa.standard.setcdr_b"); define_proc ("caar", "kawa.standard.cxr"); define_proc ("cadr", "kawa.standard.cxr"); define_proc ("cdar", "kawa.standard.cxr"); define_proc ("cddr", "kawa.standard.cxr"); define_proc ("caaar", "kawa.standard.cxr"); define_proc ("caadr", "kawa.standard.cxr"); define_proc ("cadar", "kawa.standard.cxr"); define_proc ("caddr", "kawa.standard.cxr"); define_proc ("cdaar", "kawa.standard.cxr"); define_proc ("cdadr", "kawa.standard.cxr"); define_proc ("cddar", "kawa.standard.cxr"); define_proc ("cdddr", "kawa.standard.cxr"); define_proc ("caaaar", "kawa.standard.cxr"); define_proc ("caaadr", "kawa.standard.cxr"); define_proc ("caadar", "kawa.standard.cxr"); define_proc ("caaddr", "kawa.standard.cxr"); define_proc ("cadaar", "kawa.standard.cxr"); define_proc ("cadadr", "kawa.standard.cxr"); define_proc ("caddar", "kawa.standard.cxr"); define_proc ("cadddr", "kawa.standard.cxr"); define_proc ("cdaaar", "kawa.standard.cxr"); define_proc ("cdaadr", "kawa.standard.cxr"); define_proc ("cdadar", "kawa.standard.cxr"); define_proc ("cdaddr", "kawa.standard.cxr"); define_proc ("cddaar", "kawa.standard.cxr"); define_proc ("cddadr", "kawa.standard.cxr"); define_proc ("cdddar", "kawa.standard.cxr"); define_proc ("cddddr", "kawa.standard.cxr"); define_proc ("null?", "kawa.standard.null_p"); define_proc ("list?", "kawa.standard.list_p"); define_proc ("list", "kawa.standard.list_v"); define_proc ("length", "kawa.standard.length"); define ("append", kawa.standard.append.appendProcedure); define_proc ("reverse", "kawa.standard.reverse"); define_proc ("list-tail", "kawa.standard.list_tail"); define_proc ("list-ref", "kawa.standard.list_ref"); proc = new kawa.standard.mem("memq",eq); define(proc.name (), proc); proc = new kawa.standard.mem("memv",eqv); define(proc.name (), proc); proc = new kawa.standard.mem("member",equal); define(proc.name (), proc); proc = new kawa.standard.ass("assq",eq); define(proc.name (), proc); proc = new kawa.standard.ass("assv",eqv); define(proc.name (), proc); proc = new kawa.standard.ass("assoc",equal); define(proc.name (), proc); //-- Section 6.4 -- complete, including slashified read/write define_proc ("symbol?", "kawa.standard.symbol_p"); define_proc ("symbol->string", "kawa.standard.symbol2string"); define_proc ("string->symbol", "kawa.standard.string2symbol"); //-- Section 6.5 define_proc ("number?", "kawa.lib.numbers"); define_proc ("quantity?", "kawa.lib.number"); define_proc ("complex?", "kawa.lib.numbers"); define_proc ("real?", "kawa.lib.numbers"); define_proc ("rational?", "kawa.lib.numbers"); define_proc ("integer?", "kawa.standard.integer_p"); define_proc ("exact?", "kawa.standard.exact_p"); define_proc ("inexact?", "kawa.standard.inexact_p"); define_proc ("=", "kawa.standard.equal_oper"); define_proc ("<", "kawa.standard.less_oper"); define_proc (">", "kawa.standard.greater_oper"); define_proc ("<=", "kawa.standard.lessequal_oper"); define_proc (">=", "kawa.standard.greaterequal_oper"); define_proc ("zero?", "kawa.lib.numbers"); define_proc ("positive?", "kawa.standard.positive_p"); define_proc ("negative?", "kawa.standard.negative_p"); define_proc ("odd?", "kawa.standard.odd_p"); define_proc ("even?", "kawa.standard.even_p"); define_proc ("max", "kawa.standard.max"); define_proc ("min", "kawa.standard.min"); define_proc ("+", "kawa.standard.plus_oper"); define_proc ("-", "kawa.standard.minus_oper"); define_proc ("*", "kawa.standard.multiply_oper"); define_proc ("/", "kawa.standard.divide_oper"); define_proc ("abs", "kawa.lib.numbers"); define_proc ("quotient", "kawa.lib.numbers"); define_proc ("remainder", "kawa.lib.numbers"); define_proc ("modulo", "kawa.standard.modulo"); define_proc ("gcd", "kawa.standard.gcd"); define_proc ("lcm", "kawa.standard.lcm"); define_proc ("numerator", "kawa.lib.numbers"); define_proc ("denominator", "kawa.lib.numbers"); define_proc ("floor", "kawa.standard.floor"); define_proc ("ceiling", "kawa.standard.ceiling"); define_proc ("truncate", "kawa.standard.truncate"); define_proc ("round", "kawa.standard.round"); define_proc ("rationalize", "kawa.standard.rationalize"); define_proc ("exp", "kawa.lib.numbers"); define_proc ("log", "kawa.lib.numbers"); define_proc ("sin", "kawa.standard.sin"); define_proc ("cos", "kawa.standard.cos"); define_proc ("tan", "kawa.standard.tan"); define_proc ("asin", "kawa.standard.asin"); define_proc ("acos", "kawa.standard.acos"); define_proc ("atan", "kawa.standard.atan"); define_proc ("sqrt", "kawa.standard.sqrt"); define_proc ("expt", "kawa.standard.expt"); define_proc ("make-rectangular", "kawa.lib.numbers"); define_proc ("make-polar", "kawa.lib.numbers"); define_proc ("real-part", "kawa.lib.numbers"); define_proc ("imag-part", "kawa.lib.numbers"); define_proc ("magnitude", "kawa.lib.numbers"); define_proc ("angle", "kawa.lib.numbers"); define_proc ("exact->inexact", "kawa.standard.exact2inexact"); define_proc ("inexact->exact", "kawa.standard.inexact2exact"); define_proc ("number->string", "kawa.standard.number2string"); define_proc ("string->number", "kawa.standard.string2number"); //-- Section 6.6 -- complete define_proc ("char?", "kawa.lib.characters"); define_proc ("char=?", "kawa.standard.char_equal_p"); define_proc ("char<?", "kawa.standard.char_less_p"); define_proc ("char>?", "kawa.standard.char_greater_p"); define_proc ("char<=?", "kawa.standard.char_less_equal_p"); define_proc ("char>=?", "kawa.standard.char_greater_equal_p"); define_proc ("char-ci=?", "kawa.standard.char_ci_equal_p"); define_proc ("char-ci<?", "kawa.standard.char_ci_less_p"); define_proc ("char-ci>?", "kawa.standard.char_ci_greater_p"); define_proc ("char-ci<=?", "kawa.standard.char_ci_less_equal_p"); define_proc ("char-ci>=?", "kawa.standard.char_ci_greater_equal_p"); define_proc ("char-alphabetic?", "kawa.standard.char_alphabetic_p"); define_proc ("char-numeric?", "kawa.lib.characters"); define_proc ("char-whitespace?", "kawa.lib.characters"); define_proc ("char-upper-case?", "kawa.lib.characters"); define_proc ("char-lower-case?", "kawa.lib.characters"); define_proc ("char->integer", "kawa.lib.characters"); define_proc ("integer->char", "kawa.lib.characters"); define_proc ("char-upcase", "kawa.lib.characters"); define_proc ("char-downcase", "kawa.lib.characters"); //-- Section 6.7 -- complete define_proc ("string?", "kawa.standard.string_p"); define_proc ("make-string", "kawa.lib.strings"); define_proc ("string", "kawa.standard.string_v"); define_proc ("string-length", "kawa.lib.strings"); define_proc ("string-ref", "kawa.standard.string_ref"); define_proc ("string-set!", "kawa.standard.string_set_b"); define_proc ("string=?", "kawa.standard.string_equal_p"); define_proc ("string-ci=?", "kawa.standard.string_ci_equal_p"); define_proc ("string<?", "kawa.standard.string_lessthan_p"); define_proc ("string>?", "kawa.standard.string_greaterthan_p"); define_proc ("string<=?", "kawa.standard.string_lessequal_p"); define_proc ("string>=?", "kawa.standard.string_greaterequal_p"); define_proc ("string-ci<?", "kawa.standard.string_ci_lessthan_p"); define_proc ("string-ci>?", "kawa.standard.string_ci_greaterthan_p"); define_proc ("string-ci<=?", "kawa.standard.string_ci_lessequal_p"); define_proc ("string-ci>=?", "kawa.standard.string_ci_greaterequal_p"); define_proc ("substring", "kawa.lib.strings"); define_proc ("string-append", "kawa.standard.string_append"); define_proc ("string->list", "kawa.standard.string2list"); define_proc ("list->string", "kawa.standard.list2string"); define_proc ("string-copy", "kawa.lib.strings"); define_proc ("string-fill!", "kawa.lib.strings"); //-- Section 6.8 -- complete define_proc ("vector?", "kawa.lib.vectors"); define_proc ("make-vector", "kawa.standard.make_vector"); define ("vector", kawa.standard.vector_v.vectorProcedure); define_proc ("vector-length", "kawa.lib.vectors"); define_proc ("vector-ref", "kawa.lib.vectors"); define_proc ("vector-set!", "kawa.lib.vectors"); define_proc ("list->vector", "kawa.lib.vectors"); define_proc ("vector->list", "kawa.standard.vector2list"); define_proc ("vector-fill!", "kawa.standard.vector_fill_b"); // Extension: define ("vector-append", kawa.standard.vector_append.vappendProcedure); //-- Section 6.9 -- complete [except restricted call/cc] define_proc ("procedure?", "kawa.standard.procedure_p"); define_proc ("apply", "kawa.standard.apply"); define_proc (new map (true)); // map define_proc (new map (false)); // for-each define_proc ("call-with-current-continuation", "kawa.standard.callcc"); define_proc ("force", "kawa.standard.force"); //-- Section 6.10 [complete except for transcript-on/off] define_proc ("call-with-input-file", "kawa.standard.call_with_input_file"); define_proc ("call-with-output-file", "kawa.standard.call_with_output_file"); define_proc ("input-port?", "kawa.standard.input_port_p"); define_proc ("output-port?", "kawa.standard.output_port_p"); define_proc ("current-input-port", "kawa.standard.current_input_port"); define_proc ("current-output-port", "kawa.standard.current_output_port"); define_proc ("with-input-from-file", "kawa.standard.with_input_from_file"); define_proc ("with-output-to-file", "kawa.standard.with_output_to_file"); define_proc ("open-input-file", "kawa.standard.open_input_file"); define_proc ("open-output-file", "kawa.standard.open_output_file"); define_proc ("close-input-port", "kawa.standard.close_input_port"); define_proc ("close-output-port", "kawa.standard.close_output_port"); define_proc ("read", "kawa.standard.read"); define_proc (new readchar (false)); // read-char define_proc (new readchar (true)); // peek-char define_proc ("eof-object?", "kawa.lib.ports"); define_proc ("char-ready?", "kawa.standard.char_ready_p"); define_proc (new write(true)); // write define_proc (new write(false)); // display define_proc ("write-char", "kawa.standard.writechar"); define_proc ("newline", "kawa.lib.ports"); define_proc ("load", "kawa.standard.load"); define_proc ("call-with-input-string", // Extension "kawa.standard.call_with_input_string"); define_proc ("call-with-output-string", // Extension "kawa.standard.call_with_output_string"); define_proc ("force-output", "kawa.lib.ports"); // Extension define_proc ("input-port-line-number", "kawa.lib.ports"); // Extension define_proc ("set-input-port-line-number!", "kawa.lib.ports"); define_proc ("input-port-column-number", "kawa.lib.ports"); define_proc ("input-port-read-state", "kawa.lib.ports"); define_proc ("default-prompter", "kawa.lib.ports"); define_proc ("input-port-prompter", "kawa.lib.ports"); define_proc ("set-input-port-prompter!", "kawa.lib.ports"); define_proc ("transcript-off", "kawa.lib.ports"); define_proc ("transcript-on", "kawa.lib.ports"); define_syntax ("%syntax-error", "kawa.standard.syntax_error"); r5_environment = new Environment (r4_environment); r5_environment.setName ("r5rs-environment"); environ = r5_environment; define_proc ("values", "kawa.standard.values_v"); define_proc ("call-with-values", "kawa.standard.call_with_values"); define_proc ("eval", "kawa.lang.Eval"); define_proc ("scheme-report-environment", "kawa.standard.scheme_env"); define_proc ("null-environment", "kawa.standard.null_env"); define_proc ("interaction-environment", "kawa.standard.user_env"); define_proc ("dynamic-wind", "kawa.lib.syntax"); kawa_environment = new Environment (r5_environment); environ = kawa_environment; define_proc ("exit", "kawa.lib.thread"); String sym = "arithmetic-shift"; proc = new AutoloadProcedure (sym, "kawa.standard.ashift"); define (sym, proc); define ("ash", proc); define_proc ("logand", "kawa.standard.logand"); define_proc ("logior", "kawa.standard.logior"); define_proc ("logxor", "kawa.standard.logxor"); define_proc ("lognot", "kawa.standard.lognot"); define_proc ("logop", "kawa.standard.logop"); define_proc ("logbit?", "kawa.standard.logbit_p"); define_proc ("logtest", "kawa.standard.logtest"); define_proc ("logcount", "kawa.standard.logcount"); define_proc ("bit-extract", "kawa.standard.bit_extract"); define_proc ("integer-length", "kawa.standard.int_length"); define_proc("primitive-virtual-method", new kawa.standard.prim_method(182)); define_proc("primitive-static-method", new kawa.standard.prim_method(184)); define_proc("primitive-interface-method", new kawa.standard.prim_method(185)); define_proc("primitive-constructor", new kawa.standard.prim_method(183)); define_proc("primitive-op1", new kawa.standard.prim_method()); define_proc("primitive-throw", new kawa.standard.prim_throw()); define_syntax("try-finally", "kawa.standard.try_finally"); define_syntax("try-catch", "kawa.standard.try_catch"); define_proc("throw", "kawa.standard.throw_name"); define_proc("catch", "kawa.lib.syntax"); define_proc("error", "kawa.lib.syntax"); define_proc("as", new kawa.standard.convert()); define_proc("instance?", new kawa.standard.instance()); define_proc("file-exists?", "kawa.lib.files"); define_proc("file-directory?", "kawa.lib.files"); define_proc("file-readable?", "kawa.lib.files"); define_proc("file-writable?", "kawa.lib.files"); define_proc("delete-file", "kawa.lib.files"); define_proc("rename-file", "kawa.lib.files"); define_proc("copy-file", "kawa.lib.files"); define_proc("create-directory", "kawa.lib.files"); define("port-char-encoding", Boolean.TRUE); // JDK 1.1 only: define_proc ("record-accessor", "kawa.lib.reflection"); define_proc ("record-modifier", "kawa.lib.reflection"); define_proc ("record-predicate", "kawa.lib.reflection"); define_proc ("record-constructor", "kawa.lib.reflection"); define_proc ("make-record-type", "kawa.lib.reflection"); define_proc ("record-type-descriptor", "kawa.lib.reflection"); define_proc ("record-type-name", "kawa.lib.reflection"); define_proc ("record-type-field-names", "kawa.lib.reflection"); define_proc ("record?", "kawa.lib.reflection"); define_syntax ("when", "kawa.lib.syntax"); //-- (when cond exp ...) define_syntax ("unless", "kawa.lib.syntax"); //-- (unless cond exp ...) define_syntax ("fluid-let", "kawa.lib.syntax"); define_proc ("compile-file", "kawa.lang.CompileFile"); define_proc ("load-compiled", "kawa.lang.loadcompiled"); define_proc ("environment-bound?", "kawa.lib.misc"); define_proc ("scheme-implementation-version", "kawa.lib.misc"); define_proc ("scheme-window", "kawa.lib.misc"); define_proc ("quantity->number", "kawa.standard.quantity2number"); define_proc ("quantity->unit", "kawa.standard.quantity2unit"); define_proc ("make-quantity", "kawa.standard.make_quantity"); define_syntax ("define-unit", "kawa.lib.quantities"); define_proc ("gentemp", "kawa.lib.syntax"); define_syntax ("defmacro", "kawa.lib.syntax"); define_syntax ("future", "kawa.lib.thread"); define_proc ("%make-future", "kawa.standard.make_future"); define_proc ("sleep", "kawa.standard.sleep"); define_proc ("keyword?", "kawa.lib.keywords"); define_proc ("keyword->string", "kawa.lib.keywords"); define_proc ("string->keyword", "kawa.lib.keywords"); } static int scheme_counter = 0; public Scheme () { if (kawa_environment == null) initScheme(); environ = new Environment (kawa_environment); environ.setName ("interaction-environment."+(++scheme_counter)); } public Scheme (Environment environ) { this.environ = environ; } /** Evalutate Scheme expressions from string. * @param string the string constaining Scheme expressions * @param env the Environment to evaluate the string in * @return result of last expression, or Interpreter.voidObject if none. */ public static Object eval (String string, Environment env) throws WrongArguments, WrongType, GenericError, UnboundSymbol { return eval (call_with_input_string.open_input_string (string), env); } public Object eval (String string) throws WrongArguments, WrongType, GenericError, UnboundSymbol { return eval(string, environ); } /** Evalutate Scheme expressions from stream. * @param port the port to read Scheme expressions from * @param env the Environment to evaluate the string in * @return result of last expression, or Interpreter.voidObject if none. */ public static Object eval (InPort port, Environment env) throws WrongArguments, WrongType, GenericError, UnboundSymbol { Translator tr = new Translator (env); return Eval.eval (CompileFile.read (port, tr), tr, env); } /** Evalutate Scheme expressions from an "S expression." * @param sexpr the S expression to evaluate * @param env the Environment to evaluate the string in * @return result of the expression. */ public static Object eval (Object sexpr, Environment env) throws UnboundSymbol, WrongArguments, WrongType, GenericError { return Eval.eval (sexpr, env); } public Object read (InPort in) throws java.io.IOException, kawa.lang.ReadError { return in.readSchemeObject(); } public void print (Object value, OutPort out) { if (value == Scheme.voidObject) return; if (value instanceof Values) { Object[] values = ((Values) value).values(); for (int i = 0; i < values.length; i++) { SFormat.print (values[i], out); out.println(); } } else { SFormat.print (value, out); out.println(); } out.flush(); } }
package de.tobject.findbugs; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import edu.umd.cs.findbugs.plugin.eclipse.util.MutexSchedulingRule; /** * @author Andrei */ public abstract class FindBugsJob extends Job { static { // we must run this stupid code in the UI thread Display.getDefault().asyncExec(new Runnable() { public void run() { PlatformUI.getWorkbench().getProgressService().registerIconForFamily( FindbugsPlugin.getDefault().getImageDescriptor("runFindbugs.png"), FindbugsPlugin.class); } }); } private final IResource resource; public static void cancelSimilarJobs(FindBugsJob job) { if(job.getResource() == null) { return; } Job[] jobs = Job.getJobManager().find(FindbugsPlugin.class); for (Job job2 : jobs) { if(job.getResource().equals(((FindBugsJob)job2).getResource())){ if(job2.getState() != Job.RUNNING) { job2.cancel(); } } } } public FindBugsJob(String name, IResource resource) { super(name); this.resource = resource; setRule(new MutexSchedulingRule(resource)); } public IResource getResource() { return resource; } @Override public boolean belongsTo(Object family) { return FindbugsPlugin.class == family; } public void scheduleInteractive() { setUser(true); setPriority(Job.INTERACTIVE); schedule(); } public void scheduleAsSystem() { setUser(false); setPriority(Job.BUILD); schedule(); } protected String createErrorMessage() { return getName() + " failed"; } abstract protected void runWithProgress(IProgressMonitor monitor) throws CoreException; @Override public IStatus run(IProgressMonitor monitor) { try { runWithProgress(monitor); } catch (OperationCanceledException e) { // Do nothing when operation cancelled. return Status.CANCEL_STATUS; } catch (CoreException ex) { FindbugsPlugin.getDefault().logException(ex, createErrorMessage()); return ex.getStatus(); } finally { monitor.done(); } return Status.OK_STATUS; } }
package aurelienribon.bodyeditor.ui; import aurelienribon.bodyeditor.Ctx; import aurelienribon.ui.components.ArStyle; import aurelienribon.ui.components.PaintedPanel; import aurelienribon.ui.components.TabPanel; import aurelienribon.ui.css.Style; import aurelienribon.ui.css.swing.SwingStyle; import aurelienribon.utils.io.HttpUtils; import aurelienribon.utils.ui.SwingHelper; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; import res.Res; public class MainWindow extends javax.swing.JFrame { public MainWindow() { setContentPane(new PaintedPanel()); initComponents(); SwingStyle.init(); ArStyle.init(); Style.registerCssClasses(getContentPane(), ".rootPanel"); Style.registerCssClasses(projectPanel, ".titledPanel", "#projectPanel"); Style.registerCssClasses(optionsPanel, ".titledPanel", "#optionsPanel"); Style.registerCssClasses(logoWebsiteLbl, ".brightlink"); Style.registerCssClasses(logoManualLbl, ".brightlink", ".bold"); Style.registerCssClasses(versionPanel, ".versionPanel"); Style.registerCssClasses(versionLabel, ".versionLabel"); Style.apply(getContentPane(), new Style(Res.getUrl("css/style.css"))); JLabel commingSoonLabel = new JLabel(Res.getImage("gfx/comingSoon.png")); JPanel dummyPanel = new JPanel(new BorderLayout()); dummyPanel.setBackground(Color.WHITE); dummyPanel.add(commingSoonLabel, BorderLayout.CENTER); objectsPanel.getModel().add(new RigidBodiesPanel(), "Rigid bodies", null, false); objectsPanel.getModel().add(dummyPanel, "Dynamic objects", null, false); objectsPanel.setHeaderLayout(TabPanel.LAYOUT_GRID); logoWebsiteLbl.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { SwingHelper.browse(MainWindow.this, "http: } }); logoManualLbl.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { SwingHelper.browse(MainWindow.this, "http: } }); addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { Ctx.bodies.select(null); Ctx.objects.select(null); } }); checkUpdates(); } public void setCanvas(Component canvas) { renderPanel.add(canvas, BorderLayout.CENTER); canvas.requestFocusInWindow(); } private void checkUpdates() { final String version = "2.9.2"; versionLabel.setText("v" + version + " (checking for updates)"); versionLabel.setIcon(Res.getImage("gfx/ic_loading.gif")); URL tmpUrl; try {tmpUrl = new URL("http: catch (MalformedURLException ex) {throw new RuntimeException(ex);} final URL url = tmpUrl; final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final HttpUtils.Callback callback = new HttpUtils.Callback() { @Override public void canceled() {} @Override public void updated(int length, int totalLength) {} @Override public void completed() { try {testUpdate(version, stream.toString("UTF-8"));} catch (UnsupportedEncodingException ex) {throw new RuntimeException(ex);} } @Override public void error(IOException ex) { versionLabel.setText("v" + version + " (connection error)"); versionLabel.setIcon(Res.getImage("gfx/ic_error.png")); } }; Timer timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { HttpUtils.downloadAsync(url, stream, callback); } }); timer.setRepeats(false); timer.start(); } private void testUpdate(String version, String str) { List<String> versions = Arrays.asList(str.split("\n")); int versionIdx = versions.indexOf(version); MouseListener mouseListener = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { SwingHelper.browse(MainWindow.this, "http://code.google.com/p/box2d-editor/"); } }; if (versionIdx == 0) { versionLabel.setText("v" + version + " (latest version)"); versionLabel.setIcon(Res.getImage("gfx/ic_ok.png")); } else if (versionIdx > 0) { versionLabel.setText("v" + version + " (new version available: v" + versions.get(0) + ")"); versionLabel.setIcon(Res.getImage("gfx/ic_warning.png")); versionLabel.addMouseListener(mouseListener); Style.unregisterAllCssClasses(versionLabel); Style.registerCssClasses(versionLabel, ".darklink"); Style.apply(versionLabel, new Style(Res.getUrl("css/style.css"))); } else { versionLabel.setText("v" + version + " (invalid update file)"); versionLabel.setIcon(Res.getImage("gfx/ic_error.png")); } } // Generated Stuff @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { sidePanel = new javax.swing.JPanel(); logoPanel = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); logoWebsiteLbl = new javax.swing.JLabel(); logoManualLbl = new javax.swing.JLabel(); projectPanel = new aurelienribon.bodyeditor.ui.ProjectPanel(); jPanel1 = new javax.swing.JPanel(); objectsPanel = new aurelienribon.ui.components.TabPanel(); versionPanel = new javax.swing.JPanel(); versionLabel = new javax.swing.JLabel(); renderPanel = new javax.swing.JPanel(); optionsPanel = new javax.swing.JPanel(); rigidBodiesOptionsPanel1 = new aurelienribon.bodyeditor.ui.RigidBodiesOptionsPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Physics Body Editor"); sidePanel.setOpaque(false); logoPanel.setOpaque(false); jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/gfx/title.png"))); // NOI18N logoWebsiteLbl.setText("<html><p align=\"right\">2012 - Aurelien Ribon<br/>www.aurelienribon.com</p>"); logoManualLbl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/gfx/ic_manual.png"))); // NOI18N logoManualLbl.setText("Manual"); javax.swing.GroupLayout logoPanelLayout = new javax.swing.GroupLayout(logoPanel); logoPanel.setLayout(logoPanelLayout); logoPanelLayout.setHorizontalGroup( logoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(logoPanelLayout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(logoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(logoWebsiteLbl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(logoManualLbl))) ); logoPanelLayout.setVerticalGroup( logoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(logoPanelLayout.createSequentialGroup() .addComponent(logoWebsiteLbl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(logoManualLbl)) .addComponent(jLabel10) ); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.BorderLayout()); jPanel1.add(objectsPanel, java.awt.BorderLayout.CENTER); versionPanel.setLayout(new java.awt.BorderLayout()); versionLabel.setText("..."); versionPanel.add(versionLabel, java.awt.BorderLayout.CENTER); jPanel1.add(versionPanel, java.awt.BorderLayout.SOUTH); javax.swing.GroupLayout sidePanelLayout = new javax.swing.GroupLayout(sidePanel); sidePanel.setLayout(sidePanelLayout); sidePanelLayout.setHorizontalGroup( sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(logoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(projectPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); sidePanelLayout.setVerticalGroup( sidePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(sidePanelLayout.createSequentialGroup() .addComponent(logoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(projectPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)) ); renderPanel.setLayout(new java.awt.BorderLayout()); optionsPanel.setLayout(new java.awt.CardLayout()); optionsPanel.add(rigidBodiesOptionsPanel1, "card2"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(sidePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(renderPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE) .addComponent(optionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(renderPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(optionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(sidePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel10; private javax.swing.JPanel jPanel1; private javax.swing.JLabel logoManualLbl; private javax.swing.JPanel logoPanel; private javax.swing.JLabel logoWebsiteLbl; private aurelienribon.ui.components.TabPanel objectsPanel; private javax.swing.JPanel optionsPanel; private aurelienribon.bodyeditor.ui.ProjectPanel projectPanel; private javax.swing.JPanel renderPanel; private aurelienribon.bodyeditor.ui.RigidBodiesOptionsPanel rigidBodiesOptionsPanel1; private javax.swing.JPanel sidePanel; private javax.swing.JLabel versionLabel; private javax.swing.JPanel versionPanel; // End of variables declaration//GEN-END:variables }
package com.cloud.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.apache.log4j.Logger; import com.cloud.api.ApiServer; import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ConfigurationServer; import com.cloud.server.ManagementServer; import com.cloud.utils.SerialVersionUID; import com.cloud.utils.component.ComponentLocator; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class CloudStartupServlet extends HttpServlet implements ServletContextListener { public static final Logger s_logger = Logger.getLogger(CloudStartupServlet.class.getName()); static final long serialVersionUID = SerialVersionUID.CloudStartupServlet; protected static ComponentLocator s_locator; @Override public void init() throws ServletException { // Save Configuration Values //ComponentLocator loc = ComponentLocator.getLocator(ConfigurationServer.Name); ConfigurationServer c = (ConfigurationServer)ComponentLocator.getComponent(ConfigurationServer.Name); //ConfigurationServer c = new ConfigurationServerImpl(); try { c.persistDefaultValues(); s_locator = ComponentLocator.getLocator(ManagementServer.Name); ManagementServer ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name); ApiServer.initApiServer(ms.getApiConfig()); } catch (InvalidParameterValueException ipve) { s_logger.error("Exception starting management server ", ipve); throw new ServletException (ipve.getMessage()); } catch (Exception e) { s_logger.error("Exception starting management server ", e); throw new ServletException (e.getMessage()); } } @Override public void contextInitialized(ServletContextEvent sce) { try { init(); } catch (ServletException e) { s_logger.error("Exception starting management server ", e); throw new RuntimeException(e); } } @Override public void contextDestroyed(ServletContextEvent sce) { } }
package com.cloud.upgrade.dao; import java.io.File; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.UUID; import org.apache.log4j.Logger; import com.cloud.offering.NetworkOffering; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; public class Upgrade2214to30 implements DbUpgrade { final static Logger s_logger = Logger.getLogger(Upgrade2214to30.class); @Override public String[] getUpgradableVersionRange() { return new String[] { "2.2.14", "3.0.0" }; } @Override public String getUpgradedVersion() { return "3.0.0"; } @Override public boolean supportsRollingUpgrade() { return true; } @Override public File[] getPrepareScripts() { String script = Script.findScript("", "db/schema-2214to30.sql"); if (script == null) { throw new CloudRuntimeException("Unable to find db/schema-2214to30.sql"); } return new File[] { new File(script) }; } @Override public void performDataMigration(Connection conn) { // encrypt data encryptData(conn); // drop keys dropKeysIfExist(conn); // physical network setup setupPhysicalNetworks(conn); // update domain network ref updateDomainNetworkRef(conn); // update redundant routers updateReduntantRouters(conn); // create service/provider map for network offerings createNetworkOfferingServices(conn); // create service/provider map for networks createNetworkServices(conn); } @Override public File[] getCleanupScripts() { String script = Script.findScript("", "db/schema-2214to30-cleanup.sql"); if (script == null) { throw new CloudRuntimeException("Unable to find db/schema-2214to30-cleanup.sql"); } return new File[] { new File(script) }; } private void setupPhysicalNetworks(Connection conn) { /** * for each zone: * add a p.network, use zone.vnet and zone.type * add default traffic types, pnsp and virtual router element in enabled state * set p.network.id in op_dc_vnet and vlan and user_ip_address * list guest networks for the zone, set p.network.id */ PreparedStatement pstmt = null; ResultSet rs = null; PreparedStatement pstmtUpdate = null; try { // Load all DataCenters String getNextNetworkSequenceSql = "SELECT value from sequence where name='physical_networks_seq'"; String advanceNetworkSequenceSql = "UPDATE sequence set value=value+1 where name='physical_networks_seq'"; pstmt = conn.prepareStatement("SELECT value FROM configuration where name = 'xen.public.network.device'"); rs = pstmt.executeQuery(); String xenPublicLabel = null; if (rs.next()) { xenPublicLabel = rs.getString(1); } rs.close(); pstmt.close(); pstmt = conn.prepareStatement("SELECT value FROM configuration where name = 'xen.private.network.device'"); rs = pstmt.executeQuery(); String xenPrivateLabel = null; if (rs.next()) { xenPrivateLabel = rs.getString(1); } rs.close(); pstmt.close(); pstmt = conn.prepareStatement("SELECT value FROM configuration where name = 'xen.storage.network.device1'"); rs = pstmt.executeQuery(); String xenStorageLabel = null; if (rs.next()) { xenStorageLabel = rs.getString(1); } rs.close(); pstmt.close(); pstmt = conn.prepareStatement("SELECT value FROM configuration where name = 'xen.guest.network.device'"); rs = pstmt.executeQuery(); String xenGuestLabel = null; if (rs.next()) { xenGuestLabel = rs.getString(1); } rs.close(); pstmt.close(); pstmt = conn.prepareStatement("SELECT id, domain_id, networktype, vnet, name FROM data_center"); rs = pstmt.executeQuery(); while (rs.next()) { long zoneId = rs.getLong(1); long domainId = rs.getLong(2); String networkType = rs.getString(3); String vnet = rs.getString(4); String zoneName = rs.getString(5); // add p.network PreparedStatement pstmt2 = conn.prepareStatement(getNextNetworkSequenceSql); ResultSet rsSeq = pstmt2.executeQuery(); rsSeq.next(); long physicalNetworkId = rsSeq.getLong(1); rsSeq.close(); pstmt2.close(); pstmt2 = conn.prepareStatement(advanceNetworkSequenceSql); pstmt2.executeUpdate(); pstmt2.close(); String uuid = UUID.randomUUID().toString(); String broadcastDomainRange = "POD"; if ("Advanced".equals(networkType)) { broadcastDomainRange = "ZONE"; } String values = null; values = "('" + physicalNetworkId + "'"; values += ",'" + uuid + "'"; values += ",'" + zoneId + "'"; values += ",'" + vnet + "'"; values += ",'" + domainId + "'"; values += ",'" + broadcastDomainRange + "'"; values += ",'Enabled'"; values += ",'" + zoneName + "-pNtwk'"; values += ")"; s_logger.debug("Adding PhysicalNetwork " + physicalNetworkId + " for Zone id " + zoneId); String sql = "INSERT INTO `cloud`.`physical_network` (id, uuid, data_center_id, vnet, domain_id, broadcast_domain_range, state, name) VALUES " + values; pstmtUpdate = conn.prepareStatement(sql); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add traffic types s_logger.debug("Adding PhysicalNetwork traffic types"); String insertTraficType = "INSERT INTO `cloud`.`physical_network_traffic_types` (physical_network_id, traffic_type, xen_network_label, uuid) VALUES ( ?, ?, ?, ?)"; pstmtUpdate = conn.prepareStatement(insertTraficType); pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setString(2, "Public"); pstmtUpdate.setString(3, xenPublicLabel); pstmtUpdate.setString(4, UUID.randomUUID().toString()); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); pstmtUpdate = conn.prepareStatement(insertTraficType); pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setString(2, "Management"); pstmtUpdate.setString(3, xenPrivateLabel); pstmtUpdate.setString(4, UUID.randomUUID().toString()); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); pstmtUpdate = conn.prepareStatement(insertTraficType); pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setString(2, "Storage"); pstmtUpdate.setString(3, xenStorageLabel); pstmtUpdate.setString(4, UUID.randomUUID().toString()); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); pstmtUpdate = conn.prepareStatement(insertTraficType); pstmtUpdate.setLong(1, physicalNetworkId); pstmtUpdate.setString(2, "Guest"); pstmtUpdate.setString(3, xenGuestLabel); pstmtUpdate.setString(4, UUID.randomUUID().toString()); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physical network service provider - VirtualRouter s_logger.debug("Adding PhysicalNetworkServiceProvider VirtualRouter"); String insertPNSP = "INSERT INTO `physical_network_service_providers` (`uuid`, `physical_network_id` , `provider_name`, `state` ," + "`destination_physical_network_id`, `vpn_service_provided`, `dhcp_service_provided`, `dns_service_provided`, `gateway_service_provided`," + "`firewall_service_provided`, `source_nat_service_provided`, `load_balance_service_provided`, `static_nat_service_provided`," + "`port_forwarding_service_provided`, `user_data_service_provided`, `security_group_service_provided`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; pstmtUpdate = conn.prepareStatement(insertPNSP); pstmtUpdate.setString(1, UUID.randomUUID().toString()); pstmtUpdate.setLong(2, physicalNetworkId); pstmtUpdate.setString(3, "VirtualRouter"); pstmtUpdate.setString(4, "Enabled"); pstmtUpdate.setLong(5, 0); pstmtUpdate.setInt(6, 1); pstmtUpdate.setInt(7, 1); pstmtUpdate.setInt(8, 1); pstmtUpdate.setInt(9, 1); pstmtUpdate.setInt(10, 1); pstmtUpdate.setInt(11, 1); pstmtUpdate.setInt(12, 1); pstmtUpdate.setInt(13, 1); pstmtUpdate.setInt(14, 1); pstmtUpdate.setInt(15, 1); pstmtUpdate.setInt(16, 0); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add virtual_router_element String fetchNSPid = "SELECT id from physical_network_service_providers where physical_network_id=" + physicalNetworkId; pstmt2 = conn.prepareStatement(fetchNSPid); ResultSet rsNSPid = pstmt2.executeQuery(); rsNSPid.next(); long nspId = rsNSPid.getLong(1); rsSeq.close(); pstmt2.close(); String insertRouter = "INSERT INTO `virtual_router_providers` (`nsp_id`, `uuid` , `type` , `enabled`) " + "VALUES (?,?,?,?)"; pstmtUpdate = conn.prepareStatement(insertRouter); pstmtUpdate.setLong(1, nspId); pstmtUpdate.setString(2, UUID.randomUUID().toString()); pstmtUpdate.setString(3, "VirtualRouter"); pstmtUpdate.setInt(4, 1); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to op_dc_vnet_alloc for this zone s_logger.debug("Adding PhysicalNetwork to op_dc_vnet_alloc"); String updateVnet = "UPDATE op_dc_vnet_alloc SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateVnet); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to vlan for this zone s_logger.debug("Adding PhysicalNetwork to VLAN"); String updateVLAN = "UPDATE vlan SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateVLAN); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to user_ip_address for this zone s_logger.debug("Adding PhysicalNetwork to user_ip_address"); String updateUsrIp = "UPDATE user_ip_address SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId; pstmtUpdate = conn.prepareStatement(updateUsrIp); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); // add physicalNetworkId to guest networks for this zone s_logger.debug("Adding PhysicalNetwork to networks"); String updateNet = "UPDATE networks SET physical_network_id = " + physicalNetworkId + " WHERE data_center_id = " + zoneId + " AND traffic_type = 'Guest'"; pstmtUpdate = conn.prepareStatement(updateNet); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); } } catch (SQLException e) { throw new CloudRuntimeException("Exception while adding PhysicalNetworks", e); } finally { if (pstmtUpdate != null) { try { pstmtUpdate.close(); } catch (SQLException e) { } } if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { } } } } private void encryptData(Connection conn) { encryptConfigValues(conn); encryptHostDetails(conn); encryptVNCPassword(conn); encryptUserCredentials(conn); } private void encryptConfigValues(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select name, value from configuration where category = 'Hidden'"); rs = pstmt.executeQuery(); while (rs.next()) { String name = rs.getString(1); String value = rs.getString(2); if (value == null) { continue; } String encryptedValue = DBEncryptionUtil.encrypt(value); pstmt = conn.prepareStatement("update configuration set value=? where name=?"); pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); pstmt.setString(2, name); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable encrypt configuration values ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt configuration values ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } private void encryptHostDetails(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, value from host_details where name = 'password'"); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String value = rs.getString(2); if (value == null) { continue; } String encryptedValue = DBEncryptionUtil.encrypt(value); pstmt = conn.prepareStatement("update host_details set value=? where id=?"); pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); pstmt.setLong(2, id); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable encrypt host_details values ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt host_details values ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } private void encryptVNCPassword(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, vnc_password from vm_instance"); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String value = rs.getString(2); if (value == null) { continue; } String encryptedValue = DBEncryptionUtil.encrypt(value); pstmt = conn.prepareStatement("update vm_instance set vnc_password=? where id=?"); pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); pstmt.setLong(2, id); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable encrypt vm_instance vnc_password ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt vm_instance vnc_password ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } private void encryptUserCredentials(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement("select id, secret_key from user"); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String secretKey = rs.getString(2); String encryptedSecretKey = DBEncryptionUtil.encrypt(secretKey); pstmt = conn.prepareStatement("update user set secret_key=? where id=?"); if (encryptedSecretKey == null) { pstmt.setNull(1, Types.VARCHAR); } else { pstmt.setBytes(1, encryptedSecretKey.getBytes("UTF-8")); } pstmt.setLong(2, id); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable encrypt user secret key ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable encrypt user secret key ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } private void dropKeysIfExist(Connection conn) { HashMap<String, List<String>> uniqueKeys = new HashMap<String, List<String>>(); List<String> keys = new ArrayList<String>(); keys.add("public_ip_address"); uniqueKeys.put("console_proxy", keys); uniqueKeys.put("secondary_storage_vm", keys); // drop keys s_logger.debug("Dropping public_ip_address keys from secondary_storage_vm and console_proxy tables..."); for (String tableName : uniqueKeys.keySet()) { DbUpgradeUtils.dropKeysIfExist(conn, tableName, uniqueKeys.get(tableName), true); } } private void createNetworkOfferingServices(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn .prepareStatement("select id, dns_service, gateway_service, firewall_service, lb_service, userdata_service, vpn_service, dhcp_service, unique_name from network_offerings where traffic_type='Guest'"); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String uniqueName = rs.getString(9); ArrayList<String> services = new ArrayList<String>(); if (rs.getLong(2) != 0) { services.add("Dns"); } if (rs.getLong(3) != 0) { services.add("Gateway"); } if (rs.getLong(4) != 0) { services.add("Firewall"); } if (rs.getLong(5) != 0) { services.add("Lb"); } if (rs.getLong(6) != 0) { services.add("UserData"); } if (rs.getLong(7) != 0) { services.add("Vpn"); } if (rs.getLong(8) != 0) { services.add("Dhcp"); } if (uniqueName.equalsIgnoreCase(NetworkOffering.DefaultSharedNetworkOfferingWithSGService.toString())) { services.add("SecurityGroup"); } if (uniqueName.equals(NetworkOffering.DefaultIsolatedNetworkOfferingWithSourceNatService.toString())) { services.add("SourceNat"); services.add("PortForwarding"); services.add("StaticNat"); } for (String service : services) { pstmt = conn.prepareStatement("INSERT INTO ntwk_offering_service_map (`network_offering_id`, `service`, `provider`, `created`) values (?,?,?, now())"); pstmt.setLong(1, id); pstmt.setString(2, service); if (service.equalsIgnoreCase("SecurityGroup")) { pstmt.setString(3, "SecurityGroupProvider"); } else { pstmt.setString(3, "VirtualRouter"); } pstmt.executeUpdate(); } } } catch (SQLException e) { throw new CloudRuntimeException("Unable to create service/provider map for network offerings", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } private void updateDomainNetworkRef(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; try { // update subdomain access field for existing domain specific networks pstmt = conn.prepareStatement("select value from configuration where name='allow.subdomain.network.access'"); rs = pstmt.executeQuery(); while (rs.next()) { boolean subdomainAccess = Boolean.valueOf(rs.getString(1)); pstmt = conn.prepareStatement("UPDATE domain_network_ref SET subdomain_access=?"); pstmt.setBoolean(1, subdomainAccess); pstmt.executeUpdate(); s_logger.debug("Successfully updated subdomain_access field in network_domain table with value " + subdomainAccess); } // convert zone level 2.2.x networks to ROOT domain 3.0 access networks pstmt = conn.prepareStatement("select id from networks where shared=true and is_domain_specific=false and traffic_type='Guest'"); rs = pstmt.executeQuery(); while (rs.next()) { long networkId = rs.getLong(1); pstmt = conn.prepareStatement("INSERT INTO domain_network_ref (domain_id, network_id, subdomain_access) VALUES (1, ?, 1)"); pstmt.setLong(1, networkId); pstmt.executeUpdate(); s_logger.debug("Successfully converted zone specific network id=" + networkId + " to the ROOT domain level network with subdomain access set to true"); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to update domain network ref", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } protected void createNetworkServices(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; ResultSet rs1 = null; try { pstmt = conn.prepareStatement("select id, network_offering_id from networks where traffic_type='Guest'"); rs = pstmt.executeQuery(); while (rs.next()) { long networkId = rs.getLong(1); long networkOfferingId = rs.getLong(2); pstmt = conn.prepareStatement("select service, provider from ntwk_offering_service_map where network_offering_id=?"); pstmt.setLong(1, networkOfferingId); rs1 = pstmt.executeQuery(); while (rs1.next()) { String service = rs1.getString(1); String provider = rs1.getString(2); pstmt = conn.prepareStatement("INSERT INTO ntwk_service_map (`network_id`, `service`, `provider`, `created`) values (?,?,?, now())"); pstmt.setLong(1, networkId); pstmt.setString(2, service); pstmt.setString(3, provider); pstmt.executeUpdate(); } s_logger.debug("Created service/provider map for network id=" + networkId); } } catch (SQLException e) { throw new CloudRuntimeException("Unable to create service/provider map for networks", e); } finally { try { if (rs != null) { rs.close(); } if (rs1 != null) { rs1.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } protected void updateReduntantRouters(Connection conn) { PreparedStatement pstmt = null; ResultSet rs = null; ResultSet rs1 = null; try { // get all networks that need to be updated to the redundant network offerings pstmt = conn .prepareStatement("select ni.network_id, n.network_offering_id from nics ni, networks n where ni.instance_id in (select id from domain_router where is_redundant_router=1) and n.id=ni.network_id and n.traffic_type='Guest'"); rs = pstmt.executeQuery(); pstmt = conn.prepareStatement("select count(*) from network_offerings"); rs1 = pstmt.executeQuery(); long ntwkOffCount = 0; while (rs1.next()) { ntwkOffCount = rs1.getLong(1); } s_logger.debug("Have " + ntwkOffCount + " networkOfferings"); pstmt = conn.prepareStatement("CREATE TEMPORARY TABLE network_offerings2 ENGINE=MEMORY SELECT * FROM network_offerings WHERE id=1"); pstmt.executeUpdate(); HashMap<Long, Long> newNetworkOfferingMap = new HashMap<Long, Long>(); while (rs.next()) { long networkId = rs.getLong(1); long networkOfferingId = rs.getLong(2); s_logger.debug("Updating network offering for the network id=" + networkId + " as it has redundant routers"); Long newNetworkOfferingId = null; if (!newNetworkOfferingMap.containsKey(networkOfferingId)) { // clone the record to pstmt = conn.prepareStatement("INSERT INTO network_offerings2 SELECT * FROM network_offerings WHERE id=?"); pstmt.setLong(1, networkOfferingId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("SELECT unique_name FROM network_offerings WHERE id=?"); pstmt.setLong(1, networkOfferingId); rs1 = pstmt.executeQuery(); String uniqueName = null; while (rs1.next()) { uniqueName = rs1.getString(1) + "-redundant"; } pstmt = conn.prepareStatement("UPDATE network_offerings2 SET id=?, redundant_router_service=1, unique_name=?, name=? WHERE id=?"); ntwkOffCount = ntwkOffCount + 1; newNetworkOfferingId = ntwkOffCount; pstmt.setLong(1, newNetworkOfferingId); pstmt.setString(2, uniqueName); pstmt.setString(3, uniqueName); pstmt.setLong(4, networkOfferingId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("INSERT INTO network_offerings SELECT * from network_offerings2 WHERE id=" + newNetworkOfferingId); pstmt.executeUpdate(); pstmt = conn.prepareStatement("UPDATE networks SET network_offering_id=? where id=?"); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); pstmt.executeUpdate(); newNetworkOfferingMap.put(networkOfferingId, ntwkOffCount); } else { pstmt = conn.prepareStatement("UPDATE networks SET network_offering_id=? where id=?"); newNetworkOfferingId = newNetworkOfferingMap.get(networkOfferingId); pstmt.setLong(1, newNetworkOfferingId); pstmt.setLong(2, networkId); pstmt.executeUpdate(); } s_logger.debug("Successfully updated network offering id=" + networkId + " with new network offering id " + newNetworkOfferingId); } pstmt = conn.prepareStatement("DROP TABLE network_offerings2"); pstmt.executeUpdate(); } catch (SQLException e) { throw new CloudRuntimeException("Unable to redundant router networks", e); } finally { try { if (rs != null) { rs.close(); } if (rs1 != null) { rs1.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } } }
package org.xtreemfs.osd.stages; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.xtreemfs.common.Capability; import org.xtreemfs.common.TimeSync; import org.xtreemfs.common.logging.Logging; import org.xtreemfs.common.xloc.InvalidXLocationsException; import org.xtreemfs.foundation.ErrNo; import org.xtreemfs.foundation.oncrpc.server.ONCRPCRequest; import org.xtreemfs.interfaces.OSDInterface.OSDException; import org.xtreemfs.interfaces.Exceptions.ProtocolException; import org.xtreemfs.interfaces.OSDInterface.OSDInterface; import org.xtreemfs.interfaces.utils.ONCRPCRequestHeader; import org.xtreemfs.interfaces.utils.ONCRPCResponseHeader; import org.xtreemfs.osd.ErrorCodes; import org.xtreemfs.osd.LocationsCache; import org.xtreemfs.osd.OSDRequest; import org.xtreemfs.osd.OSDRequestDispatcher; import org.xtreemfs.osd.OpenFileTable; import org.xtreemfs.osd.operations.EventCloseFile; import org.xtreemfs.osd.operations.OSDOperation; import org.xtreemfs.osd.storage.CowPolicy; public class PreprocStage extends Stage { public final static int STAGEOP_PARSE_AUTH_OFTOPEN = 1; public final static int STAGEOP_OFT_DELETE = 2; public final static int STAGEOP_ACQUIRE_LEASE = 3; public final static int STAGEOP_RETURN_LEASE = 4; public final static int STAGEOP_VERIFIY_CLEANUP = 5; private final static long OFT_CLEAN_INTERVAL = 1000 * 60; private final static long OFT_OPEN_EXTENSION = 1000 * 30; private final Map<String, Set<String>> capCache; private final OpenFileTable oft; // time left to next clean op private long timeToNextOFTclean; // last check of the OFT private long lastOFTcheck; private volatile long numRequests; /** * X-Location cache */ private final LocationsCache xLocCache; private final OSDRequestDispatcher master; private final boolean ignoreCaps; /** Creates a new instance of AuthenticationStage */ public PreprocStage(OSDRequestDispatcher master) { super("OSD PreProcSt"); capCache = new HashMap<String, Set<String>>(); oft = new OpenFileTable(); xLocCache = new LocationsCache(10000); this.master = master; this.ignoreCaps = master.getConfig().isIgnoreCaps(); } public void prepareRequest(OSDRequest request, ParseCompleteCallback listener) { this.enqueueOperation(STAGEOP_PARSE_AUTH_OFTOPEN, new Object[]{request}, null, listener); } public static interface ParseCompleteCallback { public void parseComplete(OSDRequest result, Exception error); } private void doPrepareRequest(StageRequest rq) { final OSDRequest request = (OSDRequest) rq.getArgs()[0]; final ParseCompleteCallback callback = (ParseCompleteCallback) rq.getCallback(); numRequests++; if (parseRequest(request) == false) return; if (request.getOperation().requiresCapability()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "STAGEOP AUTH"); try { processAuthenticate(request); } catch (OSDException ex) { callback.parseComplete(request, ex); return; } } String fileId = request.getFileId(); if (fileId != null) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "STAGEOP OPEN"); CowPolicy cowPolicy; if (oft.contains(fileId)) { cowPolicy = oft.refresh(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION); } else { //find out which COW mode to use //currently everything is no COW oft.openFile(fileId, TimeSync.getLocalSystemTime() + OFT_OPEN_EXTENSION, CowPolicy.PolicyNoCow); cowPolicy = CowPolicy.PolicyNoCow; } request.setCowPolicy(cowPolicy); } callback.parseComplete(request, null); } public void checkDeleteOnClose(String fileId, DeleteOnCloseCallback listener) { this.enqueueOperation(STAGEOP_OFT_DELETE, new Object[]{fileId}, null, listener); } public static interface DeleteOnCloseCallback { public void deleteOnCloseResult(boolean isDeleteOnClose, Exception error); } private void doCheckDeleteOnClose(StageRequest m) { final String fileId = (String)m.getArgs()[0]; final DeleteOnCloseCallback callback = (DeleteOnCloseCallback)m.getCallback(); final boolean deleteOnClose = oft.contains(fileId); if (deleteOnClose) oft.setDeleteOnClose(fileId); callback.deleteOnCloseResult(deleteOnClose, null); } @Override public void run() { notifyStarted(); // interval to check the OFT timeToNextOFTclean = OFT_CLEAN_INTERVAL; lastOFTcheck = TimeSync.getLocalSystemTime(); while (!quit) { try { final StageRequest op = q.poll(timeToNextOFTclean, TimeUnit.MILLISECONDS); checkOpenFileTable(); if (op == null) { // Logging.logMessage(Logging.LEVEL_DEBUG,this,"no request // -- timer only"); continue; } processMethod(op); } catch (InterruptedException ex) { break; } catch (Exception ex) { Logging.logMessage(Logging.LEVEL_ERROR, this, ex); notifyCrashed(ex); break; } } notifyStopped(); } private void checkOpenFileTable() { final long tPassed = TimeSync.getLocalSystemTime() - lastOFTcheck; timeToNextOFTclean = timeToNextOFTclean - tPassed; // Logging.logMessage(Logging.LEVEL_DEBUG,this,"time to next OFT: // "+timeToNextOFTclean); if (timeToNextOFTclean <= 0) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "OpenFileTable clean"); // do OFT clean List<OpenFileTable.OpenFileTableEntry> closedFiles = oft.clean(TimeSync.getLocalSystemTime()); // Logging.logMessage(Logging.LEVEL_DEBUG,this,"closing // "+closedFiles.size()+" files"); for (OpenFileTable.OpenFileTableEntry entry : closedFiles) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "send internal close event for " + entry.getFileId() + ", deleteOnClose=" + entry.isDeleteOnClose()); capCache.remove(entry.getFileId()); //send close event OSDOperation closeEvent = master.getInternalEvent(EventCloseFile.class); closeEvent.startInternalEvent(new Object[]{entry.getFileId(),entry.isDeleteOnClose()}); } timeToNextOFTclean = OFT_CLEAN_INTERVAL; } lastOFTcheck = TimeSync.getLocalSystemTime(); } protected void processMethod(StageRequest m) { final int requestedMethod = m.getStageMethod(); if (requestedMethod == STAGEOP_PARSE_AUTH_OFTOPEN) { doPrepareRequest(m); } else if (requestedMethod == STAGEOP_OFT_DELETE) { doCheckDeleteOnClose(m); } } private boolean parseRequest(OSDRequest rq) { final ONCRPCRequest rpcRq = rq.getRPCRequest(); final ONCRPCRequestHeader hdr = rpcRq.getRequestHeader(); //assemble stuff if (hdr.getInterfaceVersion() != OSDInterface.getVersion()) { rq.sendProtocolException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_PROG_MISMATCH, ErrNo.EINVAL,"invalid version requested (requested="+hdr.getInterfaceVersion()+" avail="+OSDInterface.getVersion()+")")); return false; } // everything ok, find the right operation OSDOperation op = master.getOperation(hdr.getOperationNumber()); if (op == null) { rq.sendProtocolException(new ProtocolException(ONCRPCResponseHeader.ACCEPT_STAT_PROC_UNAVAIL, ErrNo.EINVAL,"requested operation is not available on this OSD (proc # "+hdr.getOperationNumber()+")")); return false; } rq.setOperation(op); try { rq.setRequestArgs(op.parseRPCMessage(rpcRq.getRequestFragment(), rq)); } catch (InvalidXLocationsException ex) { OSDException osdex = new OSDException(ErrorCodes.NOT_IN_XLOC, ex.getMessage(), ""); rpcRq.sendGenericException(osdex); return false; } catch (Throwable ex) { if (Logging.isDebug()) Logging.logMessage(Logging.LEVEL_DEBUG, this,ex); rpcRq.sendGarbageArgs(ex.toString()); return false; } if (Logging.isDebug()) { Logging.logMessage(Logging.LEVEL_DEBUG, this, "request parsed: " + rq.getRequestId()); } return true; } private void processAuthenticate(OSDRequest rq) throws OSDException { final Capability rqCap = rq.getCapability(); //check capability args if (rqCap.getFileId().length() == 0) { throw new OSDException(ErrorCodes.INVALID_FILEID, "invalid capability. file_id must not be empty", ""); } if (rqCap.getEpochNo() < 0) { throw new OSDException(ErrorCodes.INVALID_FILEID, "invalid capability. epoch must not be < 0", ""); } if (ignoreCaps) return; if (!rqCap.getFileId().equals(rq.getFileId())) { throw new OSDException(ErrorCodes.AUTH_FAILED, "capability was issued for another file than the one requested", ""); } boolean isValid = false; // look in capCache Set<String> cachedCaps = capCache.get(rqCap.getFileId()); if (cachedCaps != null) { if (cachedCaps.contains(rqCap.getSignature())) { isValid = true; } } // TODO: check access mode (read, write, ...) if (!isValid) { isValid = rqCap.isValid(); if (isValid) { // add to cache if (cachedCaps == null) { cachedCaps = new HashSet<String>(); capCache.put(rqCap.getFileId(), cachedCaps); } cachedCaps.add(rqCap.getSignature()); } } // depending on the result the event listener is sent if (!isValid) { throw new OSDException(ErrorCodes.AUTH_FAILED, "capability is not valid", ""); } } public int getNumOpenFiles() { return oft.getNumOpenFiles(); } public long getNumRequests() { return numRequests; } }