answer
stringlengths
17
10.2M
package de.matthiasmann.twlthemeeditor.gui; import de.matthiasmann.twl.Event; import de.matthiasmann.twl.SimpleDialog; import de.matthiasmann.twl.BoxLayout; import de.matthiasmann.twl.DialogLayout; import de.matthiasmann.twl.EditField; import de.matthiasmann.twl.Menu; import de.matthiasmann.twl.MenuAction; import de.matthiasmann.twl.ScrollPane; import de.matthiasmann.twl.Table; import de.matthiasmann.twl.TableBase.Callback; import de.matthiasmann.twl.TableBase.DragListener; import de.matthiasmann.twl.TableRowSelectionManager; import de.matthiasmann.twl.TreeTable; import de.matthiasmann.twl.model.TableSingleSelectionModel; import de.matthiasmann.twl.model.TreeTableNode; import de.matthiasmann.twl.renderer.MouseCursor; import de.matthiasmann.twl.utils.CallbackSupport; import de.matthiasmann.twlthemeeditor.datamodel.DecoratedText; import de.matthiasmann.twlthemeeditor.datamodel.FilteredModel; import de.matthiasmann.twlthemeeditor.datamodel.ThemeTreeModel; import de.matthiasmann.twlthemeeditor.datamodel.ThemeTreeNode; import de.matthiasmann.twlthemeeditor.datamodel.ThemeTreeOperation; import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateAtWrapper; import de.matthiasmann.twlthemeeditor.datamodel.operations.CreateChildOperation; import de.matthiasmann.twlthemeeditor.datamodel.operations.MoveNodeOperations; import java.io.File; import java.net.URI; import java.net.URL; import java.util.List; /** * * @author Matthias Mann */ public class ThemeTreePane extends DialogLayout { private final MessageLog messageLog; private final TreeTable treeTable; private final TableSingleSelectionModel treeTableSelectionModel; private final Table table; private final TableSingleSelectionModel tableSelectionModel; private final ScrollPane scrollPane; private final EditField filterEditField; private final MyFilter filter; private final BoxLayout buttons; private FilteredModel filteredModel; private TreeTableNode selected; private Runnable[] callbacks; public ThemeTreePane(MessageLog messageLog) { this.messageLog = messageLog; this.treeTable = new TreeTable() { @Override protected boolean handleKeyStrokeAction(String action, Event event) { if(handleOperationKeyStrokeAction(action, event)) { return true; } return super.handleKeyStrokeAction(action, event); } }; this.treeTableSelectionModel = new TableSingleSelectionModel(); this.table = new Table(); this.tableSelectionModel = new TableSingleSelectionModel(); this.scrollPane = new ScrollPane(treeTable); this.filterEditField = new EditField(); this.filter = new MyFilter(); this.buttons = new BoxLayout(BoxLayout.Direction.HORIZONTAL); CollapsiblePanel collapsibleButtons = new CollapsiblePanel( CollapsiblePanel.Direction.HORIZONTAL, "", buttons, null); IconCellRenderer.install(treeTable); scrollPane.setFixed(ScrollPane.Fixed.HORIZONTAL); treeTable.setSelectionManager(new TableRowSelectionManager(treeTableSelectionModel)); table.setSelectionManager(new TableRowSelectionManager(tableSelectionModel)); filterEditField.setTheme("filter"); filterEditField.addCallback(new EditField.Callback() { public void callback(int key) { updateFilter(); } }); treeTableSelectionModel.addSelectionChangeListener(new Runnable() { public void run() { TreeTableNode node = null; if(treeTableSelectionModel.hasSelection()) { node = treeTable.getNodeFromRow(treeTableSelectionModel.getFirstSelected()); } setSelected(node); } }); tableSelectionModel.addSelectionChangeListener(new Runnable() { public void run() { TreeTableNode node = null; if(tableSelectionModel.hasSelection()) { node = filteredModel.getRow(tableSelectionModel.getFirstSelected()); } setSelected(node); } }); treeTable.addCallback(new Callback() { public void mouseDoubleClicked(int row, int column) { if(row >= 0 && row < treeTable.getNumRows()) { treeTable.setRowExpanded(row, !treeTable.isRowExpanded(row)); } } public void mouseRightClick(int row, int column, Event evt) { if(row >= 0 && row < treeTable.getNumRows()) { showTreeTablePopupMenu(row, evt); } } public void columnHeaderClicked(int column) { } }); treeTable.setDragListener(new DragListener() { TreeTableNode dragParent; MoveNodeOperations moveUp; MoveNodeOperations moveDown; public boolean dragStarted(int row, int col, Event evt) { if((evt.getModifiers() & Event.MODIFIER_BUTTON) != Event.MODIFIER_LBUTTON) { return false; } if(!(selected instanceof ThemeTreeNode)) { return false; } dragParent = selected.getParent(); if(dragParent == null) { return false; } ThemeTreeNode selectedThemeNode = (ThemeTreeNode)selected; moveUp = selectedThemeNode.getMoveOperation(-1); moveDown = selectedThemeNode.getMoveOperation(+1); if(moveUp == null || moveDown == null) { return false; } return true; } public MouseCursor dragged(Event evt) { if(!treeTable.setDropMarker(evt) || getNewNodeIndex() < 0) { treeTable.clearDropMarker(); } scrollPane.checkAutoScroll(evt); return null; } public void dragStopped(Event evt) { int newIndex = getNewNodeIndex(); if(newIndex >= 0) { int oldIndex = dragParent.getChildIndex(selected); if(newIndex < oldIndex) { while(moveUp.isEnabled() && newIndex < oldIndex) { executeOperation(moveUp, null); --oldIndex; } } else { --newIndex; while(moveDown.isEnabled() && newIndex > oldIndex) { executeOperation(moveDown, null); ++oldIndex; } } } dragCanceled(); } public void dragCanceled() { treeTable.clearDropMarker(); scrollPane.stopAutoScroll(); moveUp = null; moveDown = null; dragParent = null; } private int getNewNodeIndex() { if(!treeTable.isDropMarkerBeforeRow()) { return -1; } int row = treeTable.getDropMarkerRow(); if(row < treeTable.getNumRows()) { TreeTableNode node = treeTable.getNodeFromRow(row); if(node.getParent() == dragParent) { return dragParent.getChildIndex(node); } } if(row > 0) { // special case: allow to drop at the end of the parent TreeTableNode node = treeTable.getNodeFromRow(row - 1); if(node.getParent() == dragParent) { int idx = dragParent.getChildIndex(node); if(idx == dragParent.getNumChildren()-1) { return idx + 1; } } } return -1; } }); table.addCallback(new Callback() { public void mouseDoubleClicked(int row, int column) { clearFilterAndJumpToRow(row); } public void mouseRightClick(int row, int column, Event evt) { } public void columnHeaderClicked(int column) { } }); setHorizontalGroup(createParallelGroup() .addWidget(scrollPane) .addGroup(createSequentialGroup().addGap(DEFAULT_GAP).addWidget(filterEditField).addWidget(collapsibleButtons))); setVerticalGroup(createSequentialGroup() .addWidget(scrollPane) .addGroup(createParallelGroup(filterEditField, collapsibleButtons))); } public void addCallback(Runnable cb) { callbacks = CallbackSupport.addCallbackToList(callbacks, cb, Runnable.class); } public void removeCallback(Runnable cb) { callbacks = CallbackSupport.removeCallbackFromList(callbacks, cb); } void updateFilter() { if(filter.setString(filterEditField.getText())) { TreeTableNode curSel = selected; if(filter.hasFilter()) { scrollPane.setContent(table); if(filteredModel != null) { filteredModel.setFilter(filter); } } else { scrollPane.setContent(treeTable); } selectNode(curSel); } } void setSelected(TreeTableNode node) { if(selected != node) { selected = node; CallbackSupport.fireCallbacks(callbacks); updateOperationButtons(); } } void updateOperationButtons() { buttons.removeAllChildren(); if(selected instanceof ThemeTreeNode) { ThemeTreeNode node = (ThemeTreeNode)selected; Menu m = new Menu(); addButtons(m, node, node.getOperations()); addCreateSubMenu(m, node, node.getCreateChildOperations()); m.createMenuBar(buttons); } } void showTreeTablePopupMenu(int row, Event evt) { TreeTableNode nodeFromRow = treeTable.getNodeFromRow(row); if(nodeFromRow instanceof ThemeTreeNode) { ThemeTreeNode node = (ThemeTreeNode)nodeFromRow; Menu menu = new Menu(); if(node.getParent() instanceof ThemeTreeNode) { ThemeTreeNode parentNode = (ThemeTreeNode)node.getParent(); List<CreateChildOperation> parentOperations = parentNode.getCreateChildOperations(); addCreateAtSubMenu(menu, "opNewNodeBefore", parentNode, parentOperations, CreateAtWrapper.Location.BEFORE, node); addCreateAtSubMenu(menu, "opNewNodeAfter", parentNode, parentOperations, CreateAtWrapper.Location.AFTER, node); } addCreateSubMenu(menu, node, node.getCreateChildOperations()); List<ThemeTreeOperation> operations = node.getOperations(); if(!operations.isEmpty()) { if(menu.getNumElements() > 0) { menu.addSpacer(); } addButtons(menu, node, operations); } if(menu.getNumElements() > 0) { menu.openPopupMenu(treeTable, evt.getMouseX(), evt.getMouseY()); } } } public TreeTableNode getSelected() { return selected; } public void setModel(ThemeTreeModel model) { treeTable.setModel(model); if(model == null) { filteredModel = null; } else { treeTable.setRowExpanded(0, true); filteredModel = new FilteredModel(model); } table.setModel(filteredModel); updateFilter(); } private void addButtons(Menu menu, ThemeTreeNode node, List<ThemeTreeOperation> operations) { for(final ThemeTreeOperation operation : operations) { MenuAction action = createMenuAction(node, operation); menu.add(action); } } private void addCreateSubMenu(Menu menu, final ThemeTreeNode node, List<CreateChildOperation> operations) { if(!operations.isEmpty()) { Menu subPopupMenu = new Menu(); subPopupMenu.setTheme("opNewNode"); subPopupMenu.setPopupTheme("opNewNode-popupMenu"); menu.add(subPopupMenu); for(CreateChildOperation operation : operations) { MenuAction action = createMenuAction(node, operation); subPopupMenu.add(action); } } } private void addCreateAtSubMenu(Menu menu, String id, ThemeTreeNode node, List<CreateChildOperation> operations, CreateAtWrapper.Location location, ThemeTreeNode pos) { if(!operations.isEmpty()) { Menu subPopupMenu = new Menu(); subPopupMenu.setTheme(id); subPopupMenu.setPopupTheme("opNewNode-popupMenu"); menu.add(subPopupMenu); for(CreateChildOperation operation : operations) { MenuAction action = createMenuAction(node, new CreateAtWrapper(operation, location, pos)); subPopupMenu.add(action); } } } private MenuAction createMenuAction(final ThemeTreeNode node, final ThemeTreeOperation operation) { MenuAction action = new MenuAction(); action.setTheme(operation.getActionID()); action.setEnabled(operation.isEnabled()); action.setCallback(new Runnable() { public void run() { queryOperationParameter(node, operation, false); } }); return action; } private static final MessageLog.Category CAT_THEME_TREE_OPERATION = new MessageLog.Category("Tree operation", MessageLog.CombineMode.NONE, DecoratedText.ERROR); void executeOperation(ThemeTreeOperation operation, Object[] paramter) { TreeTableNode newSelection = null; try { newSelection = operation.execute(paramter); } catch(IllegalArgumentException ex) { messageLog.add(new MessageLog.Entry(CAT_THEME_TREE_OPERATION, "Invalid parameters for operation", ex.getMessage(), null)); } catch(Throwable ex) { messageLog.add(new MessageLog.Entry(CAT_THEME_TREE_OPERATION, "Error while executing tree operation", null, ex)); } selectNode(newSelection); } void selectNode(TreeTableNode node) { int idx = (node != null) ? treeTable.getRowFromNodeExpand(node) : -1; treeTableSelectionModel.setSelection(idx, idx); if(idx >= 0) { treeTable.scrollToRow(idx); } idx = (node != null) ? filteredModel.getRowFromNode(node) : -1; tableSelectionModel.setSelection(idx, idx); if(idx >= 0) { table.scrollToRow(idx); } updateOperationButtons(); } void clearFilterAndJumpToRow(int row) { if(row >= 0 && row < filteredModel.getNumRows()) { selectNode(filteredModel.getRow(row)); filterEditField.setText(""); } } private static final MessageLog.Category CAT_URL_ERROR = new MessageLog.Category("URL", MessageLog.CombineMode.NONE, DecoratedText.ERROR); private static final MessageLog.Category CAT_URL_WARNING = new MessageLog.Category("URL", MessageLog.CombineMode.REPLACE, DecoratedText.WARNING); void queryOperationParameter(ThemeTreeNode node, final ThemeTreeOperation operation, final boolean skipConfirm) { ThemeTreeOperation.Parameter[] parameter = operation.getParameter(); if(parameter != null && parameter.length > 0) { File startDir = null; URL url = node.getThemeFile().getURL(); try { URI uri = url.toURI(); if("file".equals(uri.getScheme())) { startDir = new File(uri).getParentFile(); } else { messageLog.add(new MessageLog.Entry(CAT_URL_WARNING, "Can't resolve URI in file system", uri.toString(), null)); } } catch (Exception ex) { messageLog.add(new MessageLog.Entry(CAT_URL_ERROR, "Error resolving URL to file system", url.toString(), ex)); } final QueryOperationParameter qop = new QueryOperationParameter(startDir); qop.setParameter(parameter); SimpleDialog dialog = new SimpleDialog(); dialog.setTheme("parameterDlg-" + operation.getActionID()); dialog.setTitle(operation.getActionID()); dialog.setMessage(qop); dialog.setOkCallback(new Runnable() { public void run() { maybeConfirmOperation(operation, qop.getResults(), skipConfirm); } }); dialog.showDialog(this); } else { maybeConfirmOperation(operation, null, skipConfirm); } } void maybeConfirmOperation(ThemeTreeOperation operation, Object[] paramter, boolean skipConfirm) { if(!skipConfirm && operation.needConfirm()) { confirmOperation(operation, paramter); } else { executeOperation(operation, paramter); } } void confirmOperation(final ThemeTreeOperation operation, final Object[] paramter) { SimpleDialog dialog = new SimpleDialog(); dialog.setTheme("confirmationDlg-" + operation.getActionID()); dialog.setTitle(operation.getActionID()); dialog.setMessage(selected.toString()); dialog.setOkCallback(new Runnable() { public void run() { executeOperation(operation, paramter); } }); dialog.showDialog(this); } boolean handleOperationKeyStrokeAction(String action, Event event) { if(event.isKeyPressedEvent() && !event.isKeyRepeated() && selected instanceof ThemeTreeNode) { ThemeTreeNode node = (ThemeTreeNode)selected; ThemeTreeOperation o = findOperation(node.getOperations(), action); if(o == null) { o = findOperation(node.getCreateChildOperations(), action); } if(o != null) { queryOperationParameter(node, o, (event.getModifiers() & Event.MODIFIER_SHIFT) != 0); return true; } } return false; } private ThemeTreeOperation findOperation(List<? extends ThemeTreeOperation> operations, String action) { for(ThemeTreeOperation o : operations) { if(o.getActionID().equals(action)) { return o; } } return null; } static class MyFilter implements FilteredModel.Filter { private String str = ""; boolean setString(String str) { str = str.toLowerCase(); if(!this.str.equals(str)) { this.str = str; return true; } return false; } boolean hasFilter() { return str.length() > 0; } public boolean isVisible(TreeTableNode node) { if(node instanceof ThemeTreeNode) { ThemeTreeNode ttn = (ThemeTreeNode)node; String name = ttn.getName(); return (name != null) && name.toLowerCase().contains(str); } return false; } } }
package de.mrunde.bachelorthesis.activities; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Locale; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.graphics.Color; import android.graphics.Paint; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.mapquest.android.maps.DefaultItemizedOverlay; import com.mapquest.android.maps.GeoPoint; import com.mapquest.android.maps.LineOverlay; import com.mapquest.android.maps.MapActivity; import com.mapquest.android.maps.MapView; import com.mapquest.android.maps.MyLocationOverlay; import com.mapquest.android.maps.OverlayItem; import com.mapquest.android.maps.RouteManager; import com.mapquest.android.maps.RouteResponse; import de.mrunde.bachelorthesis.R; import de.mrunde.bachelorthesis.basics.Landmark; import de.mrunde.bachelorthesis.basics.LandmarkCategory; import de.mrunde.bachelorthesis.basics.Maneuver; import de.mrunde.bachelorthesis.basics.MyDefaultItemizedOverlay; import de.mrunde.bachelorthesis.instructions.GlobalInstruction; import de.mrunde.bachelorthesis.instructions.Instruction; import de.mrunde.bachelorthesis.instructions.InstructionManager; import de.mrunde.bachelorthesis.instructions.LandmarkInstruction; /** * This is the navigational activity which is started by the MainActivity. It * navigates the user from his current location to the desired destination. * * @author Marius Runde */ public class NaviActivity extends MapActivity implements OnInitListener, LocationListener { /** * Index of the local landmark overlay */ private final int INDEX_OF_LANDMARK_OVERLAY = 3; /** * Instruction view (verbal) */ private TextView tv_instruction; /** * Instruction view (image) */ private ImageView iv_instruction; /** * Map view */ private MapView map; /** * An overlay to display the user's location */ private MyLocationOverlay myLocationOverlay; /** * Current location as String (for RouteManager only!) */ private String str_currentLocation; /** * Destination as String (for RouteManager and as title of destination * overlay) */ private String str_destination; /** * Latitude of the destination */ private double destination_lat; /** * Longitude of the destination */ private double destination_lng; /** * Route manager for route calculation */ private RouteManager rm; /** * Route options (already formatted as a String) */ private String routeOptions; /** * Instruction manager that creates instructions */ private InstructionManager im; /** * Location manager to monitor the user's location */ private LocationManager lm; /** * Location provider of the LocationManager */ private String provider; /** * Minimum distance for a route segment to use a NowInstruction */ private final int MIN_DISTANCE_FOR_NOW_INSTRUCTION = 100; /** * The NowInstruction will be returned at this distance before reaching the * next decision point */ private final int DISTANCE_FOR_NOW_INSTRUCTION = 48; /** * Variable to control if the usage of a NowInstruction has been checked */ private boolean nowInstructionChecked = false; /** * Variable to control if a NowInstruction will be used */ private boolean nowInstructionUsed = false; /** * Maximum distance to a decision point when it is supposed to be reached */ private final int MAX_DISTANCE_TO_DECISION_POINT = 32; /** * Store the last distance between the next decision point and the current * location. Is set to 0 when the instruction is updated. */ private double lastDistanceDP1 = 0; /** * Store the last distance between the decision point after next and the * current location. Is set to 0 when the instruction is updated. */ private double lastDistanceDP2 = 0; /** * Counts the distance changes between the next decision point, the decision * point after next and the current location. Is set to 0 after the * instruction has been updated. The instruction is updated when the counter * reaches its maximum negative value (<code>(-1) * MAX_COUNTER_VALUE</code> * ) or the next decision point has been reached. If the counter reaches the * maximum positive value (<code>MAX_COUNTER_VALUE</code>), the whole * guidance will be updated. */ private int distanceCounter = 0; /** * Maximum value for the <code>distanceCounter</code>. */ private final int MAX_COUNTER_VALUE = 5; /** * TextToSpeech for audio output */ private TextToSpeech tts; /** * Store all logs of the <code>onLocationChanged()</code> and * <code>updateInstruction()</code> methods in this String to display them * on the application via the <code>OptionsMenu</code> */ private String debugger = ""; /** * This method is called when the application has been started */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.navi); // Get the route information from the intent Intent intent = getIntent(); this.str_currentLocation = intent.getStringExtra("str_currentLocation"); this.str_destination = intent.getStringExtra("str_destination"); this.destination_lat = intent.getDoubleExtra("destination_lat", 0.0); this.destination_lng = intent.getDoubleExtra("destination_lng", 0.0); this.routeOptions = intent.getStringExtra("routeOptions"); // Initialize the TextToSpeech tts = new TextToSpeech(this, this); // Initialize the LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Choose the location provider Criteria criteria = new Criteria(); provider = lm.getBestProvider(criteria, false); Location location = lm.getLastKnownLocation(provider); if (location != null) { Log.e("Test", "Provider " + provider + " has been selected."); onLocationChanged(location); } else { Log.e("Test", "Location not available"); } // Setup the whole GUI and map setupGUI(); setupMapView(); setupMyLocation(); // Add the destination overlay to the map addDestinationOverlay(destination_lat, destination_lng); // Calculate the route calculateRoute(); // Get the guidance information and create the instructions getGuidance(); } /** * Set up the GUI */ private void setupGUI() { this.tv_instruction = (TextView) findViewById(R.id.tv_instruction); this.iv_instruction = (ImageView) findViewById(R.id.iv_instruction); } /** * Set up the map and disable user interaction */ private void setupMapView() { this.map = (MapView) findViewById(R.id.map); map.setBuiltInZoomControls(false); map.setClickable(false); map.setLongClickable(false); } /** * Set up a MyLocationOverlay and execute the runnable once a location has * been fixed */ private void setupMyLocation() { // Check if the GPS is enabled if (!((LocationManager) getSystemService(LOCATION_SERVICE)) .isProviderEnabled(LocationManager.GPS_PROVIDER)) { // Open dialog to inform the user that the GPS is disabled AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.gpsDisabled)); builder.setCancelable(false); builder.setPositiveButton(R.string.openSettings, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Open the location settings if it is disabled Intent intent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Dismiss the dialog dialog.cancel(); } }); // Display the dialog AlertDialog dialog = builder.create(); dialog.show(); } // Set up the myLocationOverlay this.myLocationOverlay = new MyLocationOverlay(this, map); myLocationOverlay.enableMyLocation(); myLocationOverlay.setMarker( getResources().getDrawable(R.drawable.my_location), 0); myLocationOverlay.runOnFirstFix(new Runnable() { @Override public void run() { GeoPoint currentLocation = myLocationOverlay.getMyLocation(); map.getController().animateTo(currentLocation); map.getController().setZoom(18); map.getOverlays().add(myLocationOverlay); myLocationOverlay.setFollowing(true); } }); } /** * Add the destination overlay to the map * * @param lat * Latitude of the destination * @param lng * Longitude of the destination */ private void addDestinationOverlay(double lat, double lng) { // Create a GeoPoint object of the destination GeoPoint destination = new GeoPoint(lat, lng); // Create the destination overlay OverlayItem oi_destination = new OverlayItem(destination, "Destination", str_destination); final DefaultItemizedOverlay destinationOverlay = new DefaultItemizedOverlay( getResources().getDrawable(R.drawable.destination_flag)); destinationOverlay.addItem(oi_destination); // Add the overlay to the map map.getOverlays().add(destinationOverlay); } /** * Calculate the route from the current location to the destination */ private void calculateRoute() { // Clear the previous route first if (rm != null) { rm.clearRoute(); } // Initialize a new RouteManager to calculate the route rm = new RouteManager(getBaseContext(), getResources().getString( R.string.apiKey)); // Set the route options (e.g. route type) rm.setOptions(routeOptions); // Set route callback rm.setRouteCallback(new RouteManager.RouteCallback() { @Override public void onSuccess(RouteResponse response) { // Route has been calculated successfully Log.i("NaviActivity", getResources().getString(R.string.routeCalculated)); } @Override public void onError(RouteResponse response) { // Route could not be calculated Log.e("NaviActivity", getResources().getString(R.string.routeNotCalculated)); } }); // Calculate the route and display it on the map rm.createRoute(str_currentLocation, str_destination); // Zoom to current location map.getController().animateTo(myLocationOverlay.getMyLocation()); map.getController().setZoom(18); } /** * Get the guidance information from MapQuest */ private void getGuidance() { // Create the URL to request the guidance from MapQuest String url; try { url = "https://open.mapquestapi.com/guidance/v1/route?key=" + getResources().getString(R.string.apiKey) + "&from=" + URLEncoder.encode(str_currentLocation, "UTF-8") + "&to=" + URLEncoder.encode(str_destination, "UTF-8") + "&narrativeType=text&fishbone=false&callback=renderBasicInformation"; } catch (UnsupportedEncodingException e) { Log.e("NaviActivity", "Could not encode the URL. This is the error message: " + e.getMessage()); return; } // Get the data. The instructions are created afterwards. GetJsonTask jsonTask = new GetJsonTask(); jsonTask.execute(url); } /** * This is a class to get the JSON file asynchronously from the given URL. * * @author Marius Runde */ private class GetJsonTask extends AsyncTask<String, Void, JSONObject> { /** * Progress dialog to inform the user about the download */ private ProgressDialog progressDialog = new ProgressDialog( NaviActivity.this); /** * Count the time needed for the data download */ private int downloadTimer; @Override protected void onPreExecute() { // Display progress dialog progressDialog.setMessage("Downloading guidance..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // Cancel the download when the "Cancel" button has been // clicked GetJsonTask.this.cancel(true); } }); // Set timer to current time downloadTimer = Calendar.getInstance().get(Calendar.SECOND); } @Override protected JSONObject doInBackground(String... url) { // Get the data from the URL String output = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; try { response = httpclient.execute(new HttpGet(url[0])); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); output = out.toString(); } else { // Close the connection response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (Exception e) { Log.e("GetJsonTask", "Could not get the data. This is the error message: " + e.getMessage()); return null; } // Delete the "renderBasicInformation" stuff at the beginning and // end of the output if needed to convert it to a JSONObject if (output.startsWith("renderBasicInformation(")) { output = output.substring(23, output.length()); } if (output.endsWith(");")) { output = output.substring(0, output.length() - 2); } // Convert the output to a JSONObject try { JSONObject result = new JSONObject(output); return result; } catch (JSONException e) { Log.e("GetJsonTask", "Could not convert output to JSONObject. This is the error message: " + e.getMessage()); return null; } } @Override protected void onPostExecute(JSONObject result) { // Dismiss progress dialog progressDialog.dismiss(); // Write the time needed for the download into the log downloadTimer = Calendar.getInstance().get(Calendar.SECOND) - downloadTimer; Log.i("GetJsonTask", "Completed guidance download in " + downloadTimer + " seconds"); // Check if the download was successful if (result == null) { // Could not receive the JSON Toast.makeText(NaviActivity.this, getResources().getString(R.string.routeNotCalculated), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } else { // Create the instructions createInstructions(result); // Draw the route and display the first instruction drawRoute(result); } } } /** * Create the instructions for the navigation * * @param guidance * The guidance information from MapQuest */ private void createInstructions(JSONObject guidance) { // Load the landmarks as a JSONObject from res/raw/landmarks.json InputStream is = getResources().openRawResource(R.raw.landmarks); JSONObject landmarks = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); landmarks = new JSONObject(rawJson); } catch (Exception e) { // Could not load landmarks Log.e("NaviActivity", "Could not load landmarks. This is the error message: " + e.getMessage()); } // Load the street furniture as a JSONArray from // res/raw/streetfurniture.json is = getResources().openRawResource(R.raw.streetfurniture); JSONArray streetFurniture = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); streetFurniture = new JSONArray(rawJson); } catch (Exception e) { // Could not load street furniture Log.e("NaviActivity", "Could not load street furniture. This is the error message: " + e.getMessage()); } // Load the intersections as a JSONArray from res/raw/intersections.json is = getResources().openRawResource(R.raw.intersections); JSONArray intersections = null; try { String rawJson = IOUtils.toString(is, "UTF-8"); intersections = new JSONArray(rawJson); } catch (Exception e) { // Could not load intersections Log.e("NaviActivity", "Could not load intersections. This is the error message: " + e.getMessage()); } // Create the instruction manager im = new InstructionManager(guidance, landmarks, streetFurniture, intersections); // Check if the import was successful if (im.isImportSuccessful()) { // Create the instructions im.createInstructions(); } else { // Import was not successful Toast.makeText(this, getResources().getString(R.string.jsonImportNotSuccessful), Toast.LENGTH_SHORT).show(); // Finish the activity to return to MainActivity finish(); } } /** * Draw the route with the given shapePoints from the guidance information * * @param json * The guidance information from MapQuest */ private void drawRoute(JSONObject json) { // Set custom line style Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); // Initialize the route overlay List<GeoPoint> shapePoints = new ArrayList<GeoPoint>( Arrays.asList(this.im.getShapePoints())); LineOverlay drawnRoute = new LineOverlay(paint); drawnRoute.setData(shapePoints); // Add the drawn route to the map map.getOverlays().add(drawnRoute); Log.d("NaviActivity", "Route overlay added"); if (!im.isImportSuccessful()) { // Import was not successful Toast.makeText(NaviActivity.this, getResources().getString(R.string.jsonImportNotSuccessful), Toast.LENGTH_SHORT).show(); // Finish the activity to return to the MainActivity finish(); } else { do { // Route is not displayed yet } while (!this.isRouteDisplayed()); // Get the first instruction and display it displayInstruction(im.getInstruction(0)); } } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.closeActivity_title) .setMessage(R.string.closeActivity_message) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setNegativeButton("No", null).show(); } @Override protected boolean isRouteDisplayed() { if (this.map.getOverlays().size() > 1) { return true; } else { return false; } } /** * Called when the OptionsMenu is created */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.navi, menu); return true; } /** * Called when an item of the OptionsMenu is clicked */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_allInstructions: // Create an array of all verbal instructions String[] allInstructions = im.getVerbalInstructions(); // Display all instructions in a list AlertDialog.Builder builder1 = new AlertDialog.Builder( NaviActivity.this); builder1.setTitle(R.string.allInstructions); builder1.setItems(allInstructions, null); AlertDialog alertDialog1 = builder1.create(); alertDialog1.show(); return true; case R.id.menu_debugger: // Display all stored logs in a list AlertDialog.Builder builder2 = new AlertDialog.Builder( NaviActivity.this); builder2.setTitle(R.string.menu_debugger); builder2.setMessage(debugger); AlertDialog alertDialog2 = builder2.create(); alertDialog2.show(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { // Enable features of the MyLocationOverlay myLocationOverlay.enableMyLocation(); // Request location updates at startup every 500ms for changes of 1m lm.requestLocationUpdates(provider, 500, 1, this); super.onResume(); } @Override protected void onPause() { super.onPause(); // Disable features of the MyLocationOverlay when in the background myLocationOverlay.disableMyLocation(); // Disable the LocationManager when in the background lm.removeUpdates(this); } @Override public void onInit(int status) { // Initialize the TextToSpeech engine if (status == TextToSpeech.SUCCESS) { tts.setLanguage(Locale.ENGLISH); } else { tts = null; Log.e("MainActivity", "Failed to initialize the TextToSpeech engine"); } } @Override public void onLocationChanged(Location location) { debugger += "onLocationChanged() called...\n"; double lat = location.getLatitude(); double lng = location.getLongitude(); // Check if the instruction manager has been initialized already if (im != null) { // Get the coordinates of the next decision point double dp1Lat = im.getCurrentInstruction().getDecisionPoint() .getLatitude(); double dp1Lng = im.getCurrentInstruction().getDecisionPoint() .getLongitude(); // Get the coordinates of the decision point after next double dp2Lat = im.getNextInstructionLocation().getLatitude(); double dp2Lng = im.getNextInstructionLocation().getLongitude(); // Calculate the distance to the next decision point float[] results = new float[1]; Location.distanceBetween(lat, lng, dp1Lat, dp1Lng, results); double distanceDP1 = results[0]; // Check whether a now instruction must be used (only once for each // route segment) if (nowInstructionChecked == false && distanceDP1 >= MIN_DISTANCE_FOR_NOW_INSTRUCTION) { nowInstructionUsed = true; } nowInstructionChecked = true; // Calculate the distance to the decision point after next Location.distanceBetween(lat, lng, dp2Lat, dp2Lng, results); double distanceDP2 = results[0]; // Log the distances String distancesString = "LastDistanceDP1: " + lastDistanceDP1 + " | distanceDP1: " + distanceDP1 + " | LastDistanceDP2: " + lastDistanceDP2 + " | distanceDP2: " + distanceDP2; debugger += distancesString + "\n"; Log.v("NaviActivity.onLocationChanged", distancesString); // Check the distances with the stored ones if (distanceDP1 < MAX_DISTANCE_TO_DECISION_POINT) { // Distance to decision point is less than // MAX_DISTANCE_TO_DECISION_POINT updateInstruction(); } else if (distanceDP1 < DISTANCE_FOR_NOW_INSTRUCTION && nowInstructionUsed == true) { // Distance to decision point is less than // DISTANCE_FOR_NOW_INSTRUCTION and decreasing, so a now // instruction is prompted to the user updateNowInstruction(); // Set variable nowInstructionUsed to false, so that the now // instruction is only used once nowInstructionUsed = false; } else if (distanceDP1 > lastDistanceDP1 && distanceDP2 < lastDistanceDP2) { // The distance to the next decision point has increased and the // distance to the decision point after next has decreased lastDistanceDP1 = distanceDP1; lastDistanceDP2 = distanceDP2; distanceCounter++; String logMessage = "distanceCounter: " + distanceCounter; debugger += logMessage + "\n"; Log.v("NaviActivity.onLocationChanged", logMessage); } else if (distanceDP1 > lastDistanceDP1 && distanceDP2 > lastDistanceDP2) { // Distance to the next decision point and the decision point // after next has increased (can lead to a driving error) lastDistanceDP1 = distanceDP1; lastDistanceDP2 = distanceDP2; distanceCounter String logMessage = "distanceIncreaseCounter: " + distanceCounter; debugger += logMessage + "\n"; Log.v("NaviActivity.onLocationChanged", logMessage); } // Check if the whole guidance needs to be reloaded due to a driving // error (user seems to go away from both the decision point and the // decision point after next) if (distanceCounter < (-1 * MAX_COUNTER_VALUE)) { updateGuidance(); } // Check if the instruction needs to be updated if (distanceCounter > MAX_COUNTER_VALUE) { updateInstruction(); } } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Do nothing here } @Override public void onProviderEnabled(String provider) { // Do nothing here } @Override public void onProviderDisabled(String provider) { // Do nothing here } /** * Called when the next decision point has been reached to update the * current instruction to the following instruction. */ private void updateInstruction() { String logMessage = "Updating Instruction..."; debugger += logMessage + "\n"; Log.i("NaviActivity", logMessage); // Reset the distances, their counters, and the NowInstruction // controllers lastDistanceDP1 = 0; lastDistanceDP2 = 0; distanceCounter = 0; nowInstructionChecked = false; nowInstructionUsed = false; // Get the next instruction and display it Instruction nextInstruction = im.getNextInstruction(); displayInstruction(nextInstruction); } /** * Called when a new instruction shall be displayed. Also the map is being * updated so that the old landmarks are removed and the new ones are * displayed. * * @param instruction * The instruction to be displayed */ private void displayInstruction(Instruction instruction) { // Get the next verbal instruction String nextVerbalInstruction = instruction.toString(); // Display the verbal instruction this.tv_instruction.setText(nextVerbalInstruction); // Get the corresponding instruction image and display it this.iv_instruction.setImageDrawable(getResources().getDrawable( Maneuver.getDrawableId(instruction.getManeuverType()))); // Remove previous landmark (if available) if (this.map.getOverlays().size() > this.INDEX_OF_LANDMARK_OVERLAY) { this.map.getOverlays().remove(this.INDEX_OF_LANDMARK_OVERLAY); } // Add new local landmark (if available) if (instruction.getClass().equals(LandmarkInstruction.class)) { Landmark newLocalLandmark = ((LandmarkInstruction) instruction) .getLocal(); OverlayItem oi_newLocalLandmark = new OverlayItem( newLocalLandmark.getCenter(), newLocalLandmark.getTitle(), newLocalLandmark.getCategory()); MyDefaultItemizedOverlay newLocalLandmarkOverlay = new MyDefaultItemizedOverlay( getResources().getDrawable( LandmarkCategory.getDrawableId(newLocalLandmark .getCategory()))); newLocalLandmarkOverlay.addItem(oi_newLocalLandmark); this.map.getOverlays().add(this.INDEX_OF_LANDMARK_OVERLAY, newLocalLandmarkOverlay); } // Add new global landmark (if available) if (instruction.getClass().equals(GlobalInstruction.class)) { Landmark newGlobalLandmark = ((GlobalInstruction) instruction) .getGlobal(); OverlayItem oi_newGlobalLandmark = new OverlayItem( newGlobalLandmark.getCenter(), newGlobalLandmark.getTitle(), newGlobalLandmark.getCategory()); MyDefaultItemizedOverlay newGlobalLandmarkOverlay = new MyDefaultItemizedOverlay( getResources().getDrawable( LandmarkCategory.getDrawableId(newGlobalLandmark .getCategory()))); newGlobalLandmarkOverlay.addItem(oi_newGlobalLandmark); this.map.getOverlays().add(this.INDEX_OF_LANDMARK_OVERLAY, newGlobalLandmarkOverlay); } // Speak out the verbal instruction speakInstruction(); } /** * Speak out the current instruction */ private void speakInstruction() { tts.setSpeechRate((float) 0.85); tts.speak(tv_instruction.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); } /** * Called when the next decision point will be reached in * <code>DISTANCE_FOR_NOW_INSTRUCTION</code> and a * <code>NowInstruction</code> is used to update the current instruction to * the instruction. The map is not changed as in the * <code>updateInstruction</code> method. */ private void updateNowInstruction() { // Get the now instruction Instruction nowInstruction = im.getNowInstruction(); // Get the verbal instruction String verbalInstruction = nowInstruction.toString(); // Display the verbal instruction this.tv_instruction.setText(verbalInstruction); // The instruction image stays the same so nothing has to be done here // Speak out the verbal instruction speakInstruction(); } /** * Update the complete guidance. This method is called when a driving error * has occurred. */ private void updateGuidance() { // Inform the user about updating the guidance Log.i("NaviActivity", "Updating guidance..."); tts.setSpeechRate((float) 1); tts.speak("Updating guidance", TextToSpeech.QUEUE_FLUSH, null); // Restart the activity finish(); startActivity(getIntent()); } }
package dr.app.beauti.treespanel; import dr.app.beauti.options.PartitionTreeModel; import dr.app.beauti.options.PartitionTreePrior; import dr.app.beauti.types.TreePriorParameterizationType; import dr.app.beauti.types.TreePriorType; import dr.app.beauti.util.PanelUtils; import dr.app.gui.components.WholeNumberField; import dr.app.util.OSType; import dr.evomodel.coalescent.VariableDemographicModel; import dr.evomodelxml.speciation.BirthDeathModelParser; import dr.evomodelxml.speciation.BirthDeathSerialSamplingModelParser; import jam.panels.OptionsPanel; import javax.swing.*; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.EnumSet; /** * @author Andrew Rambaut * @author Alexei Drummond * @author Walter Xie * @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $ */ public class PartitionTreePriorPanel extends OptionsPanel { private static final long serialVersionUID = 5016996360264782252L; private JComboBox treePriorCombo = new JComboBox(EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM).toArray()); private JComboBox parameterizationCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.GROWTH_RATE, TreePriorParameterizationType.DOUBLING_TIME).toArray()); // private JComboBox parameterizationCombo1 = new JComboBox(EnumSet.of(TreePriorParameterizationType.DOUBLING_TIME).toArray()); private JComboBox bayesianSkylineCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.CONSTANT_SKYLINE, TreePriorParameterizationType.LINEAR_SKYLINE).toArray()); private WholeNumberField groupCountField = new WholeNumberField(2, Integer.MAX_VALUE); private JComboBox extendedBayesianSkylineCombo = new JComboBox( new VariableDemographicModel.Type[]{VariableDemographicModel.Type.LINEAR, VariableDemographicModel.Type.STEPWISE}); private JComboBox gmrfBayesianSkyrideCombo = new JComboBox(EnumSet.range(TreePriorParameterizationType.UNIFORM_SKYRIDE, TreePriorParameterizationType.TIME_AWARE_SKYRIDE).toArray()); // RealNumberField samplingProportionField = new RealNumberField(Double.MIN_VALUE, 1.0); // private BeautiFrame frame = null; // private BeautiOptions options = null; PartitionTreePrior partitionTreePrior; private final TreesPanel treesPanel; private boolean settingOptions = false; public PartitionTreePriorPanel(PartitionTreePrior parTreePrior, TreesPanel parent) { super(12, (OSType.isMac() ? 6 : 24)); this.partitionTreePrior = parTreePrior; this.treesPanel = parent; PanelUtils.setupComponent(treePriorCombo); treePriorCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setNodeHeightPrior((TreePriorType) treePriorCombo.getSelectedItem()); setupPanel(); } }); PanelUtils.setupComponent(parameterizationCombo); parameterizationCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo.getSelectedItem()); } }); // PanelUtils.setupComponent(parameterizationCombo1); // parameterizationCombo1.addItemListener(new ItemListener() { // public void itemStateChanged(ItemEvent ev) { // partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo1.getSelectedItem()); PanelUtils.setupComponent(groupCountField); groupCountField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent ev) { // move to here? } }); PanelUtils.setupComponent(bayesianSkylineCombo); bayesianSkylineCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setSkylineModel((TreePriorParameterizationType) bayesianSkylineCombo.getSelectedItem()); } }); PanelUtils.setupComponent(extendedBayesianSkylineCombo); extendedBayesianSkylineCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem())); } }); PanelUtils.setupComponent(gmrfBayesianSkyrideCombo); gmrfBayesianSkyrideCombo.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ev) { partitionTreePrior.setSkyrideSmoothing((TreePriorParameterizationType) gmrfBayesianSkyrideCombo.getSelectedItem()); } }); // samplingProportionField.addKeyListener(keyListener); setupPanel(); } private void setupPanel() { removeAll(); JTextArea citationText = new JTextArea(1, 200); citationText.setLineWrap(true); citationText.setEditable(false); citationText.setFont(this.getFont()); // JScrollPane scrollPane = new JScrollPane(citation, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, // JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // scrollPane.setOpaque(true); String citation = null; addComponentWithLabel("Tree Prior:", treePriorCombo); if (treePriorCombo.getSelectedItem() == TreePriorType.EXPONENTIAL || treePriorCombo.getSelectedItem() == TreePriorType.LOGISTIC || treePriorCombo.getSelectedItem() == TreePriorType.EXPANSION) { addComponentWithLabel("Parameterization for growth:", parameterizationCombo); partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo.getSelectedItem()); // } else if (treePriorCombo.getSelectedItem() == TreePriorType.LOGISTIC //) {//TODO Issue 93 // || treePriorCombo.getSelectedItem() == TreePriorType.EXPANSION) { //TODO Issue 266 // addComponentWithLabel("Parameterization for growth:", parameterizationCombo1); // partitionTreePrior.setParameterization((TreePriorParameterizationType) parameterizationCombo1.getSelectedItem()); } else if (treePriorCombo.getSelectedItem() == TreePriorType.SKYLINE) { groupCountField.setColumns(6); addComponentWithLabel("Number of groups:", groupCountField); addComponentWithLabel("Skyline Model:", bayesianSkylineCombo); citation = "Drummond AJ, Rambaut A & Shapiro B and Pybus OG (2005) Mol Biol Evol 22, 1185-1192."; } else if (treePriorCombo.getSelectedItem() == TreePriorType.EXTENDED_SKYLINE) { addComponentWithLabel("Model Type:", extendedBayesianSkylineCombo); treesPanel.linkTreePriorCheck.setSelected(true); treesPanel.updateShareSameTreePriorChanged(); citation = "Insert citation here..."; // treesPanel.getFrame().setupEBSP(); TODO } else if (treePriorCombo.getSelectedItem() == TreePriorType.GMRF_SKYRIDE) { addComponentWithLabel("Smoothing:", gmrfBayesianSkyrideCombo); //For GMRF, one tree prior has to be associated to one tree model. The validation is in BeastGenerator.checkOptions() addLabel("<html>For GMRF, tree model/tree prior combination not implemented by BEAST yet. " + "It is only available for single tree model partition for this release. " + "Please go to Data Partition panel to link all tree models." + "</html>"); citation = "Minin, Bloomquist and Suchard (2008) Mol Biol Evol, 25, 1459-1471."; // treesPanel.linkTreePriorCheck.setSelected(false); // treesPanel.linkTreePriorCheck.setEnabled(false); // treesPanel.linkTreeModel(); // treesPanel.updateShareSameTreePriorChanged(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH) { // samplingProportionField.setColumns(8); // treePriorPanel.addComponentWithLabel("Proportion of taxa sampled:", samplingProportionField); citation = BirthDeathModelParser.getCitation(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_INCOM_SAMP) { citation = BirthDeathModelParser.getCitationRHO(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_SERI_SAMP) { citation = BirthDeathSerialSamplingModelParser.getCitationPsiOrg(); } else if (treePriorCombo.getSelectedItem() == TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM) { citation = BirthDeathSerialSamplingModelParser.getCitationRT(); } else { // treesPanel.linkTreePriorCheck.setEnabled(true); // treesPanel.linkTreePriorCheck.setSelected(true); // treesPanel.updateShareSameTreePriorChanged(); } if (citation != null) { addComponentWithLabel("Citation:", citationText); citationText.setText(citation); } // getOptions(); // treesPanel.treeModelPanels.get(treesPanel.currentTreeModel).setOptions(); for (PartitionTreeModel model : treesPanel.treeModelPanels.keySet()) { if (model != null) { treesPanel.treeModelPanels.get(model).setOptions(); } } // createTreeAction.setEnabled(options != null && options.dataPartitions.size() > 0); // fireTableDataChanged(); validate(); repaint(); } public void setOptions() { if (partitionTreePrior == null) { return; } settingOptions = true; treePriorCombo.setSelectedItem(partitionTreePrior.getNodeHeightPrior()); groupCountField.setValue(partitionTreePrior.getSkylineGroupCount()); //samplingProportionField.setValue(partitionTreePrior.birthDeathSamplingProportion); parameterizationCombo.setSelectedItem(partitionTreePrior.getParameterization()); bayesianSkylineCombo.setSelectedItem(partitionTreePrior.getSkylineModel()); extendedBayesianSkylineCombo.setSelectedItem(partitionTreePrior.getExtendedSkylineModel()); gmrfBayesianSkyrideCombo.setSelectedItem(partitionTreePrior.getSkyrideSmoothing()); // setupPanel(); settingOptions = false; validate(); repaint(); } public void getOptions() { if (settingOptions) return; // partitionTreePrior.setNodeHeightPrior((TreePriorType) treePriorCombo.getSelectedItem()); if (partitionTreePrior.getNodeHeightPrior() == TreePriorType.SKYLINE) { Integer groupCount = groupCountField.getValue(); if (groupCount != null) { partitionTreePrior.setSkylineGroupCount(groupCount); } else { partitionTreePrior.setSkylineGroupCount(5); } } else if (partitionTreePrior.getNodeHeightPrior() == TreePriorType.BIRTH_DEATH) { // Double samplingProportion = samplingProportionField.getValue(); // if (samplingProportion != null) { // partitionTreePrior.birthDeathSamplingProportion = samplingProportion; // } else { // partitionTreePrior.birthDeathSamplingProportion = 1.0; } // partitionTreePrior.setParameterization(parameterizationCombo.getSelectedIndex()); // partitionTreePrior.setSkylineModel(bayesianSkylineCombo.getSelectedIndex()); // partitionTreePrior.setExtendedSkylineModel(((VariableDemographicModel.Type) extendedBayesianSkylineCombo.getSelectedItem()).toString()); // partitionTreePrior.setSkyrideSmoothing(gmrfBayesianSkyrideCombo.getSelectedIndex()); // the taxon list may not exist yet... this should be set when generating... // partitionTreePrior.skyrideIntervalCount = partitionTreePrior.taxonList.getTaxonCount() - 1; } public void setMicrosatelliteTreePrior() { treePriorCombo.removeAllItems(); treePriorCombo.addItem(TreePriorType.CONSTANT); } public void removeCertainPriorFromTreePriorCombo() { treePriorCombo.removeItem(TreePriorType.YULE); treePriorCombo.removeItem(TreePriorType.BIRTH_DEATH); } public void recoveryTreePriorCombo() { if (treePriorCombo.getItemCount() < EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM).size()) { treePriorCombo.removeAllItems(); for (TreePriorType tpt : EnumSet.range(TreePriorType.CONSTANT, TreePriorType.BIRTH_DEATH_SERI_SAMP_ESTIM)) { treePriorCombo.addItem(tpt); } } } }
package edu.ucla.cens.awserver.jee.servlet; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import edu.ucla.cens.awserver.controller.Controller; import edu.ucla.cens.awserver.controller.ControllerException; import edu.ucla.cens.awserver.dao.EmaQueryDao.EmaQueryResult; import edu.ucla.cens.awserver.datatransfer.AwRequest; import edu.ucla.cens.awserver.jee.servlet.glue.AwRequestCreator; import edu.ucla.cens.awserver.util.StringUtils; /** * Servlet for responding to requests for EMA visualization query execution. * * @author selsky */ @SuppressWarnings("serial") public class EmaVizServlet extends AbstractAwHttpServlet { private static Logger _logger = Logger.getLogger(EmaVizServlet.class); private Controller _controller; private AwRequestCreator _awRequestCreator; /** * Default no-arg constructor. */ public EmaVizServlet() { } /** * JavaEE-to-Spring glue code. When the web application starts up, the init method on all servlets is invoked by the Servlet * container (if load-on-startup for the Servlet > 0). In this method, names of Spring "beans" are pulled out of the * ServletConfig and the names are used to retrieve the beans out of the ApplicationContext. The basic design rule followed * is that only Servlet.init methods contain Spring Framework glue code. */ public void init(ServletConfig config) throws ServletException { super.init(config); String servletName = config.getServletName(); // Note that these names are actually Spring Bean ids, not FQCNs String controllerName = config.getInitParameter("controllerName"); String awRequestCreatorName = config.getInitParameter("awRequestCreatorName"); if(StringUtils.isEmptyOrWhitespaceOnly(controllerName)) { throw new ServletException("Invalid web.xml. Missing controllerName init param. Servlet " + servletName + " cannot be initialized and put into service."); } if(StringUtils.isEmptyOrWhitespaceOnly(awRequestCreatorName)) { throw new ServletException("Invalid web.xml. Missing awRequestCreatorName init param. Servlet " + servletName + " cannot be initialized and put into service."); } // OK, now get the beans out of the Spring ApplicationContext // If the beans do not exist within the Spring configuration, Spring will throw a RuntimeException and initialization // of this Servlet will fail. (check catalina.out in addition to aw.log) ServletContext servletContext = config.getServletContext(); ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); _controller = (Controller) applicationContext.getBean(controllerName); _awRequestCreator = (AwRequestCreator) applicationContext.getBean(awRequestCreatorName); _logger.info("Servlet " + servletName + " successfully put into service"); } /** * Services the user requests to the URLs bound to this Servlet as configured in web.xml. */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // allow Tomcat to handle Servlet and IO Exceptions // Map data from the inbound request to our internal format AwRequest awRequest = _awRequestCreator.createFrom(request); Writer writer = null; try { // Execute feature-specific logic _controller.execute(awRequest); // Prepare for sending the response to the client writer = new BufferedWriter(new OutputStreamWriter(getOutputStream(request, response))); String responseText = null; expireResponse(response); response.setContentType("application/json"); // Build the appropriate response if(! awRequest.isFailedRequest()) { // Convert the results to JSON for output. List<EmaQueryResult> results = (List<EmaQueryResult>) awRequest.getAttribute("emaQueryResults"); JSONArray jsonArray = new JSONArray(); for(EmaQueryResult result : results) { JSONObject entry = new JSONObject(); entry.put("response", new JSONObject(result.getJsonData()).get("response")); entry.put("time", result.getTimestamp()); entry.put("timezone", result.getTimezone()); jsonArray.put(entry); } responseText = jsonArray.toString(); } else { responseText = awRequest.getFailedRequestErrorMessage(); } // Write the ouptut writer.write(responseText); } catch(Throwable t) { _logger.error("an error occurred running an EMA query", t); writer.write("{\"error_code\":\"0103\",\"error_text\":\"" + t.getMessage() + "\"}"); } finally { if(null != writer) { writer.flush(); writer.close(); } } } /** * Dispatches to processRequest(). */ @Override protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } /** * Dispatches to processRequest(). */ @Override protected final void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } }
package de.university.reutlingen.aufgabe2.a2; import java.util.ArrayList; import de.university.reutlingen.aufgabe2.a2.ProductDescription; public class Main { public static void main(String[] args) { Produkt<ProductDescription>[] products = new Produkt[4]; products[0] = new Produkt<ProductDescription>(new ProductDescription("Adobe kostet auf NYSE ", " Stuck kostet 5.6 - 10 Stucke "),56); products[1] = new Produkt<ProductDescription>(new ProductDescription("Adobe CS6 - Dreamweaver is the best. "," Stuck kostet 65.33 - 10 Stucke"), 651.33); products[2] = new Produkt<ProductDescription>(new ProductDescription("Microsoft costs auf NASDAQ "," Stuck kostet 0 - 10 Stucke"), 0); products[3] = new Produkt<ProductDescription>(new ProductDescription("Apple will make iTV "," Stuck kostet 5600 - 10 Stucke"), 56_000); for (Produkt<ProductDescription> i : products) { System.out.println(i.getProduktBeschreibung() + " "+ i.getProduktPreis()); } System.out.println(""); // This is better, because uses ArrayLists. ArrayList<Produkt<ProductDescription>> produktLists = new ArrayList<>(); ProductDescription pd = new ProductDescription("Adobe ist besser als Apple. NYSE: ", "564.5146"); produktLists.add(new Produkt<ProductDescription>(pd,0)); // 0 kommt von double, wird nicht gezeigt. produktLists.add(new Produkt<ProductDescription>(new ProductDescription("I love Trees", null) ,0)); for (Produkt<ProductDescription> g : produktLists) { System.out.println(g.getProduktBeschreibung()+ " " + g.getProduktPreis()); } } }
package com.hubspot.blazar.base; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Optional; import com.hubspot.rosetta.annotations.StoredAsJson; import java.util.Objects; public class Build { public enum State { QUEUED(false), LAUNCHING(false), IN_PROGRESS(false), SUCCEEDED(true), CANCELLED(true), FAILED(true); private final boolean completed; State(boolean completed) { this.completed = completed; } public boolean isComplete() { return completed; } } private final Optional<Long> id; private final int moduleId; private final int buildNumber; private final State state; private final Optional<Long> startTimestamp; private final Optional<Long> endTimestamp; private final Optional<String> sha; @StoredAsJson private final Optional<CommitInfo> commitInfo; private final Optional<String> log; private final Optional<String> taskId; @StoredAsJson private final Optional<BuildConfig> buildConfig; @StoredAsJson private final Optional<BuildConfig> resolvedConfig; @JsonCreator public Build(@JsonProperty("id") Optional<Long> id, @JsonProperty("moduleId") int moduleId, @JsonProperty("buildNumber") int buildNumber, @JsonProperty("state") State state, @JsonProperty("startTimestamp") Optional<Long> startTimestamp, @JsonProperty("endTimestamp") Optional<Long> endTimestamp, @JsonProperty("sha") Optional<String> sha, @JsonProperty("commitInfo") Optional<CommitInfo> commitInfo, @JsonProperty("log") Optional<String> log, @JsonProperty("taskId") Optional<String> taskId, @JsonProperty("buildConfig") Optional<BuildConfig> buildConfig, @JsonProperty("resolvedConfig") Optional<BuildConfig> resolvedConfig) { this.id = id; this.moduleId = moduleId; this.buildNumber = buildNumber; this.state = state; this.startTimestamp = startTimestamp; this.endTimestamp = endTimestamp; this.sha = sha; this.taskId = taskId; this.commitInfo = com.google.common.base.Objects.firstNonNull(commitInfo, Optional.<CommitInfo>absent()); this.log = log; this.buildConfig = buildConfig; this.resolvedConfig = resolvedConfig; } public static Build queuedBuild(Module module, int buildNumber) { Optional<Long> absentLong = Optional.absent(); Optional<String> absentString = Optional.absent(); Optional<CommitInfo> commitInfo = Optional.absent(); Optional<BuildConfig> config = Optional.absent(); return new Build(absentLong, module.getId().get(), buildNumber, State.QUEUED, absentLong, absentLong, absentString, commitInfo, absentString, absentString, config, config); } public Optional<Long> getId() { return id; } public int getModuleId() { return moduleId; } public int getBuildNumber() { return buildNumber; } public State getState() { return state; } public Optional<Long> getStartTimestamp() { return startTimestamp; } public Optional<Long> getEndTimestamp() { return endTimestamp; } public Optional<String> getSha() { return sha; } public Optional<CommitInfo> getCommitInfo() { return commitInfo; } public Optional<String> getLog() { return log; } public Optional<String> getTaskId() { return taskId; } public Optional<BuildConfig> getBuildConfig() { return buildConfig; } public Optional<BuildConfig> getResolvedConfig() { return resolvedConfig; } public Build withId(long id) { return new Build(Optional.of(id), moduleId, buildNumber, state, startTimestamp, endTimestamp, sha, commitInfo, log, taskId, buildConfig, resolvedConfig); } public Build withCommitInfo(CommitInfo commitInfo) { Optional<String> sha = Optional.of(commitInfo.getCurrent().getId()); return new Build(id, moduleId, buildNumber, state, startTimestamp, endTimestamp, sha, Optional.of(commitInfo), log, taskId, buildConfig, resolvedConfig); } public Build withState(State state) { return new Build(id, moduleId, buildNumber, state, startTimestamp, endTimestamp, sha, commitInfo, log, taskId, buildConfig, resolvedConfig); } public Build withStartTimestamp(long startTimestamp) { return new Build(id, moduleId, buildNumber, state, Optional.of(startTimestamp), endTimestamp, sha, commitInfo, log, taskId, buildConfig, resolvedConfig); } public Build withEndTimestamp(long endTimestamp) { return new Build(id, moduleId, buildNumber, state, startTimestamp, Optional.of(endTimestamp), sha, commitInfo, log, taskId, buildConfig, resolvedConfig); } public Build withLog(String log) { return new Build(id, moduleId, buildNumber, state, startTimestamp, endTimestamp, sha, commitInfo, Optional.of(log), taskId, buildConfig, resolvedConfig); } public Build withBuildConfig(BuildConfig buildConfig) { return new Build(id, moduleId, buildNumber, state, startTimestamp, endTimestamp, sha, commitInfo, log, taskId, Optional.of(buildConfig), resolvedConfig); } public Build withResolvedConfig(BuildConfig resolvedConfig) { return new Build(id, moduleId, buildNumber, state, startTimestamp, endTimestamp, sha, commitInfo, log, taskId, buildConfig, Optional.of(resolvedConfig)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Build build = (Build) o; return Objects.equals(moduleId, build.moduleId) && Objects.equals(buildNumber, build.buildNumber); } @Override public int hashCode() { return Objects.hash(moduleId, buildNumber); } }
package edu.columbia.gemma.controller; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.lang.NullArgumentException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.validation.BindException; import org.springframework.web.bind.RequestUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.servlet.view.RedirectView; import edu.columbia.gemma.loader.loaderutils.BulkCreator; public class LoaderController extends SimpleFormController { private Configuration conf; /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog( getClass() ); /** * @throws ConfigurationException */ public LoaderController() throws ConfigurationException { conf = new PropertiesConfiguration( "loader.properties" ); } /** * Obtains filename to be read from the form. * * @param command * @return ModelAndView * @throws IOException * @throws NumberFormatException */ public ModelAndView onSubmit( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors ) throws IOException, NumberFormatException { Map myModel = new HashMap(); boolean hasHeader = RequestUtils.getBooleanParameter( request, "hasHeader", false ); String typeOfLoader = RequestUtils.getStringParameter( request, "typeOfLoader", null ); BulkCreator bc = determineService( getApplicationContext(), typeOfLoader ); bc.bulkCreate( determineFilename( typeOfLoader ), hasHeader ); return new ModelAndView( new RedirectView( getSuccessView() ), "model", myModel ); } /** * Determine file to read based on loader selected. * * @param typeOfLoader * @return String TODO use reflection */ private String determineFilename( String typeOfLoader ) { String filename = null; if ( typeOfLoader.equals( "geneLoaderService" ) ) filename = conf.getString( "loader.filename.gene" ); else if ( typeOfLoader.equals( "taxonLoaderService" ) ) filename = conf.getString( "loader.filename.taxon" ); else if ( typeOfLoader.equals( "chromosomeLoaderService" ) ) filename = conf.getString( "loader.filename.chromosome" ); else if ( typeOfLoader.equals( "arrayDesignLoaderService" ) ) filename = conf.getString( "loader.filename.arrayDesign" ); return filename; } private BulkCreator determineService( ApplicationContext ctx, String typeOfLoader ) throws NullArgumentException { return ( BulkCreator ) ctx.getBean( typeOfLoader ); } /** * This is needed or you will have to specify a commandClass in the DispatcherServlet's context * * @param request * @return Object * @throws Exception */ protected Object formBackingObject( HttpServletRequest request ) throws Exception { return request; } }
package org.voovan.tools.log; import org.voovan.tools.TEnv; import org.voovan.tools.TString; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Formatter; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.atomic.AtomicBoolean; public class LoggerThread implements Runnable { private ConcurrentLinkedDeque<Object> logQueue; private ConcurrentLinkedDeque<String> logCacheQueue; private OutputStream[] outputStreams; private AtomicBoolean finished = new AtomicBoolean(false); private Thread thread; private int pause = 0; // 0: , 1: , 2: /** * * @param outputStreams */ public LoggerThread(OutputStream[] outputStreams) { this.logQueue = new ConcurrentLinkedDeque<Object>(); this.logCacheQueue = new ConcurrentLinkedDeque<String>(); this.outputStreams = outputStreams; TEnv.addShutDownHook(()->{ while(!logQueue.isEmpty() || !logCacheQueue.isEmpty()) { TEnv.sleep(10); if(!Logger.isEnable()) { try { output(); } catch (IOException e) { e.printStackTrace(); } } } Logger.setEnable(false); }); } /** * * @return true: , false: */ public boolean isFinished() { return finished.get() || !thread.isAlive(); } /** * * @return true: , false: */ public boolean pause(){ pause = 1; return TEnv.wait(3000, ()-> pause != 2); } public void unpause(){ pause = 0; } public Thread getThread() { return thread; } protected void setThread(Thread thread) { this.thread = thread; } /** * * @return */ public OutputStream[] getOutputStreams() { return outputStreams; } /** * * @param outputStreams */ public void setOutputStreams(OutputStream[] outputStreams) { if(outputStreams != null) { for (OutputStream outputStream : getOutputStreams()) { if (outputStream instanceof FileOutputStream) { try { ((FileOutputStream) outputStream).close(); } catch (IOException e) { e.printStackTrace(); } } } } this.outputStreams = outputStreams; } /** * * * @param msg */ public void addLogMessage(Object msg) { logQueue.offer(msg); } @Override public void run() { try { while (Logger.isEnable()) { try { if (this.pause == 1) { flush(); this.pause = 2; } if (this.pause != 0) { Thread.sleep(100); continue; } if (logQueue.isEmpty()) { flush(); TEnv.sleep(10); continue; } output(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("[FRAMEWORK] Main logger thread is terminaled"); flush(); } finally { close(); finished.set(true); } } public String renderMessage(Object obj){ String formatedMessage = null; if (obj instanceof String) { formatedMessage = (String) obj; } else if(obj instanceof Message) { Message msg = (Message) obj; msg.format(); if("SIMPLE".equals(msg.getLevel())){ formatedMessage = Logger.formater.simpleFormat(msg)+"\r\n"; }else{ formatedMessage = Logger.formater.format(msg); } } return formatedMessage; } /** * * @return true: , false: * @throws IOException IO */ public boolean output() throws IOException { Object obj = logQueue.poll(); String formatedMessage = renderMessage(obj); if (formatedMessage != null && this.outputStreams != null) { for (OutputStream outputStream : outputStreams) { if (outputStream != null) { if (LoggerStatic.HAS_COLOR && !(outputStream instanceof PrintStream)) { formatedMessage = TString.fastReplaceAll(formatedMessage, "\033\\[\\d{2}m", ""); } if(outputStream instanceof FileOutputStream) { if(!((FileOutputStream)outputStream).getChannel().isOpen()){ logCacheQueue.add(formatedMessage); continue; } else { while(true) { String message = logCacheQueue.poll(); if(message!=null) { outputStream.write(message.getBytes()); } else { break; } } } } outputStream.write(formatedMessage.getBytes()); } } return true; } else { return false; } } /** * OutputStream */ public void close() { try { for (OutputStream outputStream : outputStreams) { if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { e.printStackTrace(); } } public void flush(){ for (OutputStream outputStream : outputStreams) { if (outputStream != null) { try { outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Web * @param outputStreams * @return */ public synchronized static LoggerThread start(OutputStream[] outputStreams) { LoggerThread loggerThread = new LoggerThread(outputStreams); Thread loggerMainThread = new Thread(loggerThread,"VOOVAN@LOGGER_THREAD"); loggerMainThread.setDaemon(true); loggerMainThread.setPriority(1); loggerMainThread.start(); loggerThread.setThread(loggerMainThread); return loggerThread; } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.exception.InvalidSessionException; import gov.nih.nci.calab.exception.NoAccessException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; public abstract class AbstractDispatchAction extends DispatchAction { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; // response.setHeader("Cache-Control", "no-cache"); if (isCancelled(request)) return mapping.findForward("cancel"); // TODO fill in the common operations */ if (!loginRequired() || loginRequired() && isUserLoggedIn(request)) { if (loginRequired()) { String dispatch = request.getParameter("dispatch"); // check whether user have access to the class boolean accessStatus = canUserExecute(request.getSession()); //if dispatch is view or accessStatus is true don't throw exception if (!dispatch.equals("view") && !accessStatus) { throw new NoAccessException( "You don't have access to class: " + this.getClass().getName()); } } forward = super.execute(mapping, form, request, response); } else { throw new InvalidSessionException(); } return forward; } /** * * @param request * @return whether the user is successfully logged in. */ private boolean isUserLoggedIn(HttpServletRequest request) { boolean isLoggedIn = false; if (request.getSession().getAttribute("user") != null) { isLoggedIn = true; } return isLoggedIn; } public abstract boolean loginRequired(); /** * Check whether the current user in the session can perform the action * * @param session * @return * @throws Exception */ public boolean canUserExecute(HttpSession session) throws Exception { return InitSessionSetup.getInstance().canUserExecuteClass(session, this.getClass()); } }
package gov.nih.nci.calab.ui.search; /** * This class searches workflows based on user supplied criteria. * * @author pansu */ /* CVS $Id: SearchWorkflowAction.java,v 1.11 2006-05-08 15:08:40 zengje Exp $ */ import gov.nih.nci.calab.dto.search.WorkflowResultBean; import gov.nih.nci.calab.service.search.SearchWorkflowService; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.core.AbstractBaseAction; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class SearchWorkflowAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorForm theForm = (DynaValidatorForm) form; String assayName = (String) theForm.get("assayName"); String assayType = ((String) theForm.get("assayType")).trim(); String assayRunDateBeginStr = (String) theForm.get("assayRunDateBegin"); String assayRunDateEndStr = (String) theForm.get("assayRunDateEnd"); Date assayRunDateBegin = assayRunDateBeginStr.length() == 0 ? null : StringUtils.convertToDate(assayRunDateBeginStr, "MM/dd/yyyy"); Date assayRunDateEnd = assayRunDateEndStr.length() == 0 ? null : StringUtils.convertToDate(assayRunDateEndStr, "MM/dd/yyyy"); String aliquotName = (String) theForm.get("aliquotName"); boolean excludeMaskedAliquots = ((String) theForm .get("excludeMaskedAliquots")).equals("on") ? true : false; String fileName = (String) theForm.get("fileName"); boolean isFileInput = ((String) theForm.get("isFileIn")).equals("on") ? true : false; boolean isFileOutput = ((String) theForm.get("isFileOut")).equals("on") ? true : false; String fileSubmissionDateBeginStr = (String) theForm .get("fileSubmissionDateBegin"); String fileSubmissionDateEndStr = (String) theForm .get("fileSubmissionDateEnd"); Date fileSubmissionDateBegin = fileSubmissionDateBeginStr.length() == 0 ? null : StringUtils.convertToDate(fileSubmissionDateBeginStr, "MM/dd/yyyy"); Date fileSubmissionDateEnd = fileSubmissionDateEndStr.length() == 0 ? null : StringUtils.convertToDate(fileSubmissionDateEndStr, "MM/dd/yyyy"); // Add one day to the fileSubmissionDateEnd to include all the files files during the day if (fileSubmissionDateEnd != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(fileSubmissionDateEnd); calendar.add(Calendar.DAY_OF_MONTH, 1); fileSubmissionDateEnd = calendar.getTime(); } String fileSubmitter = (String) theForm.get("fileSubmitter"); boolean excludeMaskedFiles = ((String) theForm .get("excludeMaskedFiles")).equals("on") ? true : false; String criteriaJoin = (String) theForm.get("criteriaJoin"); // pass the parameters to the searchWorkflowService SearchWorkflowService searchWorkflowService = new SearchWorkflowService(); List<WorkflowResultBean> workflows = searchWorkflowService .searchWorkflows(assayName, assayType, assayRunDateBegin, assayRunDateEnd, aliquotName, excludeMaskedAliquots, fileName, isFileInput, isFileOutput, fileSubmissionDateBegin, fileSubmissionDateEnd, fileSubmitter, excludeMaskedFiles, criteriaJoin); if (workflows == null || workflows.isEmpty()) { ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage( "message.searchWorkflow.noResult"); msgs.add("message", msg); saveMessages(request, msgs); forward = mapping.getInputForward(); } else { request.setAttribute("workflows", workflows); forward = mapping.findForward("success"); } return forward; } public boolean loginRequired() { return true; } }
package gov.nih.nci.cananolab.dto.common; import gov.nih.nci.cananolab.domain.common.Author; import gov.nih.nci.cananolab.domain.common.Publication; import gov.nih.nci.cananolab.util.DateUtils; import gov.nih.nci.cananolab.util.StringUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Publication view bean * * @author tanq, pansu * */ public class PublicationBean extends FileBean { private static final String delimiter = ";"; private String[] sampleNames; private String[] researchAreas; private List<Author> authors = new ArrayList<Author>(); private Author theAuthor = new Author(); private String displayName = "";; public PublicationBean() { domainFile = new Publication(); domainFile.setUriExternal(false); } public PublicationBean(Publication publication) { super(publication); this.domainFile = publication; String researchAreasStr = publication.getResearchArea(); if (researchAreasStr != null && researchAreasStr.length() > 0) { researchAreas = researchAreasStr.split(delimiter); } else { researchAreas = null; } Collection<Author> authorCollection = publication.getAuthorCollection(); if (authorCollection != null && authorCollection.size() > 0) { List<Author> authorslist = new ArrayList<Author>(authorCollection); Collections.sort(authorslist, new Comparator<Author>() { public int compare(Author o1, Author o2) { return (int) (o1.getCreatedDate().compareTo(o2 .getCreatedDate())); } }); authors = authorslist; } } public PublicationBean(Publication publication, String[] sampleNames) { this(publication); this.sampleNames = sampleNames; } public boolean equals(Object obj) { boolean eq = false; if (obj instanceof PublicationBean) { PublicationBean c = (PublicationBean) obj; Long thisId = this.domainFile.getId(); if (thisId != null && thisId.equals(c.getDomainFile().getId())) { eq = true; } } return eq; } public String[] getSampleNames() { return sampleNames; } public void setSampleNames(String[] sampleNames) { this.sampleNames = sampleNames; } /** * @return the researchAreas */ public String[] getResearchAreas() { return researchAreas; } /** * @param researchAreas * the researchAreas to set */ public void setResearchAreas(String[] researchAreas) { this.researchAreas = researchAreas; } /** * @return the authors */ public List<Author> getAuthors() { return authors; } /** * @param authors * the authors to set */ public void setAuthors(List<Author> authors) { this.authors = authors; } // /** // * @return the authorsStr // */ // public String getAuthorsStr() { // return authorsStr; // /** // * @param authorsStr the authorsStr to set // */ // public void setAuthorsStr(String authorsStr) { // this.authorsStr = authorsStr; public void addAuthor() { authors.add(new Author()); } public void removeAuthor(int ind) { authors.remove(ind); } private String getAuthorsDisplayName() { List<String> strs = new ArrayList<String>(); for (Author author : authors) { String authorDisplayName = ""; List<String> authorStrs = new ArrayList<String>(); authorStrs.add(author.getLastName()); authorStrs.add(author.getInitial()); authorDisplayName = StringUtils.join(authorStrs, ", "); strs.add(authorDisplayName); } return StringUtils.join(strs, ", "); } private String getPublishInfoDisplayName() { Publication pub = (Publication) domainFile; String publishInfo = ""; if (pub.getYear() != null) { publishInfo += pub.getYear().toString() + "; "; } if (!StringUtils.isEmpty((pub.getVolume()))) { publishInfo += pub.getVolume() + ":"; } if (pub.getVolume() != null && pub.getStartPage() != null && pub.getEndPage() != null) { publishInfo += pub.getStartPage() + "-" + pub.getEndPage(); } return publishInfo; } public String getPubMedDisplayName() { Publication pub = (Publication) domainFile; if (pub.getPubMedId() != null) { StringBuilder sb = new StringBuilder("<a target='_abstract' href="); sb.append("http: sb.append(pub.getPubMedId()); sb.append(">"); sb.append("PMID: " + pub.getPubMedId()); sb.append("</a>"); return sb.toString(); } else { return null; } } private String getDOIDisplayName() { Publication pub = (Publication) domainFile; if (!StringUtils.isEmpty(pub.getDigitalObjectId())) { StringBuilder sb = new StringBuilder("<a target='_abstract' href="); sb.append("http://dx.doi.org/"); sb.append(pub.getDigitalObjectId()); sb.append(">"); sb.append("DOI: " + pub.getDigitalObjectId()); sb.append("</a>"); return sb.toString(); } else { return null; } } private String getUriDisplayName() { Publication pub = (Publication) domainFile; if (!StringUtils.isEmpty(pub.getUri())) { StringBuilder sb = new StringBuilder("<a href="); sb.append("publication.do?dispatch=download&publicationId="); sb.append(pub.getId()); sb.append("&location="); sb.append(getLocation()); sb.append(" target='"); sb.append(getUrlTarget()); sb.append("'>"); sb.append(pub.getName()); sb.append("</a>"); return sb.toString(); } else { return null; } } public String getDisplayName() { // standard PubMed journal citation format // e.g. Freedman SB, Adler M, Seshadri R, Powell EC. Oral ondansetron // for gastroenteritis in a pediatric emergency department. N Engl J // Med. 2006 Apr 20;354(16):1698-705. PubMed PMID: 12140307. Publication pub = (Publication) domainFile; List<String> strs = new ArrayList<String>(); strs.add(getAuthorsDisplayName()); // remove last . in the title if (pub.getTitle().endsWith(".")) { pub.getTitle().substring(0, pub.getTitle().length() - 2); } strs.add(pub.getTitle()); strs.add(pub.getJournalName()); strs.add(getPublishInfoDisplayName()); strs.add(getPubMedDisplayName()); strs.add(getDOIDisplayName()); strs.add(getUriDisplayName()); displayName = StringUtils.join(strs, ". ") + "."; return displayName; } public void setupDomain(String internalUriPath, String createdBy, int index) throws Exception { super.setupDomainFile(internalUriPath, createdBy, 0); Publication domain = (Publication) domainFile; if (domain.getPubMedId() != null && domain.getPubMedId() == 0) { domain.setPubMedId(null); } if (domain.getYear() != null && domain.getYear() == 0) { domain.setYear(null); } if (researchAreas != null && researchAreas.length > 0) { String researchAreasStr = StringUtils.join(researchAreas, ";"); domain.setResearchArea(researchAreasStr); } for (Author author : authors) { if (!StringUtils.isEmpty(author.getFirstName()) || !StringUtils.isEmpty(author.getLastName()) || !StringUtils.isEmpty(author.getInitial())) { if (author.getCreatedDate() == null) { author.setCreatedDate(DateUtils.addSecondsToCurrentDate(1)); } if (author.getCreatedBy() == null || author.getCreatedBy().trim().length() == 0) { author.setCreatedBy(createdBy); } } else { author = null; } } } public Author getTheAuthor() { return theAuthor; } public void setTheAuthor(Author theAuthor) { this.theAuthor = theAuthor; } public void addAuthor(Author author) { // if an old one exists, remove it first int index = authors.indexOf(author); if (index != -1) { authors.remove(author); // retain the original order authors.add(index, author); } else { authors.add(author); } } public void removeAuthor(Author author) { authors.remove(author); } }
package gov.nih.nci.cananolab.service.common; import gov.nih.nci.cananolab.domain.common.LabFile; import gov.nih.nci.cananolab.dto.common.LabFileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException; import gov.nih.nci.cananolab.exception.FileException; import gov.nih.nci.cananolab.exception.NoAccessException; import gov.nih.nci.cananolab.service.security.AuthorizationService; import gov.nih.nci.cananolab.system.applicationservice.CustomizedApplicationService; import gov.nih.nci.cananolab.util.CaNanoLabConstants; import gov.nih.nci.cananolab.util.PropertyReader; import gov.nih.nci.cananolab.util.StringUtils; import gov.nih.nci.system.client.ApplicationServiceProvider; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Property; /** * Utility service for file retrieving and writing. * * @author pansu * */ public class FileService { Logger logger = Logger.getLogger(FileService.class); public FileService() { } /** * Load the file for the given fileId from the database * * @param fileId * @return */ public LabFileBean findFile(String fileId) throws FileException { LabFileBean fileBean = null; try { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); DetachedCriteria crit = DetachedCriteria.forClass(LabFile.class) .add(Property.forName("id").eq(new Long(fileId))); List result = appService.query(crit); if (!result.isEmpty()) { fileBean = new LabFileBean((LabFile) result.get(0)); } return fileBean; } catch (Exception e) { logger.error("Problem finding the file by id: " + fileId, e); throw new FileException(); } } /** * Load the file for the given fileId from the database. Also check whether * user can do it. * * @param fileId * @return */ public LabFileBean findFile(String fileId, UserBean user) throws FileException, CaNanoLabSecurityException { LabFileBean fileBean = null; try { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); DetachedCriteria crit = DetachedCriteria.forClass(LabFile.class) .add(Property.forName("id").eq(new Long(fileId))); List result = appService.query(crit); if (!result.isEmpty()) { fileBean = new LabFileBean((LabFile) result.get(0)); } AuthorizationService auth = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); if (auth.isUserAllowed(fileBean.getDomainFile().getId().toString(), user)) { return fileBean; } else { throw new NoAccessException(); } } catch (Exception e) { logger.error("Problem finding the file by id: " + fileId, e); throw new FileException(); } } public void saveCopiedFileAndSetVisibility(LabFile copy, UserBean user, String oldSampleName, String newSampleName) throws Exception { // the copied file has been persisted with the same URI but createdBy is // COPY LabFile file = findFileByUri(copy.getUri()); copy.setUri(copy.getUri().replaceFirst(oldSampleName, newSampleName)); saveFile(copy); byte[] content = this.getFileContent(file.getId()); this.writeFile(copy, content); AuthorizationService auth = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); LabFileBean fileBean = new LabFileBean(file); this.retrieveVisibility(fileBean, user); auth.assignVisibility(copy.getId().toString(), fileBean .getVisibilityGroups()); } public LabFile findFileByUri(String uri) throws FileException { LabFile file = null; try { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); DetachedCriteria crit = DetachedCriteria .forClass(LabFile.class) .add(Property.forName("uri").eq(uri)) .add( Property .forName("createdBy") .ne( CaNanoLabConstants.AUTO_COPY_ANNOTATION_PREFIX)); List results = appService.query(crit); file = (LabFile) results.get(0); return file; } catch (Exception e) { String err = "Could not find the file by uri"; logger.error(err, e); throw new FileException(err, e); } } /** * Write content of the file to the given output stream * * @param fileId * @param out * @throws FileException */ public void writeFileContent(Long fileId, OutputStream out) throws FileException { try { LabFileBean fileBean = findFile(fileId.toString()); String fileRoot = PropertyReader .getProperty(CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File fileObj = new File(fileRoot + File.separator + fileBean.getDomainFile().getUri()); InputStream in = new FileInputStream(fileObj); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } catch (HibernateException e) { String err = "Error getting file meta data from the database."; this.logger.error(err, e); throw new FileException(err, e); } catch (IOException e) { String err = "Error getting file content from the file system and writing to the output stream."; this.logger.error(err, e); throw new FileException(err, e); } } /** * Get the content of the file into a byte array. * * @param fileId * @return * @throws FileException */ public byte[] getFileContent(Long fileId) throws FileException { try { LabFileBean fileBean = findFile(fileId.toString()); if (fileBean == null || fileBean.getDomainFile().getUri() == null) { return null; } // check if the file is external link if (fileBean.getDomainFile().getUri().startsWith("http")) { return null; } String fileRoot = PropertyReader .getProperty(CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File fileObj = new File(fileRoot + File.separator + fileBean.getDomainFile().getUri()); long fileLength = fileObj.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (fileLength > Integer.MAX_VALUE) { logger .error("The file is too big. Byte array can't be longer than Java Integer MAX_VALUE"); throw new FileException( "The file is too big. Byte array can't be longer than Java Integer MAX_VALUE"); } // Create the byte array to hold the data byte[] fileData = new byte[(int) fileLength]; // Read in the bytes InputStream is = new FileInputStream(fileObj); int offset = 0; int numRead = 0; while (offset < fileData.length && (numRead = is.read(fileData, offset, fileData.length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < fileData.length) { throw new FileException("Could not completely read file " + fileObj.getName()); } // Close the input stream and return bytes is.close(); return fileData; } catch (IOException e) { String err = "Error getting file content from the file system and writing to the output stream."; this.logger.error(err, e); throw new FileException(err, e); } } public String writeFile(byte[] fileContent, String fileName, String filePath, boolean addTimeStampPrefix) throws IOException { File pathDir = new File(filePath); if (!pathDir.exists()) pathDir.mkdirs(); if (addTimeStampPrefix) { fileName = prefixFileNameWithTimeStamp(fileName); } String fullFileName = filePath + File.separator + fileName; FileOutputStream oStream = new FileOutputStream(new File(fullFileName)); oStream.write(fileContent); return fileName; } private void writeFile(byte[] fileContent, String fullFileName) throws IOException { String path = fullFileName.substring(0, fullFileName.lastIndexOf("/")); File pathDir = new File(path); if (!pathDir.exists()) pathDir.mkdirs(); File file = new File(fullFileName); if (file.exists()) { return; // don't save again } FileOutputStream oStream = new FileOutputStream(new File(fullFileName)); oStream.write(fileContent); } private void writeFile(InputStream is, FileOutputStream os) throws IOException { byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = is.read(bytes)) > 0) { os.write(bytes, 0, numRead); } os.close(); } public static String prefixFileNameWithTimeStamp(String fileName) { String newFileName = StringUtils.convertDateToString(new Date(), "yyyyMMdd_HH-mm-ss-SSS") + "_" + fileName; return newFileName; } // save to the file system fileData is not empty public void writeFile(LabFile file, byte[] fileData) throws FileException { try { if (fileData != null) { FileService fileService = new FileService(); String rootPath = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); String fullFileName = rootPath + "/" + file.getUri(); fileService.writeFile(fileData, fullFileName); } } catch (Exception e) { logger.error("Problem writing file " + file.getUri() + " to the file system."); throw new FileException(); } } /** * save the meta data associated with a file stored in the database * * @param file * @throws FileException */ public void saveFile(LabFile file) throws FileException { try { CustomizedApplicationService appService = (CustomizedApplicationService) ApplicationServiceProvider .getApplicationService(); appService.saveOrUpdate(file); } catch (Exception e) { logger.error("Problem saving file: ", e); throw new FileException(); } } // retrieve file visibility public void retrieveVisibility(LabFileBean fileBean, UserBean user) throws FileException { try { AuthorizationService auth = new AuthorizationService( CaNanoLabConstants.CSM_APP_NAME); if (fileBean.getDomainFile().getId() != null && auth.isUserAllowed(fileBean.getDomainFile().getId() .toString(), user)) { fileBean.setHidden(false); // get assigned visible groups List<String> accessibleGroups = auth.getAccessibleGroups( fileBean.getDomainFile().getId().toString(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); } else { fileBean.setHidden(true); } } catch (Exception e) { String err = "Error in setting file visibility for " + fileBean.getDisplayName(); logger.error(err, e); throw new FileException(err, e); } } }
package gr.uoi.cs.daintiness.hecate.metrics; /** * @author iskoulis * */ public class TableChanges { int version; int insertions; int deletions; int keyChange; int attrTypeChange; public TableChanges() { this.version = 0; this.insertions = 0; this.deletions = 0; this.keyChange = 0; this.attrTypeChange = 0; } public int getVersion() { return version; } public int getInsertions() { return insertions; } public int getDeletions() { return deletions; } public int getKeyChange() { return keyChange; } public int getAttrTypeChange() { return attrTypeChange; } }
package io.jchat.android.activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import cn.jpush.im.android.api.JMessageClient; import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback; import cn.jpush.im.android.api.callback.GetUserInfoCallback; import cn.jpush.im.android.api.model.Conversation; import cn.jpush.im.android.api.model.GroupInfo; import cn.jpush.im.android.api.model.UserInfo; import cn.jpush.im.android.eventbus.EventBus; import io.jchat.android.R; import io.jchat.android.application.JPushDemoApplication; import io.jchat.android.controller.FriendInfoController; import io.jchat.android.entity.Event; import io.jchat.android.tools.BitmapLoader; import io.jchat.android.tools.DialogCreator; import io.jchat.android.tools.HandleResponseCode; import io.jchat.android.view.FriendInfoView; public class FriendInfoActivity extends BaseActivity { private FriendInfoView mFriendInfoView; private FriendInfoController mFriendInfoController; private String mTargetID; private long mGroupID; private UserInfo mUserInfo; private String mNickname; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_friend_info); mFriendInfoView = (FriendInfoView) findViewById(R.id.friend_info_view); mTargetID = getIntent().getStringExtra(JPushDemoApplication.TARGET_ID); mGroupID = getIntent().getLongExtra(JPushDemoApplication.GROUP_ID, 0); Conversation conv; conv = JMessageClient.getSingleConversation(mTargetID); if (conv == null) { conv = JMessageClient.getGroupConversation(mGroupID); GroupInfo groupInfo = (GroupInfo) conv.getTargetInfo(); mUserInfo = groupInfo.getGroupMemberInfo(mTargetID); } else { mUserInfo = (UserInfo) conv.getTargetInfo(); } mFriendInfoView.initModule(); //ConversationUserInfo mFriendInfoView.initInfo(mUserInfo); mFriendInfoController = new FriendInfoController(mFriendInfoView, this); mFriendInfoView.setListeners(mFriendInfoController); //UserInfo final Dialog dialog = DialogCreator.createLoadingDialog(FriendInfoActivity.this, FriendInfoActivity.this.getString(R.string.loading)); dialog.show(); JMessageClient.getUserInfo(mTargetID, new GetUserInfoCallback() { @Override public void gotResult(int status, String desc, final UserInfo userInfo) { dialog.dismiss(); if (status == 0) { mNickname = userInfo.getNickname(); mFriendInfoView.initInfo(userInfo); } else { HandleResponseCode.onHandle(FriendInfoActivity.this, status, false); } } }); } /** * startActivitysetResult * finish */ public void startChatActivity() { if (mGroupID != 0) { Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(JPushDemoApplication.TARGET_ID, mTargetID); intent.setClass(this, ChatActivity.class); startActivity(intent); } else { Intent intent = new Intent(); intent.putExtra("returnChatActivity", true); intent.putExtra(JPushDemoApplication.NICKNAME, mNickname); setResult(JPushDemoApplication.RESULT_CODE_FRIEND_INFO, intent); } Conversation conv = JMessageClient.getSingleConversation(mTargetID); //EventBus if (conv == null) { conv = Conversation.createSingleConversation(mTargetID); EventBus.getDefault().post(new Event.StringEvent(mTargetID)); } finish(); } public String getNickname() { return mNickname; } //UserInfo public void startBrowserAvatar() { final Dialog dialog = DialogCreator.createLoadingDialog(this, this.getString(R.string.loading)); dialog.show(); mUserInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() { @Override public void gotResult(int status, String desc, Bitmap bitmap) { if (status == 0) { String path = BitmapLoader.saveBitmapToLocal(bitmap); Intent intent = new Intent(); intent.putExtra("browserAvatar", true); intent.putExtra("avatarPath", path); intent.setClass(FriendInfoActivity.this, BrowserViewPagerActivity.class); startActivity(intent); }else { HandleResponseCode.onHandle(FriendInfoActivity.this, status, false); } dialog.dismiss(); } }); } @Override public void onBackPressed() { Intent intent = new Intent(); intent.putExtra(JPushDemoApplication.NICKNAME, mNickname); setResult(JPushDemoApplication.RESULT_CODE_FRIEND_INFO, intent); finish(); super.onBackPressed(); } }
package info.guardianproject.otr.app.im.app; import info.guardianproject.otr.app.im.IImConnection; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.app.adapter.ConnectionListenerAdapter; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.engine.ImErrorInfo; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.otr.app.im.service.ImServiceConstants; import info.guardianproject.util.LogCleaner; import java.util.Collection; import java.util.HashSet; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.DeadObjectException; import android.os.Handler; import android.os.RemoteException; import android.util.Log; import android.widget.TextView; import android.widget.Toast; /** * Handle sign-in process for activities. * * @author devrandom * * <p>Users of this helper must call {@link SignInHelper#stop()} to clean up callbacks * in their onDestroy() or onPause() lifecycle methods. * * <p>The helper listens to connection events. It automatically stops listening when the * connection state is logged-in or disconnected (failed). */ public class SignInHelper { Activity mContext; private SimpleAlertHandler mHandler; private ImApp mApp; private MyConnectionListener mListener; private Collection<IImConnection> connections; private SignInListener mSignInListener; // This can be used to be informed of signin events public interface SignInListener { void connectedToService(); void stateChanged(int state, long accountId); } public SignInHelper(Activity context, SignInListener listener) { this.mContext = context; mHandler = new SimpleAlertHandler(context); mListener = new MyConnectionListener(mHandler); mSignInListener = listener; if (mApp == null) { mApp = (ImApp)mContext.getApplication(); } connections = new HashSet<IImConnection>(); } public SignInHelper(Activity context) { this(context, null); } public void setSignInListener(SignInListener listener) { mSignInListener = listener; } public void stop() { for (IImConnection connection : connections) { try { connection.unregisterConnectionListener(mListener); } catch (RemoteException e) { // Ignore } } connections.clear(); } private final class MyConnectionListener extends ConnectionListenerAdapter { MyConnectionListener(Handler handler) { super(handler); } @Override public void onConnectionStateChange(IImConnection connection, int state, ImErrorInfo error) { handleConnectionEvent(connection, state, error); } } private void handleConnectionEvent(IImConnection connection, int state, ImErrorInfo error) { long accountId; long providerId; try { accountId = connection.getAccountId(); providerId = connection.getProviderId(); } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w(ImApp.LOG_TAG, "<SigningInActivity> Connection disappeared while signing in!"); return; } if (mSignInListener != null) mSignInListener.stateChanged(state, accountId); // Stop listening if we get into a resting state if (state == ImConnection.LOGGED_IN || state == ImConnection.DISCONNECTED) { connections.remove(connection); try { connection.unregisterConnectionListener(mListener); } catch (RemoteException e) { mHandler.showServiceErrorAlert(e.getLocalizedMessage()); LogCleaner.error(ImApp.LOG_TAG, "handle connection error",e); } } if (state == ImConnection.DISCONNECTED) { // sign in failed final ProviderDef provider = mApp.getProvider(providerId); if (provider != null) //a provider might have been deleted { String providerName = provider.mName; Resources r = mContext.getResources(); String errMsg = r.getString(R.string.login_service_failed, providerName, // FIXME error == null ? "" : ErrorResUtils.getErrorRes(r, error.getCode())); Toast.makeText(mContext, errMsg, Toast.LENGTH_LONG).show(); /* new AlertDialog.Builder(mContext).setTitle(R.string.error) .setMessage() .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // FIXME } }).setCancelable(false).show(); */ } } } public void goToAccount(long accountId) { Intent intent; intent = new Intent(mContext, NewChatActivity.class); // clear the back stack of the account setup intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, accountId); mContext.startActivity(intent); // sign in successfully, finish and switch to contact list // mContext.finish(); } public void signIn(final String password, final long providerId, final long accountId, final boolean isActive) { final ProviderDef provider = mApp.getProvider(providerId); if (provider != null) //provider may be null if deleted, or db not updated yet { final String providerName = provider.mName; if (mApp.serviceConnected()) { if (mSignInListener != null) mSignInListener.connectedToService(); if (!isActive) { activateAccount(providerId, accountId); } signInAccount(password, providerId, providerName, accountId); } else { mApp.callWhenServiceConnected(mHandler, new Runnable() { public void run() { if (mApp.serviceConnected()) { if (mSignInListener != null) mSignInListener.connectedToService(); if (!isActive) { activateAccount(providerId, accountId); } signInAccount(password, providerId, providerName, accountId); } } }); } } } private void signInAccount(final String password, final long providerId, final String providerName, final long accountId) { new AsyncTask<String, Void, String> () { @Override protected String doInBackground(String... params) { try { signInAccountAsync(password, providerId, providerName, accountId); } catch (RemoteException e) { Log.d(ImApp.LOG_TAG,"error signing in",e); } return null; } @Override protected void onPostExecute(String result) { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } }.execute(""); } private void signInAccountAsync(String password, long providerId, String providerName, long accountId) throws RemoteException { boolean autoLoadContacts = true; boolean autoRetryLogin = true; IImConnection conn = null; conn = mApp.getConnection(providerId); if (conn != null) { connections.add(conn); conn.registerConnectionListener(mListener); int state = conn.getState(); if (mSignInListener != null) mSignInListener.stateChanged(state, accountId); if (state != ImConnection.DISCONNECTED) { // already signed in or in the process if (state == ImConnection.LOGGED_IN) { connections.remove(conn); conn.unregisterConnectionListener(mListener); } handleConnectionEvent(conn, state, null); return; } } else { conn = mApp.createConnection(providerId, accountId); if (conn == null) { // This can happen when service did not come up for any reason return; } connections.add(conn); conn.registerConnectionListener(mListener); } if (mApp.isNetworkAvailableAndConnected()) { conn.login(password, autoLoadContacts, autoRetryLogin); } else { promptForBackgroundDataSetting(providerName); return; } } /** * Popup a dialog to ask the user whether he/she wants to enable background * connection to continue. If yes, enable the setting and broadcast the * change. Otherwise, quit the signing in window immediately. */ private void promptForBackgroundDataSetting(String providerName) { Toast.makeText(mContext, mContext.getString(R.string.bg_data_prompt_message, providerName), Toast.LENGTH_LONG).show(); } public void activateAccount(long providerId, long accountId) { // Update the active value. We restrict to only one active // account per provider right now, so update all accounts of // this provider to inactive first and then update this // account to active. ContentValues values = new ContentValues(1); values.put(Imps.Account.ACTIVE, 0); ContentResolver cr = mContext.getContentResolver(); cr.update(Imps.Account.CONTENT_URI, values, Imps.Account.PROVIDER + "=" + providerId, null); values.put(Imps.Account.ACTIVE, 1); cr.update(ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId), values, null, null); } }
package a_BasicEexample; public class C_javaBasicVariableStringObject { //constant private static final char b = '\b'; //backSpace private static final char ff = '\f'; //formFeed private static final char lf = '\n'; //lineFeed private static final char cr = '\r'; //carriageReturn private static final char ht = '\t'; //horizontalTab private static final char dq = '\"'; //doubleQuote private static final char sq = '\''; //singleQuote private static final char bs = '\\'; //backSlash /********** * * String Concatenation - * * adding 2 string variable to create a new string variable using the + (plus operator) * */ public void StringConcatenation() { //Declare String variable and assign then a string value String stFullName ="", stFirstName = "yaki", stLastName="yak"; //String Concatenation - adding 2 string variable to create a new string variable using the + (plus operator) stFullName = stLastName + ", " + stFirstName; //the new string System.out.println("My Name is: " + stFullName); } public void PrimitiveVariableToString() { int intNumber = 123; String StringVal; StringVal = Integer.toString(intNumber); //Integer to String System.out.println("primitiveVariableToString >>> Integer to String >>> " + StringVal); /**** * StringVal = Byte.toString(byte); * StringVal = Short.toString(short); * StringVal = Integer.toString(Integer); * StringVal = Long.toString(long); * StringVal = Float.toString(float); * StringVal = Double.toString(double); * StringVal = Boolean.toString(boolean); */ } public void StringToPrimitiveVariable() { String StringVal = "321"; int intNumber = 0; intNumber = Integer.parseInt(StringVal); //String to integer System.out.println("StringToPrimitiveVariable >>> String to Integer >>> " + intNumber); /**** * short shortNumber = Short.parseShort(StringVal); * byte byteNumber = Byte.parseByte(StringVal); * int intNumber = Integer.parseInt(StringVal); * long LongNumber = Long.parseLong(StringVal); * float FloatNumber = Float.parseFloat(StringVal); * double DoubleNumber = Double.parseDouble(StringVal); * boolean booleanNumber = Boolean.parseBoolean(StringVal); */ } public void CastingNumbers() { byte byteNumber = 10; short shortNumber = 20; int intNumner = 30; long longNumber = 33l; float floatNumber = 12.32F; double doubleNumber = 1234.432; byte float2byte = (byte) floatNumber; int float2int = (int) floatNumber; short float2short = (short) floatNumber; long double2long = (long) doubleNumber; System.out.println(floatNumber + " (casting float to integer) === " + float2int); } /**** * * Generate Random Number * @param intMaxNumber - max number to generate a random number * */ public void GenerateRandomNumber(int intMaxNumber) { int intRandomNumber= 0; intMaxNumber ++; intRandomNumber = (int) (Math.random()* intMaxNumber); System.out.println("\nRandom number is (0-" + intMaxNumber + " == " + intRandomNumber); } public void TextFormatingPrintF() { byte byteNumber = -1; short shortNumber = 21; int intNumner = 321; long longNumber = 54321; float floatNumber = 12.32F; double doubleNumber = 1234.432; char ch = 'A'; String welcome = "good morning"; String [] stText = {"this", "is", "some", "text"}; int [] number = {62,73,81,64,55,43,92,54,63,74}; String StFormat = ""; /**** * * printf() * * printf(" % [flags] [width] [.precision] conversion-character * * * [flag] * - : left alignment (default alignment) * + : output a plus ( + ) or minus ( - ) sign for a numerical value * 0 : forces numerical values to be zero-padded ( default is blank padding ) * , : comma grouping separator (for numbers > 1000) * ' ' : space will display a minus sign if the number is negative or a space if it is positive * * * [width] * Specifies the field width for outputting the argument. * * * [.precision] * Specifies the floating-point values or the length * * * conversion-character * d : decimal integer [byte, short, int, long] * f : floating-point number [float, double] * c : character Capital C will uppercase the letter * s : String Capital S will uppercase all the letters in the string * h : hashcode A hashcode is like an address. This is useful for printing a reference * n : newline Platform specific newline character- use %n instead of \n for greater compatibility * */ System.out.println("\nprintf(\"byte = %-,5d \\n\" ,byteNumber);"); System.out.println("% [flags] [width] [.precision] conversion-character"); System.out.printf("byte = %10d \n" ,byteNumber); System.out.printf("short = %10d \n" ,shortNumber); System.out.printf("int = %10d \n" ,intNumner); System.out.printf("long = %10d \n" ,longNumber); System.out.printf("long = %,10d \n" ,longNumber); System.out.printf("byte = %,-10d \n" ,byteNumber); System.out.printf("short = %,-10d \n" ,shortNumber); System.out.printf("int = %,-10d \n" ,intNumner); System.out.printf("long = %,-10d \n" ,longNumber); System.out.printf("byte = %,010d \n" ,byteNumber); System.out.printf("short = %,010d \n" ,shortNumber); System.out.printf("int = %,010d \n" ,intNumner); System.out.printf("long = %,010d \n" ,longNumber); System.out.printf("char = %-10c \n" ,ch); System.out.printf("float = %-,10.5f \n" ,floatNumber); System.out.printf("double = %-,10.5f \n" ,doubleNumber); System.out.printf("String = %s %n to you", welcome); System.out.printf("%n"); for (String StringOutput: stText) { System.out.printf("%10s", StringOutput); } //formating - String.format() for (int i=0; i < number.length; i++) { StFormat = StFormat.format("%nid: %-3d ,value: %-5d ", i ,number[i]); System.out.printf("%s" ,StFormat); } } public static void main(String[] args) { C_javaBasicVariableStringObject c = new C_javaBasicVariableStringObject(); //String Concatenation c.StringConcatenation(); //Primitive Variable To String c.PrimitiveVariableToString(); //String To Primitive Variable c.StringToPrimitiveVariable(); //Casting Numbers c.CastingNumbers(); c.TextFormatingPrintF(); } }
package api.web.gw2.mapping.v2.items; import api.web.gw2.mapping.core.IdValue; import api.web.gw2.mapping.core.OptionalValue; import api.web.gw2.mapping.v2.APIv2; import java.util.List; import java.util.Optional; import java.util.OptionalInt; @APIv2(endpoint = "v2/items") // NOI18N. public interface ItemTrinketDetails extends ItemDetails { /** * Gets the type of this trinket. * @return An {@code ItemTrinketType} instance, never {@code null}. */ ItemTrinketType getType(); /** * Gets the list of infusion slots on this trinket. * @return A non-modifiable {@code List<ItemInfusionSlot>}, never {@code null}. */ List<ItemInfusionSlot> getInfusionSlots(); /** * Gets the infix upgrade on this trinket. * @return An {@code Optional<ItemInfixUpgrade>} instance, never {@code null}. */ @OptionalValue Optional<ItemInfixUpgrade> getInfixUpgrade(); /** * Gets the id of the suffix item (ie: jewel) on this trinket. * @return An {@code OptionalInt}, never {@code null}. */ @OptionalValue @IdValue OptionalInt getSuffixItemId(); /** * Gets the id of the secondary suffix item on this trinket. * @return A {@code String} instance, never {@code null}. */ @IdValue String getSecondarySuffixItemId(); }
package be.ibridge.kettle.core.dialog; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import be.ibridge.kettle.core.ColumnInfo; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.core.widget.TableView; import be.ibridge.kettle.trans.step.BaseStepDialog; /** * Displays an ArrayList of rows in a TableView. * * @author Matt * @since 19-06-2003 */ public class PreviewRowsDialog extends Dialog { private String stepname; private Label wlFields; private TableView wFields; private FormData fdlFields, fdFields; private Button wClose; private Listener lsClose; private Button wLog; private Listener lsLog; private Shell shell; private List buffer; private Props props; private String title, message; private Rectangle bounds; private int hscroll, vscroll; private int hmax, vmax; private String loggingText; /** @deprecated */ public PreviewRowsDialog(Shell parent, int style, LogWriter l, Props pr, String stepName, List rowBuffer) { this(parent, style, stepName, rowBuffer, null); } public PreviewRowsDialog(Shell parent, int style, String stepName, List rowBuffer) { this(parent, style, stepName, rowBuffer, null); } public PreviewRowsDialog(Shell parent, int style, String stepName, List rowBuffer, String loggingText) { super(parent, style); this.stepname=stepName; this.buffer=rowBuffer; this.loggingText=loggingText; props=Props.getInstance(); bounds=null; hscroll=-1; vscroll=-1; title=null; message=null; } public void setTitleMessage(String title, String message) { this.title=title; this.message=message; } public Object open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX); props.setLook(shell); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; if (title==null) title="Examine preview data"; if (message==null) message="Rows of step: "+stepname; shell.setLayout(formLayout); shell.setText(title); // int middle = props.getMiddlePct(); int margin = Const.MARGIN; wlFields=new Label(shell, SWT.LEFT); wlFields.setText(message); props.setLook(wlFields); fdlFields=new FormData(); fdlFields.left = new FormAttachment(0, 0); fdlFields.right= new FormAttachment(100, 0); fdlFields.top = new FormAttachment(0, margin); wlFields.setLayoutData(fdlFields); // Mmm, if we don't get any rows in the buffer: show a dialog box. if (buffer==null || buffer.size()==0) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING ); mb.setMessage("Sorry, no rows can be found to preview."); mb.setText("Sorry"); mb.open(); shell.dispose(); return null; } Row row = (Row)buffer.get(0); int FieldsRows=buffer.size(); ColumnInfo[] colinf=new ColumnInfo[row.size()]; for (int i=0;i<row.size();i++) { Value v=row.getValue(i); colinf[i]=new ColumnInfo(v.getName(), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[i].setToolTip(v.toStringMeta()); } wFields=new TableView(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, null, props ); fdFields=new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(wlFields, margin); fdFields.right = new FormAttachment(100, 0); fdFields.bottom = new FormAttachment(100, -50); wFields.setLayoutData(fdFields); wClose=new Button(shell, SWT.PUSH); wClose.setText(" &Close "); wLog=new Button(shell, SWT.PUSH); wLog.setText(" Show &Log "); if (loggingText==null || loggingText.length()==0) wLog.setEnabled(false); // Add listeners lsClose = new Listener() { public void handleEvent(Event e) { close(); } }; lsLog = new Listener() { public void handleEvent(Event e) { log(); } }; wClose.addListener(SWT.Selection, lsClose ); wLog.addListener(SWT.Selection, lsLog ); BaseStepDialog.positionBottomButtons(shell, new Button[] { wClose, wLog }, margin, null); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { close(); } } ); getData(); WindowProperty winprop = props.getScreen(shell.getText()); if (winprop!=null) winprop.setShell(shell); else shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; } public void dispose() { props.setScreen(new WindowProperty(shell)); bounds = shell.getBounds(); hscroll = wFields.getHorizontalBar().getSelection(); vscroll = wFields.getVerticalBar().getSelection(); shell.dispose(); } /** * Copy information from the meta-data input to the dialog fields. */ private void getData() { shell.getDisplay().asyncExec(new Runnable() { public void run() { for (int i=0;i<buffer.size();i++) { TableItem item = wFields.table.getItem(i); Row row = (Row)buffer.get(i); for (int c=0;c<row.size();c++) { Value v=row.getValue(c); String show; if (v.isNumeric()) show = v.toString(true); else show = v.toString(false); if (show!=null) item.setText(c+1, show); } } wFields.optWidth(true, 200); } }); } private void close() { stepname=null; dispose(); } /** * Show the logging of the preview (in case errors occurred */ private void log() { if (loggingText!=null) { EnterTextDialog etd = new EnterTextDialog(shell, "Logging text", "The logging text", loggingText); etd.open(); } }; public boolean isDisposed() { return shell.isDisposed(); } public Rectangle getBounds() { return bounds; } public void setBounds(Rectangle b) { bounds = b; } public int getHScroll() { return hscroll; } public void setHScroll(int s) { hscroll=s; } public int getVScroll() { return vscroll; } public void setVScroll(int s) { vscroll=s; } public int getHMax() { return hmax; } public void setHMax(int m) { hmax=m; } public int getVMax() { return vmax; } public void setVMax(int m) { vmax=m; } }
package org.jdesktop.swingx; import java.beans.BeanDescriptor; /** * BeanInfo class for JXTaskPane. * * @author rbair, Jan Stola */ public class JXTaskPaneBeanInfo extends BeanInfoSupport { /** Constructor for the JXTaskPaneBeanInfo object */ public JXTaskPaneBeanInfo() { super(JXTaskPane.class); } protected void initialize() { BeanDescriptor bd = getBeanDescriptor(); // setup bean descriptor in constructor. bd.setName("JXTaskPane"); bd.setShortDescription("JXTaskPane is a container for tasks and other arbitrary components."); bd.setValue("isContainer", Boolean.TRUE); bd.setValue("containerDelegate", "getContentPane"); setPreferred(true, "title", "icon", "special"); setPreferred(true, "animated", "scrollOnExpand", "expanded", "font"); setBound(true, "title", "icon", "special", "scrollOnExpand", "expanded"); setPreferred(false, "border"); } }
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; 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; } /** * 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, 1.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; } }
package cn.cerc.mis.core; import javax.servlet.http.HttpServletRequest; import cn.cerc.core.DataRow; import cn.cerc.core.DataSet; import cn.cerc.core.Datetime.DateType; import cn.cerc.core.ISession; import cn.cerc.core.MD5; import cn.cerc.db.core.Handle; import cn.cerc.db.core.IHandle; import cn.cerc.mis.other.MemoryBuffer; public class SegmentQuery extends Handle { private DataSet dataIn; private DataSet dataOut; public SegmentQuery(CustomService owner) { super(owner); this.dataIn = owner.getDataIn(); this.dataOut = owner.getDataOut(); } public SegmentQuery(IHandle handle, DataSet dataIn, DataSet dataOut) { super(handle); this.dataIn = dataIn; this.dataOut = dataOut; } public boolean enable(String fromField, String toField) { return enable(fromField, toField, 30); } public boolean enable(String fromField, String toField, int offset) { DataRow headIn = dataIn.getHead(); if (!headIn.getBoolean("segmentQuery")) return false; HttpServletRequest request = (HttpServletRequest) this.getSession().getProperty(ISession.REQUEST); String sessionId = request.getSession().getId(); try (MemoryBuffer buff = new MemoryBuffer(SystemBuffer.Service.BigData, this.getClass().getName(), sessionId, MD5.get(dataIn.toJson()))) { if (buff.isNull()) { buff.setValue("beginDate", headIn.getDatetime(fromField)); buff.setValue("endDate", headIn.getDatetime(toField).toDayEnd()); buff.setValue("curBegin", headIn.getDatetime(fromField)); buff.setValue("curEnd", headIn.getDatetime(fromField).toDayEnd()); headIn.setValue(fromField, buff.getDatetime("beginDate")); headIn.setValue(toField, headIn.getDatetime(fromField).inc(DateType.Day, offset).toDayEnd()); } else { headIn.setValue(fromField, buff.getDatetime("curEnd").inc(DateType.Day, 1).toDayStart()); headIn.setValue(toField, buff.getDatetime("curEnd").inc(DateType.Day, offset).toDayEnd()); } if (headIn.getDatetime(toField).compareTo(buff.getDatetime("endDate")) > 0) { headIn.setValue(toField, buff.getDatetime("endDate")); buff.clear(); } else { buff.setValue("curBegin", headIn.getDatetime(fromField)); buff.setValue("curEnd", headIn.getDatetime(toField)); buff.post(); dataOut.getHead().setValue("_has_next_", true); } } return true; } }
package com.sequenceiq.cloudbreak.service.image; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.sequenceiq.cloudbreak.cloud.model.AmbariCatalog; import com.sequenceiq.cloudbreak.cloud.model.CloudbreakImageCatalog; import com.sequenceiq.cloudbreak.cloud.model.HDPInfo; import com.sequenceiq.cloudbreak.core.CloudbreakImageNotFoundException; @Service public class HdpInfoSearchService { private static final Logger LOGGER = LoggerFactory.getLogger(HdpInfoSearchService.class); @Value("${info.app.version:}") private String cbVersion; @Inject private ImageCatalogProvider imageCatalogProvider; public HDPInfo searchHDPInfo(String ambariVersion, String hdpVersion, String imageCatalogUrl) throws CloudbreakImageNotFoundException { HDPInfo hdpInfo = null; if (ambariVersion != null && hdpVersion != null) { CloudbreakImageCatalog imageCatalog = imageCatalogProvider.getImageCatalog(imageCatalogUrl); hdpInfo = prefixSearch(imageCatalog, cbVersion, ambariVersion, hdpVersion); if (hdpInfo == null) { throw new CloudbreakImageNotFoundException( String.format("Failed to determine VM image from catalog! Cloudbreak version: %s, " + "Ambari version: %s, HDP Version: %s, Image Catalog Url: %s", cbVersion, ambariVersion, hdpVersion, imageCatalogUrl != null ? imageCatalogUrl : imageCatalogProvider.getDefaultCatalogUrl())); } } return hdpInfo; } private List<AmbariCatalog> ambariPrefixMatch(CloudbreakImageCatalog imageCatalog, String cbVersion, String ambariVersion) { if (imageCatalog == null) { return null; } List<AmbariCatalog> ambariCatalog; if (!StringUtils.isEmpty(cbVersion) && !"unspecified".equals(cbVersion) && !cbVersion.contains("dev")) { ambariCatalog = imageCatalog.getAmbariVersions().stream() .filter(p -> p.getAmbariInfo().getCbVersions().contains(cbVersion)).collect(Collectors.toList()); } else { ambariCatalog = imageCatalog.getAmbariVersions().stream().collect(Collectors.toList()); } List<AmbariCatalog> ambariCatalogs = ambariCatalog.stream() .filter(p -> p.getAmbariInfo().getVersion().startsWith(ambariVersion)).collect(Collectors.toList()); Collections.sort(ambariCatalogs, Collections.reverseOrder(new VersionComparator())); LOGGER.info("Prefix matched Ambari versions: {}. Ambari search prefix: {}", ambariCatalogs, ambariVersion); return ambariCatalogs; } private AmbariCatalog selectLatestAmbariCatalog(List<AmbariCatalog> ambariCatalogs) { if (ambariCatalogs == null || ambariCatalogs.isEmpty()) { return null; } return ambariCatalogs.get(0); } private List<HDPInfo> hdpPrefixMatch(AmbariCatalog ambariCatalog, String hdpVersion) { if (ambariCatalog == null) { return null; } List<HDPInfo> hdpInfos = ambariCatalog.getAmbariInfo().getHdp().stream() .filter(p -> p.getVersion().startsWith(hdpVersion)).collect(Collectors.toList()); Collections.sort(hdpInfos, Collections.reverseOrder(new VersionComparator())); LOGGER.info("Prefix matched HDP versions: {} for Ambari version: {}. HDP search prefix: {}", hdpInfos, ambariCatalog.getVersion(), hdpVersion); return hdpInfos; } private HDPInfo selectLatestHdpInfo(List<HDPInfo> hdpInfos) { if (hdpInfos == null || hdpInfos.isEmpty()) { return null; } return hdpInfos.get(0); } private HDPInfo prefixSearch(CloudbreakImageCatalog imageCatalog, String cbVersion, String ambariVersion, String hdpVersion) { List<AmbariCatalog> ambariCatalogs = ambariPrefixMatch(imageCatalog, cbVersion, ambariVersion); AmbariCatalog ambariCatalog = selectLatestAmbariCatalog(ambariCatalogs); List<HDPInfo> hdpInfos = hdpPrefixMatch(ambariCatalog, hdpVersion); return selectLatestHdpInfo(hdpInfos); } }
package com.camunda.fox.cycle.web.service.resource; import java.io.InputStream; import java.util.Date; import java.util.List; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.apache.commons.io.IOUtils; import org.codehaus.plexus.util.IOUtil; import org.springframework.transaction.annotation.Transactional; import com.camunda.fox.cycle.api.connector.Connector; import com.camunda.fox.cycle.api.connector.ConnectorNode; import com.camunda.fox.cycle.api.connector.ConnectorNode.ConnectorNodeType; import com.camunda.fox.cycle.connector.ConnectorRegistry; import com.camunda.fox.cycle.entity.BpmnDiagram; import com.camunda.fox.cycle.entity.Roundtrip; import com.camunda.fox.cycle.exception.CycleException; import com.camunda.fox.cycle.repository.RoundtripRepository; import com.camunda.fox.cycle.service.roundtrip.BpmnProcessModelUtil; import com.camunda.fox.cycle.util.IoUtil; import com.camunda.fox.cycle.web.dto.RoundtripDTO; import com.camunda.fox.cycle.web.service.AbstractRestService; /** * This is the main roundtrip rest controller which exposes roundtrip * <code>list</code>, <code>get</code>, <code>create</code> and<code>update</code> * methods as well as some utilities to the cycle client application. * * The arrangement of methods is compatible with angular JS <code>$resource</code>. * * @author nico.rehwaldt */ @Path("secured/resource/roundtrip") public class RoundtripService extends AbstractRestService { public enum SyncMode { LEFT_TO_RIGHT, RIGHT_TO_LEFT } @Inject private RoundtripRepository roundtripRepository; @Inject private ConnectorRegistry connectorRegistry; @Inject private BpmnProcessModelUtil bpmnProcessModelUtil; @Inject private BpmnDiagramService bpmnDiagramController; /** * $resource specific methods */ @GET public List<RoundtripDTO> list() { return RoundtripDTO.wrapAll(getRoundtripRepository().findAll()); } @GET @Path("{id}") public RoundtripDTO get(@PathParam("id") long id) { return RoundtripDTO.wrap(getRoundtripRepository().findById(id)); } @POST @Path("{id}") @Transactional public RoundtripDTO update(RoundtripDTO data) { long id = data.getId(); Roundtrip roundtrip = getRoundtripRepository().findById(id); if (roundtrip == null) { throw new IllegalArgumentException("Not found"); } update(roundtrip, data); return RoundtripDTO.wrap(roundtrip); } @POST public RoundtripDTO create(RoundtripDTO data) { Roundtrip roundtrip = new Roundtrip(); update(roundtrip, data); return RoundtripDTO.wrap(getRoundtripRepository().saveAndFlush(roundtrip)); } /** * Non $resource specific methods */ @GET @Transactional @Path("{id}/details") public RoundtripDTO getDetails(@PathParam("id") long id) { Roundtrip roundtrip = getRoundtripRepository().findById(id); // TODO: Fetch eager return new RoundtripDTO(roundtrip, roundtrip.getLeftHandSide(), roundtrip.getRightHandSide()); } @POST @Path("{id}/details") @Transactional public RoundtripDTO updateDetails(RoundtripDTO data) { long id = data.getId(); Roundtrip roundtrip = getRoundtripRepository().findById(id); if (roundtrip == null) { throw new IllegalArgumentException("Not found"); } if (data.getLeftHandSide() != null) { BpmnDiagram leftHandSide = bpmnDiagramController.createOrUpdate(data.getLeftHandSide()); roundtrip.setLeftHandSide(leftHandSide); } else { roundtrip.setLeftHandSide(null); } if (data.getRightHandSide() != null) { BpmnDiagram rightHandSide = bpmnDiagramController.createOrUpdate(data.getRightHandSide()); roundtrip.setRightHandSide(rightHandSide); } else { roundtrip.setRightHandSide(null); } Roundtrip saved = getRoundtripRepository().saveAndFlush(roundtrip); return new RoundtripDTO(saved, saved.getLeftHandSide(), saved.getRightHandSide()); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("isNameValid") public boolean isNameValid(@QueryParam("name") String name) { return getRoundtripRepository().isNameValid(name); } @POST @Path("{id}/sync") @Transactional public RoundtripDTO doSynchronize(@QueryParam("syncMode") SyncMode syncMode, @PathParam("id") long id) { Roundtrip roundtrip = this.getRoundtripRepository().findById(id); BpmnDiagram leftHandSide = roundtrip.getLeftHandSide(); Connector leftHandSideConnector = this.connectorRegistry.getSessionConnectorMap().get(leftHandSide.getConnectorId()); ConnectorNode leftHandSideModelNode = new ConnectorNode(leftHandSide.getDiagramPath(), leftHandSide.getLabel()); leftHandSideModelNode.setType(ConnectorNodeType.FILE); InputStream leftHandSideModelContent = leftHandSideConnector.getContent(leftHandSideModelNode); BpmnDiagram rightHandSide = roundtrip.getRightHandSide(); Connector rightHandSideConnector = this.connectorRegistry.getSessionConnectorMap().get(rightHandSide.getConnectorId()); ConnectorNode rightHandSideModelNode = new ConnectorNode(rightHandSide.getDiagramPath(), rightHandSide.getLabel()); rightHandSideModelNode.setType(ConnectorNodeType.FILE); InputStream rightHandSideModelContent = rightHandSideConnector.getContent(rightHandSideModelNode); try { switch (syncMode) { case LEFT_TO_RIGHT: IoUtil.closeSilently(rightHandSideModelContent); rightHandSideConnector.updateContent(rightHandSideModelNode, this.bpmnProcessModelUtil.extractExecutablePool(leftHandSideModelContent)); IoUtil.closeSilently(leftHandSideModelContent); break; case RIGHT_TO_LEFT: String result = this.bpmnProcessModelUtil.importChangesFromExecutableBpmnModel(IOUtil.toString(rightHandSideModelContent, "UTF-8"), IOUtil.toString(leftHandSideModelContent, "UTF-8")); IoUtil.closeSilently(leftHandSideModelContent); IoUtil.closeSilently(rightHandSideModelContent); InputStream resultStream = IOUtils.toInputStream(result, "UTF-8"); leftHandSideConnector.updateContent(leftHandSideModelNode, resultStream); IoUtil.closeSilently(resultStream); break; } roundtrip.setLastSync(new Date()); } catch (Exception e) { throw new CycleException(e); } return new RoundtripDTO(roundtrip, roundtrip.getLeftHandSide(), roundtrip.getRightHandSide()); } /** * Updates the roundtrip with the given data * @param roundtrip * @param data */ private void update(Roundtrip roundtrip, RoundtripDTO data) { roundtrip.setName(data.getName()); } public RoundtripRepository getRoundtripRepository() { return roundtripRepository; } public void setRoundtripRepository(RoundtripRepository roundtripRepository) { this.roundtripRepository = roundtripRepository; } }
package etomica.box; import etomica.molecule.IMolecule; import etomica.molecule.IMoleculeList; import java.util.AbstractList; /** * Creates a facade that makes a set of molecule lists look like a single list. This class is * configured by calling setMoleculeLists(). This should be called after construction, every time * one of the molecule lists in the set is changed by adding or removing a molecule, and when a * list is added or removed from the set. */ public class AtomSetAllMolecules extends AbstractList<IMolecule> implements IMoleculeList { private IMoleculeList[] moleculeLists; private int[] moleculeTotals; /** * Constructs an empty list. Subsequent call to setMoleculeLists() is needed to configure this list. */ public AtomSetAllMolecules() { moleculeTotals = new int[1]; } /** * @param i specification of the desired molecule. * @return a molecule as ordered by the species and then the molecules within the species. * @throws IndexOutOfBoundsException if i >= getMoleculeCount() or i < 0 */ public IMolecule get(int i) { if (i >= size() || i < 0) throw new IndexOutOfBoundsException("Index: " + i + ", Number of molecules: " + size()); int nSpecies = moleculeLists.length; if (moleculeTotals[0] > i) { return moleculeLists[0].get(i); } for (int iSpecies = 1; iSpecies < nSpecies; iSpecies++) { if (moleculeTotals[iSpecies] > i) { return moleculeLists[iSpecies].get(i - moleculeTotals[iSpecies - 1]); } } throw new IllegalStateException("how can this be?!?!?!"); } /** * @return total number of molecules in the list. */ public int size() { return moleculeTotals[moleculeTotals.length - 1]; } /** * Configures this list based on the given array of lists. The ordering of this list is obtained by concatenating * the given lists. * * @param newMoleculeLists lists of molecules that form this list. */ public void setMoleculeLists(IMoleculeList[] newMoleculeLists) { moleculeLists = newMoleculeLists; if (moleculeTotals.length - 1 != moleculeLists.length) { moleculeTotals = new int[moleculeLists.length + 1]; } if (moleculeLists.length == 0) { return; } moleculeTotals[0] = moleculeLists[0].size(); for (int i = 1; i < moleculeTotals.length - 1; i++) { moleculeTotals[i] = moleculeTotals[i - 1] + moleculeLists[i].size(); } moleculeTotals[moleculeTotals.length - 1] = moleculeTotals[moleculeTotals.length - 2]; } }
package com.google.zxing.client.android.result; import android.app.Activity; import com.google.zxing.client.android.R; import com.google.zxing.client.result.GeoParsedResult; import com.google.zxing.client.result.ParsedResult; /** * geoURLs * * @author lijian * @date 2017-9-7 10:37:08 */ public final class GeoResultHandler extends ResultHandler { private static final int[] buttons = { R.string.button_show_map, R.string.button_get_directions }; /** * geoURLs * * @param activity * @param result */ public GeoResultHandler(Activity activity, ParsedResult result) { super(activity, result); } @Override public int getButtonCount() { return buttons.length; } @Override public int getButtonText(int index) { return buttons[index]; } @Override public void handleButtonPress(int index) { GeoParsedResult geoResult = (GeoParsedResult) getResult(); switch (index) { case 0: openMap(geoResult.getGeoURI()); break; case 1: getDirections(geoResult.getLatitude(), geoResult.getLongitude()); break; } } @Override public int getDisplayTitle() { return R.string.result_geo; } }
package com.psddev.dari.db; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.RepeatingTask; import com.psddev.dari.util.Settings; import com.psddev.dari.util.Task; import com.psddev.dari.util.TypeReference; /** Automatic resummarization of Metric values, driven by the {@code * "dari/metricResummarize"} Settings map. To use, add lines like these to your * context.xml: * * <pre> * {@code * <!-- To match all of the analytics fields --> * <Environment name="dari/metricResummarize/analyticsDaily/fields" type="java.lang.String" value="analytics.*" /> * <!-- Resummarize all data older than 180 days--> * <Environment name="dari/metricResummarize/analyticsDaily/beforeDays" type="java.lang.Integer" value="180" /> * <!-- Collapse it from Hourly (the default) to Daily --> * <Environment name="dari/metricResummarize/analyticsDaily/intervalClass" type="java.lang.String" value="com.psddev.dari.db.MetricInterval$Daily" /> * } * </pre> * * <pre> * {@code * <!-- To match one or more specific fields: --> * <Environment name="dari/metricResummarize/example/fields" type="java.lang.String" value="com.example.ExampleClass/exampleMetricField com.example.ExampleClass2/myOtherMetricField com.example.ExampleClass3/count*" /> * <!-- Resummarize all data older than 7 days--> * <Environment name="dari/metricResummarize/example/beforeDays" type="java.lang.Integer" value="7" /> * <!-- Collapse it from Hourly (the default) to Daily --> * <Environment name="dari/metricResummarize/example/intervalClass" type="java.lang.String" value="com.psddev.dari.db.MetricInterval$Hourly" /> * <!-- Specify a database (references the dari/database Settings map) --> * <Environment name="dari/metricResummarize/example/database" type="java.lang.String" value="mydb" /> * } * </pre> * */ public class MetricResummarizationTask extends RepeatingTask { private static final Logger LOGGER = LoggerFactory.getLogger(MetricResummarizationTask.class); private static final String CONFIG_PREFIX = "dari/metricResummarize"; private static final String CONFIG_FIELDS = "fields"; private static final String CONFIG_BEFORE_DAYS = "beforeDays"; private static final String CONFIG_INTERVAL_CLASS = "intervalClass"; private static final String CONFIG_DATABASE = "database"; private static final Map<String, Map<String, Object>> CONFIG = Settings.get(new TypeReference<Map<String, Map<String, Object>>>() { }, CONFIG_PREFIX); @Override protected DateTime calculateRunTime(DateTime currentTime) { if (CONFIG == null || CONFIG.isEmpty()) { return every(currentTime, DateTimeFieldType.era(), 0, 1); } else { return everyDay(currentTime); } } @Override protected void doRepeatingTask(DateTime runTime) throws Exception { if (CONFIG == null || CONFIG.isEmpty()) { return; } for (Map.Entry<String, Map<String, Object>> entry : CONFIG.entrySet()) { String key = entry.getKey(); Map<String, Object> settings = entry.getValue(); String fieldsStr = ObjectUtils.to(String.class, settings.get(CONFIG_FIELDS)); if (ObjectUtils.isBlank(fieldsStr)) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_FIELDS + " is required; aborting."); continue; } String[] fieldSpecs = fieldsStr.split("\\s+"); Integer beforeDays = ObjectUtils.to(Integer.class, settings.get(CONFIG_BEFORE_DAYS)); if (beforeDays == null) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_BEFORE_DAYS + " is required; aborting."); continue; } String intervalClassName = ObjectUtils.to(String.class, settings.get(CONFIG_INTERVAL_CLASS)); if (intervalClassName == null) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_INTERVAL_CLASS + " is required; aborting."); continue; } Database database = Database.Static.getDefault(); String databaseName = ObjectUtils.to(String.class, settings.get(CONFIG_DATABASE)); if (databaseName != null) { database = Database.Static.getInstance(databaseName); if (database == null) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_DATABASE + " is an invalid database; aborting."); continue; } } submitResummarizationTask(database, key, fieldSpecs, beforeDays, intervalClassName); } } private void submitResummarizationTask(Database database, String key, String[] fieldSpecs, int beforeDays, String intervalClassName) { Set<ObjectField> fields = resolveFieldSpecs(database, key, fieldSpecs); if (fields == null || fields.isEmpty()) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + " specifies no valid fields to resummarize; aborting."); return; } Set<String> debugFieldNames = new HashSet<String>(); for (ObjectField field : fields) { debugFieldNames.add(field.getUniqueName()); } MetricInterval interval; try { @SuppressWarnings("unchecked") Class<MetricInterval> intervalClass = (Class<MetricInterval>) Class.forName(intervalClassName); interval = intervalClass.newInstance(); } catch (Exception e) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_INTERVAL_CLASS + " specifies an invalid MetricInterval class; aborting."); return; } LastResummarization last = Query.from(LastResummarization.class).using(database).where("key = ?", key).first(); if (last == null) { last = new LastResummarization(); last.getState().setDatabase(database); last.setKey(key); } // Ensure we're only running once per day. . . if (last.getRunDate() != null && last.getRunDate().isAfter(new DateTime().minusDays(1))) { // LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + " last ran on " + last.getRunDate().toString("yyyy/MM/dd HH:mm:ss") + ", aborting." ); return; } // Set up the new date range DateTime startDate = last.getEndDate(); DateTime endDate = new DateTime().dayOfMonth().roundFloorCopy().minusDays(beforeDays); last.setRunDate(new DateTime()); last.setStartDate(startDate); last.setEndDate(endDate); last.save(); for (ObjectField field : fields) { Task task = Metric.Static.submitResummarizeAllBetweenTask(database, field.getParentType(), field, interval, startDate, endDate, 1, "Periodic Metric Resummarization", key + " (" + field.getUniqueName() + ")"); do { try { Thread.sleep(1000); } catch (InterruptedException ex) { break; } if (!task.isRunning()) { break; } } while (shouldContinue()); } } private Set<ObjectField> resolveFieldSpecs(Database database, String key, String[] fieldSpecs) { Set<ObjectField> fields = new HashSet<ObjectField>(); for (String fieldSpec : fieldSpecs) { String[] parts = fieldSpec.split("/"); if (parts.length == 1) { // looking for a global field if (fieldSpec.endsWith("*")) { String fieldPrefix = fieldSpec.substring(0, fieldSpec.length() - 1); for (ObjectField field : database.getEnvironment().getFields()) { if (field.getInternalName().startsWith(fieldPrefix) && field.isMetric()) { fields.add(field); } } } else { ObjectField field = database.getEnvironment().getField(fieldSpec); if (field == null || !field.isMetric()) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_FIELDS + " : " + fieldSpec + " specifies an invalid field."); return null; } fields.add(field); } } else if (parts.length == 2) { // looking for a type field String typeName = parts[0]; String typeFieldSpec = parts[1]; ObjectType type = database.getEnvironment().getTypeByName(typeName); if (type == null) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_FIELDS + " : " + fieldSpec + " specifies an invalid type."); return null; } if (typeFieldSpec.endsWith("*")) { String typeFieldPrefix = typeFieldSpec.substring(0, typeFieldSpec.length() - 1); for (ObjectField field : type.getFields()) { if (field.getInternalName().startsWith(typeFieldPrefix) && field.isMetric()) { fields.add(field); } } } else { ObjectField field = type.getField(typeFieldSpec); if (field == null || !field.isMetric()) { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_FIELDS + " : " + fieldSpec + " specifies an invalid field."); return null; } fields.add(field); } } else { LOGGER.warn("Metric Resummarization: " + CONFIG_PREFIX + "/" + key + "/" + CONFIG_FIELDS + " : " + fieldSpec + " specifies an invalid field."); return null; } } return fields; } public static class LastResummarization extends Record { private Long startDate; private Long endDate; private Long runDate; @Indexed(unique = true) private String key; public DateTime getStartDate() { return (startDate == null ? null : new DateTime(startDate)); } public void setStartDate(DateTime startDate) { this.startDate = (startDate == null ? null : startDate.getMillis()); } public DateTime getEndDate() { return (endDate == null ? null : new DateTime(endDate)); } public void setEndDate(DateTime endDate) { this.endDate = (endDate == null ? null : endDate.getMillis()); } public DateTime getRunDate() { return (runDate == null ? null : new DateTime(runDate)); } public void setRunDate(DateTime runDate) { this.runDate = (runDate == null ? null : runDate.getMillis()); } public String getKey() { return key; } public void setKey(String key) { this.key = key; } } }
package gov.va.escreening.service; import freemarker.core.TemplateElement; import gov.va.escreening.constants.TemplateConstants; import gov.va.escreening.constants.TemplateConstants.TemplateType; import gov.va.escreening.controller.TemplateRestController; import gov.va.escreening.dto.TemplateDTO; import gov.va.escreening.dto.TemplateTypeDTO; import gov.va.escreening.dto.template.INode; import gov.va.escreening.dto.template.TemplateFileDTO; import gov.va.escreening.entity.Battery; import gov.va.escreening.entity.Survey; import gov.va.escreening.entity.Template; import gov.va.escreening.entity.VariableTemplate; import gov.va.escreening.repository.BatteryRepository; import gov.va.escreening.repository.SurveyRepository; import gov.va.escreening.repository.TemplateRepository; import gov.va.escreening.repository.TemplateTypeRepository; import gov.va.escreening.repository.VariableTemplateRepository; import gov.va.escreening.templateprocessor.TemplateProcessorService; import gov.va.escreening.transformer.TemplateTransformer; import java.io.IOException; import java.util.Date; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; @Service public class TemplateServiceImpl implements TemplateService { private static final Logger logger = LoggerFactory.getLogger(TemplateServiceImpl.class); @Autowired private TemplateRepository templateRepository; @Autowired private TemplateTypeRepository templateTypeRepository; @Autowired private VariableTemplateRepository variableTemplateRepository; @Autowired private SurveyRepository surveyRepository; @Autowired private BatteryRepository batteryRepository; @Autowired private TemplateProcessorService templateProcessorService; @SuppressWarnings("serial") private static List<TemplateType> surveyTemplates = new ArrayList<TemplateType>() { { add(TemplateType.CPRS_ENTRY); add(TemplateType.VET_SUMMARY_ENTRY); add(TemplateType.VISTA_QA); } }; @SuppressWarnings("serial") private static List<TemplateType> batteryTemplates = new ArrayList<TemplateType>() { { add(TemplateType.CPRS_HEADER); add(TemplateType.CPRS_FOOTER); add(TemplateType.ASSESS_SCORE_TABLE); add(TemplateType.ASSESS_CONCLUSION); add(TemplateType.VET_SUMMARY_HEADER); add(TemplateType.VET_SUMMARY_FOOTER); } }; @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void deleteTemplate(Integer templateId) { Template template = templateRepository.findOne(templateId); if (template == null) { throw new IllegalArgumentException(); } if (surveyTemplates.contains(TemplateConstants.typeForId(template .getTemplateType().getTemplateTypeId()))) { // need to remove this template from associated survey List<Survey> surveys = surveyRepository .findByTemplateId(templateId); if (surveys != null && surveys.size() > 0) { for (Survey survey : surveys) { survey.getTemplates().remove(template); surveyRepository.update(survey); } } } else { // need to remove this template from associated battery // find the survey or battery List<Battery> batteries = batteryRepository .findByTemplateId(templateId); if (batteries != null && batteries.size() > 0) { for (Battery battery : batteries) { battery.getTemplates().remove(template); batteryRepository.update(battery); } } } templateRepository.deleteById(templateId); } @Override @Transactional(readOnly = true) public TemplateDTO getTemplate(Integer templateId) { Template template = templateRepository.findOne(templateId); if (template == null) { return null; } else { return TemplateTransformer.copyToTemplateDTO(template, null); } } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public TemplateDTO updateTemplate(TemplateDTO templateDTO) { Template template = templateRepository.findOne(templateDTO .getTemplateId()); if (template == null) { throw new IllegalArgumentException("Could not find template"); } TemplateTransformer.copyToTemplate(templateDTO, template); templateRepository.update(template); return TemplateTransformer.copyToTemplateDTO(template, null); } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public TemplateDTO createTemplate(TemplateDTO templateDTO, Integer templateTypeId, Integer parentId, boolean isSurvey) { Template template = TemplateTransformer.copyToTemplate(templateDTO, null); template.setTemplateType(templateTypeRepository.findOne(templateTypeId)); if (parentId == null) { templateRepository.create(template); } else { if (isSurvey) { Survey survey = surveyRepository.findOne(parentId); Set<Template> templateSet = survey.getTemplates(); survey.setTemplates(addTemplateToSet(templateSet, template, surveyTemplates)); surveyRepository.update(survey); } else { Battery battery = batteryRepository.findOne(parentId); Set<Template> templateSet = battery.getTemplates(); battery.setTemplates(addTemplateToSet(templateSet, template, batteryTemplates)); batteryRepository.update(battery); } } return TemplateTransformer.copyToTemplateDTO(template, null); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public void addVariableTemplate(Integer templateId, Integer variableTemplateId) { Template template = templateRepository.findOne(templateId); VariableTemplate variableTemplate = variableTemplateRepository .findOne(variableTemplateId); template.getVariableTemplateList().add(variableTemplate); templateRepository.update(template); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public void addVariableTemplates(Integer templateId, List<Integer> variableTemplateIds) { Template template = templateRepository.findOne(templateId); List<VariableTemplate> variableTemplates = variableTemplateRepository .findByIds(variableTemplateIds); template.getVariableTemplateList().addAll(variableTemplates); templateRepository.update(template); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public void removeVariableTemplateFromTemplate(Integer templateId, Integer variableTemplateId) { Template template = templateRepository.findOne(templateId); VariableTemplate variableTemplate = variableTemplateRepository .findOne(variableTemplateId); template.getVariableTemplateList().remove(variableTemplate); templateRepository.update(template); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public void removeVariableTemplatesFromTemplate(Integer templateId, List<Integer> variableTemplateIds) { Template template = templateRepository.findOne(templateId); List<VariableTemplate> variableTemplates = variableTemplateRepository .findByIds(variableTemplateIds); template.getVariableTemplateList().removeAll(variableTemplates); templateRepository.update(template); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public void setVariableTemplatesToTemplate(Integer templateId, List<Integer> variableTemplateIds) { Template template = templateRepository.findOne(templateId); List<VariableTemplate> variableTemplates = variableTemplateRepository .findByIds(variableTemplateIds); template.setVariableTemplateList(variableTemplates); templateRepository.update(template); } /** * * Ensure the uniqueness of the template in either survey or battery * * @param templateSet * @param template * @param uniquTemplateTypes * @return */ private Set<Template> addTemplateToSet(Set<Template> templateSet, Template template, List<TemplateType> uniquTemplateTypes) { if (templateSet == null) { templateSet = new HashSet<Template>(); templateSet.add(template); } else { // first we make sure boolean needsToBeUnique = false; for (TemplateType tt : uniquTemplateTypes) { if (tt.getId() == template.getTemplateType() .getTemplateTypeId()) { needsToBeUnique = true; break; } } if (needsToBeUnique) { for (Template t : templateSet) { if (t.getTemplateType().getTemplateTypeId() == template .getTemplateType().getTemplateTypeId()) { templateSet.remove(t); break; } } } templateSet.add(template); } return templateSet; } @Override public TemplateDTO getTemplateBySurveyAndTemplateType(Integer surveyId, Integer templateTypeId) { Template t = templateRepository.getTemplateByIdAndTemplateType( surveyId, templateTypeId); TemplateDTO dto = null; if (t != null) { dto = new TemplateDTO(); dto.setTemplateId(t.getTemplateId()); dto.setName(t.getName()); dto.setDateCreated(t.getDateCreated()); dto.setDescription(t.getDescription()); dto.setGraphical(t.getIsGraphical()); dto.setTemplateFile(t.getTemplateFile()); dto.setTemplateType(templateTypeId); } return dto; } @Override public TemplateFileDTO getTemplateFileAsTree(Integer templateId) { Template t = templateRepository.findOne(templateId); if (t == null) return null; TemplateFileDTO dto = new TemplateFileDTO(); if (t.getJsonFile() != null) { // now parsing the template file ObjectMapper om = new ObjectMapper(); try { dto.setBlocks((List<INode>) om.readValue(t.getJsonFile(), List.class)); }catch(IOException e) { e.printStackTrace(); return null; } } dto.setName(t.getName()); dto.setId(templateId); dto.setIsGraphical(t.getIsGraphical()); TemplateTypeDTO ttDTO = new TemplateTypeDTO(); dto.setType(ttDTO); ttDTO.setName(t.getTemplateType().getName()); ttDTO.setId(t.getTemplateType().getTemplateTypeId()); ttDTO.setDescription(t.getTemplateType().getDescription()); /* String templateFile = t.getTemplateFile(); templateFile = templateFile.replace("${NBSP}", "&nbsp;") .replace("${LINE_BREAK}", "<br/>") .replace("<#include \"clinicalnotefunctions\">", ""); try { freemarker.template.Template fmTemplate = templateProcessorService .getTemplate(templateId, templateFile); for (int i = 0; i < fmTemplate.getRootTreeNode() .getChildCount(); i++) { INode nod = nodeIterate(((TemplateElement) fmTemplate .getRootTreeNode().getChildAt(i)), null); if (nod == null) continue; dto.getBlocks().add(nod); } } catch (IOException e) { return null; } return dto; } catch (Exception e) { e.printStackTrace(); }*/ return dto; } private Properties parseMetaData() { String[] data = metaStr.replace("<#--", "").replace("-->", "").trim() .split(","); Properties p = new Properties(); for (int i = 0; i < data.length; i++) { String dat[] = data[i].split("="); p.put(dat[0], dat[1]); } return p; } private String metaStr = null; private INode nodeIterate(TemplateElement node, List<Long> templateVariables) { INode nodeDTO = null; /* String type = node.getClass().getSimpleName(); String content = node.getCanonicalForm(); if (!node.isLeaf()) { try { // nodeDTO.setContent(content.substring(0, // content.indexOf(((TemplateElement)node.getChildNodes().get(0)).getCanonicalForm()))); if (type.equals("IfBlock")) { nodeDTO = new TemplateIfBlockDTO(); } else if (type.equals("ConditionalBlock")) { // nodeDTO.setContent(content.substring(0, content // .indexOf(((TemplateElement) node.getChildAt(0)) // .getCanonicalForm()))); if (content.equals("<#else>")) { nodeDTO = new TemplateBaseBlockDTO(); nodeDTO.setType("elseBlock"); } else if (content.startsWith("<#if")) { nodeDTO = new TemplateConditionBlockDTO(); nodeDTO.setType("ifBlock"); String formula = content.substring(0, content .indexOf(((TemplateElement) node.getChildAt(0)) .getCanonicalForm())).replace("<#if ", "").trim(); formula = formula.substring(0, formula.length()-1); // parse the content here parseFormula(formula, (TemplateConditionBlockDTO)nodeDTO); } else { nodeDTO = new TemplateConditionBlockDTO(); nodeDTO.setType("elseIfBlock"); // parse the content here } } else { } // nodeDTO.setContent(content); // if (metaStr != null) { // Properties p = parseMetaData(); // nodeDTO.setTitle(p.getProperty("TITLE")); // nodeDTO.setSection(p.getProperty("SECTION")); // metaStr = null; // } for (int i = 0; i < node.getChildCount(); i++) { TemplateElement childTemplateElement = (TemplateElement) node .getChildAt(i); INode n = nodeIterate(childTemplateElement, templateVariables); if (n != null) { if (((TemplateBaseBlockDTO)nodeDTO).getChildren()==null) { ((TemplateBaseBlockDTO)nodeDTO).setChildren(new ArrayList<INode>()); } ((TemplateBaseBlockDTO)nodeDTO).getChildren().add(n); } } } catch (Exception e) { e.printStackTrace(); } } else { if (type.equals("Comment")) { metaStr = content; return null; } if (type.equals("TextBlock")) { nodeDTO = new TemplateTextDTO(); nodeDTO.setType(type); ((TemplateTextDTO) nodeDTO).setContent(content); if (metaStr != null) { Properties p = parseMetaData(); ((TemplateTextDTO) nodeDTO) .setTitle(p.getProperty("TITLE")); ((TemplateTextDTO) nodeDTO).setSection(p .getProperty("SECTION")); metaStr = null; } } }*/ return nodeDTO; } @Override @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public Integer saveTemplateFileForSurvey(Integer surveyId, Integer templateTypeId, TemplateFileDTO templateFile){ //TODO: Can some of this be factored out so we an reuse the parts that don't deal with survey in a battery related version? Survey survey = surveyRepository.findOne(surveyId); Template template = new Template(); gov.va.escreening.entity.TemplateType templateType = templateTypeRepository.findOne(templateTypeId); template.setTemplateType(templateType); template.setDateCreated(new Date()); template.setIsGraphical(templateFile.getIsGraphical()); template.setName(templateFile.getName()); // save raw json file to the database if (templateFile.getBlocks() == null || templateFile.getBlocks().size() == 0) { template.setJsonFile(null); } else { ObjectMapper om = new ObjectMapper(); try { template.setJsonFile(om.writeValueAsString(templateFile.getBlocks())); } catch(IOException e) { logger.error("Error setting json blocks into template", e); e.printStackTrace(); template.setJsonFile(null); } template.setTemplateFile(generateFreeMarkerTemplateFile(templateFile.getBlocks())); } /** * for survey one template per type */ for(Template t : survey.getTemplates()) { if (t.getTemplateType().getTemplateTypeId().longValue() == templateFile.getType().getId().longValue()) { survey.getTemplates().remove(t); break; } } survey.getTemplates().add(template); surveyRepository.update(survey); return template.getTemplateId(); } private String generateFreeMarkerTemplateFile(List<INode> blocks) { StringBuffer file = new StringBuffer(); file.append("<#include \"clinicalnotefunctions\">\n"); file.append("<#-- generated file. Do not change -->"); for(INode block : blocks) { file.append(block.toFreeMarkerFormat()); } return file.toString(); } @Override @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public void updateTemplateFile(Integer templateId, TemplateFileDTO templateFile) { Template template = templateRepository.findOne(templateId); gov.va.escreening.entity.TemplateType templateType = templateTypeRepository.findOne(templateFile.getType().getId()); template.setTemplateType(templateType); template.setDateCreated(new Date()); template.setIsGraphical(templateFile.getIsGraphical()); if (templateFile.getBlocks() == null || templateFile.getBlocks().size() == 0) { template.setJsonFile(null); template.setTemplateFile(null); } else { // save raw json file to the database ObjectMapper om = new ObjectMapper(); try { template.setJsonFile(om.writeValueAsString(templateFile.getBlocks())); } catch(IOException e) { e.printStackTrace(); template.setJsonFile(null); } template.setTemplateFile(generateFreeMarkerTemplateFile(templateFile.getBlocks())); } templateRepository.update(template); } }
package org.jboss.as.ejb3.timerservice.schedule; import static org.jboss.as.ejb3.logging.EjbLogger.EJB3_TIMER_LOGGER; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Objects; import java.util.TimeZone; import javax.ejb.ScheduleExpression; import org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfMonth; import org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfWeek; import org.jboss.as.ejb3.timerservice.schedule.attribute.Hour; import org.jboss.as.ejb3.timerservice.schedule.attribute.Minute; import org.jboss.as.ejb3.timerservice.schedule.attribute.Month; import org.jboss.as.ejb3.timerservice.schedule.attribute.Second; import org.jboss.as.ejb3.timerservice.schedule.attribute.Year; /** * CalendarBasedTimeout * * @author Jaikiran Pai * @author "<a href=\"mailto:wfink@redhat.com\">Wolf-Dieter Fink</a>" * @author Eduardo Martins * @version $Revision: $ */ public class CalendarBasedTimeout { private static final TimeZone DEFAULT_TIMEZONE = TimeZone.getDefault(); /** * The {@link javax.ejb.ScheduleExpression} from which this {@link CalendarBasedTimeout} * was created */ private final ScheduleExpression scheduleExpression; /** * The {@link Second} created out of the {@link javax.ejb.ScheduleExpression#getSecond()} value */ private final Second second; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.Minute} created out of the {@link javax.ejb.ScheduleExpression#getMinute()} value */ private final Minute minute; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.Hour} created out of the {@link javax.ejb.ScheduleExpression#getHour()} value */ private final Hour hour; /** * The {@link DayOfWeek} created out of the {@link javax.ejb.ScheduleExpression#getDayOfWeek()} value */ private final DayOfWeek dayOfWeek; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.DayOfMonth} created out of the {@link javax.ejb.ScheduleExpression#getDayOfMonth()} value */ private final DayOfMonth dayOfMonth; /** * The {@link Month} created out of the {@link javax.ejb.ScheduleExpression#getMonth()} value */ private final Month month; /** * The {@link org.jboss.as.ejb3.timerservice.schedule.attribute.Year} created out of the {@link javax.ejb.ScheduleExpression#getYear()} value */ private final Year year; /** * The first timeout relative to the time when this {@link CalendarBasedTimeout} was created * from a {@link javax.ejb.ScheduleExpression} */ private final Calendar firstTimeout; /** * The timezone being used for this {@link CalendarBasedTimeout} */ private final TimeZone timezone; private final Date start; /** * Creates a {@link CalendarBasedTimeout} from the passed <code>schedule</code>. * <p> * This constructor parses the passed {@link javax.ejb.ScheduleExpression} and sets up * its internal representation of the same. * </p> * * @param schedule The schedule */ public CalendarBasedTimeout(ScheduleExpression schedule) { // store the original expression from which this // CalendarBasedTimeout was created. Since the ScheduleExpression // is mutable, we will have to store a clone copy of the schedule, // so that any subsequent changes after the CalendarBasedTimeout construction, // do not affect this internal schedule expression. // The caller of this constructor already passes a new instance of ScheduleExpression // exclusively for this purpose, so no need to clone here. this.scheduleExpression = schedule; // Start parsing the values in the ScheduleExpression this.second = new Second(schedule.getSecond()); this.minute = new Minute(schedule.getMinute()); this.hour = new Hour(schedule.getHour()); this.dayOfWeek = new DayOfWeek(schedule.getDayOfWeek()); this.dayOfMonth = new DayOfMonth(schedule.getDayOfMonth()); this.month = new Month(schedule.getMonth()); this.year = new Year(schedule.getYear()); this.timezone = getTimeZone(schedule.getTimezone()); this.start = schedule.getStart(); // Now that we have parsed the values from the ScheduleExpression, // determine and set the first timeout (relative to the current time) // of this CalendarBasedTimeout this.firstTimeout = this.calculateFirstTimeout(); } private static TimeZone getTimeZone(String id) { if (id != null) { TimeZone zone = TimeZone.getTimeZone(id); // If the timezone ID wasn't valid, then Timezone.getTimeZone returns // GMT, which may not always be desirable. if (zone.getID().equals("GMT") && !id.equalsIgnoreCase("GMT")) { EJB3_TIMER_LOGGER.unknownTimezoneId(id, DEFAULT_TIMEZONE.getID()); } else { return zone; } } // use server's timezone return DEFAULT_TIMEZONE; } public static boolean doesScheduleMatch(final ScheduleExpression expression1, final ScheduleExpression expression2) { return Objects.equals(expression1.getHour(), expression2.getHour()) && Objects.equals(expression1.getMinute(), expression2.getMinute()) && Objects.equals(expression1.getMonth(), expression2.getMonth()) && Objects.equals(expression1.getSecond(), expression2.getSecond()) && Objects.equals(expression1.getDayOfMonth(), expression2.getDayOfMonth()) && Objects.equals(expression1.getDayOfWeek(), expression2.getDayOfWeek()) && Objects.equals(expression1.getYear(), expression2.getYear()) && Objects.equals(expression1.getTimezone(), expression2.getTimezone()) && Objects.equals(expression1.getEnd(), expression2.getEnd()) && Objects.equals(expression1.getStart(), expression2.getStart()); } public Calendar getNextTimeout() { return getNextTimeout(new GregorianCalendar(this.timezone), true); } /** * @return */ public Calendar getFirstTimeout() { return this.firstTimeout; } private Calendar calculateFirstTimeout() { Calendar currentCal = new GregorianCalendar(this.timezone); if (this.start != null) { currentCal.setTime(this.start); } else { resetTimeToFirstValues(currentCal); } return getNextTimeout(currentCal, false); } /** * Returns the original {@link javax.ejb.ScheduleExpression} from which this {@link CalendarBasedTimeout} * was created. * * @return */ public ScheduleExpression getScheduleExpression() { return this.scheduleExpression; } public Calendar getNextTimeout(Calendar currentCal) { return getNextTimeout(currentCal, true); } private Calendar getNextTimeout(Calendar currentCal, boolean increment) { if (this.noMoreTimeouts(currentCal)) { return null; } Calendar nextCal = (Calendar) currentCal.clone(); nextCal.setTimeZone(this.timezone); Date start = this.scheduleExpression.getStart(); if (start != null && currentCal.getTime().before(start)) { //this may result in a millisecond component, however that is ok //otherwise WFLY-6561 will rear its only head //also as the start time may include milliseconds this is technically correct nextCal.setTime(start); } else { if (increment) { // increment the current second by 1 nextCal.add(Calendar.SECOND, 1); } nextCal.add(Calendar.MILLISECOND, -nextCal.get(Calendar.MILLISECOND)); } nextCal.setFirstDayOfWeek(Calendar.SUNDAY); nextCal = this.computeNextTime(nextCal); if (nextCal == null) { return null; } nextCal = this.computeNextMonth(nextCal); if (nextCal == null) { return null; } nextCal = this.computeNextDate(nextCal); if (nextCal == null) { return null; } nextCal = this.computeNextYear(nextCal); if (nextCal == null) { return null; } // one final check if (this.noMoreTimeouts(nextCal)) { return null; } return nextCal; } private Calendar computeNextTime(Calendar nextCal) { int currentSecond = nextCal.get(Calendar.SECOND); int currentMinute = nextCal.get(Calendar.MINUTE); int currentHour = nextCal.get(Calendar.HOUR_OF_DAY); final int currentTimeInSeconds = currentHour*3600 + currentMinute*60 + currentSecond; // compute next second Integer nextSecond = this.second.getNextMatch(currentSecond); if (nextSecond == null) { return null; } // compute next minute if (nextSecond < currentSecond) { currentMinute++; } Integer nextMinute = this.minute.getNextMatch(currentMinute < 60 ? currentMinute : 0); if (nextMinute == null) { return null; } // reset second if minute was changed (Fix WFLY-5955) if( nextMinute != currentMinute) { nextSecond = this.second.getNextMatch(0); } // compute next hour if (nextMinute < currentMinute) { currentHour++; } Integer nextHour = this.hour.getNextMatch(currentHour < 24 ? currentHour : 0); if (nextHour == null) { return null; } if(nextHour != currentHour) { // reset second/minute if hour changed (Fix WFLY-5955) nextSecond = this.second.getNextMatch(0); nextMinute = this.minute.getNextMatch(0); } final int nextTimeInSeconds = nextHour*3600 + nextMinute*60 + nextSecond; if (nextTimeInSeconds == currentTimeInSeconds) { // no change in time return nextCal; } // Set the time before adding the a day. If we do it after, // we could be using an invalid DST value in setTime method setTime(nextCal, nextHour, nextMinute, nextSecond); // time change if (nextTimeInSeconds < currentTimeInSeconds) { // advance to next day nextCal.add(Calendar.DATE, 1); } return nextCal; } private Calendar computeNextDayOfWeek(Calendar nextCal) { Integer nextDayOfWeek = this.dayOfWeek.getNextMatch(nextCal); if (nextDayOfWeek == null) { return null; } int currentDayOfWeek = nextCal.get(Calendar.DAY_OF_WEEK); // if the current day-of-week is a match, then nothing else to // do. Just return back the calendar if (currentDayOfWeek == nextDayOfWeek) { return nextCal; } int currentMonth = nextCal.get(Calendar.MONTH); // At this point, a suitable "next" day-of-week has been identified. // There can be 2 cases // 1) The "next" day-of-week is greater than the current day-of-week : This // implies that the next day-of-week is within the "current" week. // 2) The "next" day-of-week is lesser than the current day-of-week : This implies // that the next day-of-week is in the next week (i.e. current week needs to // be advanced to next week). if (nextDayOfWeek < currentDayOfWeek) { // advance one week nextCal.add(Calendar.WEEK_OF_MONTH, 1); } // set the chosen day of week nextCal.set(Calendar.DAY_OF_WEEK, nextDayOfWeek); // since we are moving to a different day-of-week (as compared to the current day-of-week), // we should reset the second, minute and hour appropriately, to their first possible // values resetTimeToFirstValues(nextCal); if (nextCal.get(Calendar.MONTH) != currentMonth) { nextCal = computeNextMonth(nextCal); } return nextCal; } private Calendar computeNextMonth(Calendar nextCal) { Integer nextMonth = this.month.getNextMatch(nextCal); if (nextMonth == null) { return null; } int currentMonth = nextCal.get(Calendar.MONTH); // if the current month is a match, then nothing else to // do. Just return back the calendar if (currentMonth == nextMonth) { return nextCal; } // At this point, a suitable "next" month has been identified. // There can be 2 cases // 1) The "next" month is greater than the current month : This // implies that the next month is within the "current" year. // 2) The "next" month is lesser than the current month : This implies // that the next month is in the next year (i.e. current year needs to // be advanced to next year). if (nextMonth < currentMonth) { // advance to next year nextCal.add(Calendar.YEAR, 1); } // set the chosen month nextCal.set(Calendar.MONTH, nextMonth); // since we are moving to a different month (as compared to the current month), // we should reset the second, minute, hour, day-of-week and dayofmonth appropriately, to their first possible // values nextCal.set(Calendar.DAY_OF_WEEK, this.dayOfWeek.getFirst()); nextCal.set(Calendar.DAY_OF_MONTH, 1); resetTimeToFirstValues(nextCal); return nextCal; } private Calendar computeNextDate(Calendar nextCal) { if (this.isDayOfMonthWildcard()) { return this.computeNextDayOfWeek(nextCal); } if (this.isDayOfWeekWildcard()) { return this.computeNextDayOfMonth(nextCal); } // both day-of-month and day-of-week are *non-wildcards* Calendar nextDayOfMonthCal = this.computeNextDayOfMonth((Calendar) nextCal.clone()); Calendar nextDayOfWeekCal = this.computeNextDayOfWeek((Calendar) nextCal.clone()); if (nextDayOfMonthCal == null) { return nextDayOfWeekCal; } if (nextDayOfWeekCal == null) { return nextDayOfMonthCal; } return nextDayOfWeekCal.getTime().before(nextDayOfMonthCal.getTime()) ? nextDayOfWeekCal : nextDayOfMonthCal; } private Calendar computeNextDayOfMonth(Calendar nextCal) { Integer nextDayOfMonth = this.dayOfMonth.getNextMatch(nextCal); if (nextDayOfMonth == null) { return null; } int currentDayOfMonth = nextCal.get(Calendar.DAY_OF_MONTH); // if the current day-of-month is a match, then nothing else to // do. Just return back the calendar if (currentDayOfMonth == nextDayOfMonth) { return nextCal; } if (nextDayOfMonth > currentDayOfMonth) { if (this.monthHasDate(nextCal, nextDayOfMonth)) { // set the chosen day-of-month nextCal.set(Calendar.DAY_OF_MONTH, nextDayOfMonth); // since we are moving to a different day-of-month (as compared to the current day-of-month), // we should reset the second, minute and hour appropriately, to their first possible // values resetTimeToFirstValues(nextCal); } else { nextCal = this.advanceTillMonthHasDate(nextCal, nextDayOfMonth); } } else { // since the next day is before the current day we need to shift to the next month nextCal.add(Calendar.MONTH, 1); // also we need to reset the time resetTimeToFirstValues(nextCal); nextCal = this.computeNextMonth(nextCal); if (nextCal == null) { return null; } nextDayOfMonth = this.dayOfMonth.getFirstMatch(nextCal); if (nextDayOfMonth == null) { return null; } // make sure the month can handle the date nextCal = this.advanceTillMonthHasDate(nextCal, nextDayOfMonth); } return nextCal; } private Calendar computeNextYear(Calendar nextCal) { Integer nextYear = this.year.getNextMatch(nextCal); if (nextYear == null || nextYear > Year.MAX_YEAR) { return null; } int currentYear = nextCal.get(Calendar.YEAR); // if the current year is a match, then nothing else to // do. Just return back the calendar if (currentYear == nextYear) { return nextCal; } // If the next year is lesser than the current year, then // we have no more timeouts for the calendar expression if (nextYear < currentYear) { return null; } // at this point we have chosen a year which is greater than the current // year. // set the chosen year nextCal.set(Calendar.YEAR, nextYear); // since we are moving to a different year (as compared to the current year), // we should reset all other calendar attribute expressions appropriately, to their first possible // values nextCal.set(Calendar.MONTH, this.month.getFirstMatch()); nextCal.set(Calendar.DAY_OF_MONTH, 1); resetTimeToFirstValues(nextCal); // recompute date nextCal = this.computeNextDate(nextCal); return nextCal; } private Calendar advanceTillMonthHasDate(Calendar cal, Integer date) { resetTimeToFirstValues(cal); // make sure the month can handle the date while (monthHasDate(cal, date) == false) { if (cal.get(Calendar.YEAR) > Year.MAX_YEAR) { return null; } // this month can't handle the date, so advance month to next month // and get the next suitable matching month cal.add(Calendar.MONTH, 1); cal = this.computeNextMonth(cal); if (cal == null) { return null; } date = this.dayOfMonth.getFirstMatch(cal); if (date == null) { return null; } } cal.set(Calendar.DAY_OF_MONTH, date); return cal; } private boolean monthHasDate(Calendar cal, int date) { return date <= cal.getActualMaximum(Calendar.DAY_OF_MONTH); } private boolean isAfterEnd(Calendar cal) { Date end = this.scheduleExpression.getEnd(); if (end == null) { return false; } // check that the next timeout isn't past the end date return cal.getTime().after(end); } private boolean noMoreTimeouts(Calendar cal) { if (cal.get(Calendar.YEAR) > Year.MAX_YEAR || isAfterEnd(cal)) { return true; } return false; } private boolean isDayOfWeekWildcard() { return this.scheduleExpression.getDayOfWeek().equals("*"); } private boolean isDayOfMonthWildcard() { return this.scheduleExpression.getDayOfMonth().equals("*"); } /** * * @param calendar */ private void resetTimeToFirstValues(Calendar calendar) { final int currentHour = calendar.get(Calendar.HOUR_OF_DAY); final int currentMinute = calendar.get(Calendar.MINUTE); final int currentSecond = calendar.get(Calendar.SECOND); final int firstHour = this.hour.getFirst(); final int firstMinute = this.minute.getFirst(); final int firstSecond = this.second.getFirst(); if (currentHour != firstHour || currentMinute != firstMinute || currentSecond != firstSecond) { setTime(calendar, firstHour, firstMinute, firstSecond); } } private void setTime(Calendar calendar, int hour, int minute, int second) { int dst = calendar.get(Calendar.DST_OFFSET); calendar.clear(Calendar.HOUR_OF_DAY); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.clear(Calendar.MINUTE); calendar.set(Calendar.MINUTE, minute); calendar.clear(Calendar.SECOND); calendar.set(Calendar.SECOND, second); // restore summertime offset WFLY-9537 // this is to avoid to have the standard time (winter) set by GregorianCalendar // after clear and set the time explicit // see comment for computeTime() -> http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/GregorianCalendar.java#2776 calendar.set(Calendar.DST_OFFSET, dst); } }
package com.yahoo.document; import com.google.inject.Inject; import com.yahoo.config.subscription.ConfigSubscriber; import com.yahoo.document.annotation.AnnotationReferenceDataType; import com.yahoo.document.annotation.AnnotationType; import com.yahoo.document.annotation.AnnotationTypeRegistry; import com.yahoo.document.annotation.AnnotationTypes; import com.yahoo.document.config.DocumentmanagerConfig; import com.yahoo.document.serialization.DocumentDeserializer; import com.yahoo.document.serialization.DocumentDeserializerFactory; import com.yahoo.io.GrowableByteBuffer; import com.yahoo.tensor.TensorType; import java.lang.reflect.Modifier; import java.util.*; import java.util.logging.Logger; /** * The DocumentTypeManager keeps track of the document types registered in * the Vespa common repository. * <p> * The DocumentTypeManager is also responsible for registering a FieldValue * factory for each data type a field can have. The Document object * uses this factory to serialize and deserialize the various datatypes. * The factory could also be used to expand the functionality of various * datatypes, for instance displaying the data type in human-readable form * or as XML. * * @author Thomas Gundersen */ public class DocumentTypeManager { private final static Logger log = Logger.getLogger(DocumentTypeManager.class.getName()); private ConfigSubscriber subscriber; // *Configured data types* (not built-in/primitive) indexed by their id // *Primitive* data types are always available and have a single id. // *Built-in dynamic* types: The tensor type. // Any tensor type has the same id and is always available just like primitive types. // However, unlike primitive types, each tensor type is a separate DataType instance // (which carries additional type information (detailedType) supplied at runtime). // The reason for this is that we want the data type to stay the same when we change the detailed tensor type // to maintain compatibility on (some) tensor type changes. private Map<Integer, DataType> dataTypes = new LinkedHashMap<>(); private Map<DataTypeName, DocumentType> documentTypes = new LinkedHashMap<>(); private AnnotationTypeRegistry annotationTypeRegistry = new AnnotationTypeRegistry(); public DocumentTypeManager() { registerDefaultDataTypes(); } @Inject public DocumentTypeManager(DocumentmanagerConfig config) { this(); DocumentTypeManagerConfigurer.configureNewManager(config, this); } public void assign(DocumentTypeManager other) { dataTypes = other.dataTypes; documentTypes = other.documentTypes; annotationTypeRegistry = other.annotationTypeRegistry; } public DocumentTypeManager configure(String configId) { subscriber = DocumentTypeManagerConfigurer.configure(this, configId); return this; } private void registerDefaultDataTypes() { DocumentType superDocType = DataType.DOCUMENT; dataTypes.put(superDocType.getId(), superDocType); documentTypes.put(superDocType.getDataTypeName(), superDocType); Class<? extends DataType> dataTypeClass = DataType.class; for (java.lang.reflect.Field field : dataTypeClass.getFields()) { if (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) { if (DataType.class.isAssignableFrom(field.getType())) { try { //these are all static final DataTypes listed in DataType: DataType type = (DataType) field.get(null); register(type); } catch (IllegalAccessException e) { //ignore } } } } for (AnnotationType type : AnnotationTypes.ALL_TYPES) { annotationTypeRegistry.register(type); } } public boolean hasDataType(String name) { if (name.startsWith("tensor(")) return true; // built-in dynamic: Always present for (DataType type : dataTypes.values()) { if (type.getName().equalsIgnoreCase(name)) { return true; } } return false; } public boolean hasDataType(int code) { if (code == DataType.tensorDataTypeCode) return true; // built-in dynamic: Always present return dataTypes.containsKey(code); } public DataType getDataType(String name) { if (name.startsWith("tensor(")) // built-in dynamic return new TensorDataType(TensorType.fromSpec(name)); List<DataType> foundTypes = new ArrayList<>(); for (DataType type : dataTypes.values()) { if (type.getName().equalsIgnoreCase(name)) { foundTypes.add(type); } } if (foundTypes.isEmpty()) { throw new IllegalArgumentException("No datatype named " + name); } else if (foundTypes.size() == 1) { return foundTypes.get(0); } else { //the found types are probably documents or structs, sort them by type Collections.sort(foundTypes, new Comparator<DataType>() { public int compare(DataType first, DataType second) { if (first instanceof StructuredDataType && !(second instanceof StructuredDataType)) { return 1; } else if (!(first instanceof StructuredDataType) && second instanceof StructuredDataType) { return -1; } else { return 0; } } }); } return foundTypes.get(0); } public DataType getDataType(int code) { return getDataType(code, ""); } /** * Return a data type instance * * @param code the code of the data type to return, which must be either built in or present in this manager * @param detailedType detailed type information, or the empty string if none * @return the appropriate DataType instance */ public DataType getDataType(int code, String detailedType) { if (code == DataType.tensorDataTypeCode) // built-in dynamic return new TensorDataType(TensorType.fromSpec(detailedType)); DataType type = dataTypes.get(code); if (type == null) { StringBuilder types=new StringBuilder(); for (Integer key : dataTypes.keySet()) { types.append(key).append(" "); } throw new IllegalArgumentException("No datatype with code " + code + ". Registered type ids: " + types); } else { return type; } } @SuppressWarnings("deprecation") DataType getDataTypeAndReturnTemporary(int code, String detailedType) { if (hasDataType(code)) { return getDataType(code, detailedType); } return new TemporaryDataType(code, detailedType); } /** * Register a data type of any sort, including document types. * @param type The datatype to register * TODO Give unique ids to document types */ public void register(DataType type) { type.register(this); // Recursively walk through all nested types and call registerSingleType for each one } /** * Register a single datatype. Re-registering an existing, but equal, datatype is ok. * * @param type The datatype to register */ @SuppressWarnings("deprecation") void registerSingleType(DataType type) { if (type instanceof TensorDataType) return; if (type instanceof TemporaryDataType) { throw new IllegalArgumentException("TemporaryDataType no longer supported: " + type); } if (type instanceof TemporaryStructuredDataType) { throw new IllegalArgumentException("TemporaryStructuredDataType no longer supported: " + type); } if (dataTypes.containsKey(type.getId())) { DataType existingType = dataTypes.get(type.getId()); if (((type instanceof TemporaryDataType) || (type instanceof TemporaryStructuredDataType)) && !((existingType instanceof TemporaryDataType) || (existingType instanceof TemporaryStructuredDataType))) { //we're trying to register a temporary type over a permanent one, don't do that: return; } else if ((existingType == type || existingType.equals(type)) && !(existingType instanceof TemporaryDataType) && !(type instanceof TemporaryDataType) && !(existingType instanceof TemporaryStructuredDataType) && !(type instanceof TemporaryStructuredDataType)) { // Shortcut to improve speed // Oki. Already registered. return; } else if (type instanceof DocumentType && dataTypes.get(type.getId()) instanceof DocumentType) { /* DocumentType newInstance = (DocumentType) type; DocumentType oldInstance = (DocumentType) dataTypes.get(type.getId()); TODO fix tests */ log.warning("Document type " + existingType + " is not equal to document type attempted registered " + type + ", but have same name. OVERWRITING TYPE as many tests currently does this. " + "Fix tests so we can throw exception here."); // + type + ", but already uses id " + type.getId()); } else if ((existingType instanceof TemporaryDataType) || (existingType instanceof TemporaryStructuredDataType)) { //removing temporary type to be able to register correct type dataTypes.remove(existingType.getId()); } else { throw new IllegalStateException("Datatype " + existingType + " is not equal to datatype attempted registered " + type + ", but already uses id " + type.getId()); } } if (type instanceof DocumentType) { DocumentType docType = (DocumentType) type; if (docType.getInheritedTypes().size() == 0) { docType.inherit(documentTypes.get(new DataTypeName("document"))); } documentTypes.put(docType.getDataTypeName(), docType); } dataTypes.put(type.getId(), type); type.setRegistered(); } /** * Registers a document type. Typically called by someone * importing the document types from the common Vespa repository. * * @param docType The document type to register. * @return the previously registered type, or null if none was registered */ public DocumentType registerDocumentType(DocumentType docType) { register(docType); return docType; } /** * Gets a registered document. * * @param name the document name of the type * @return returns the document type found, * or null if there is no type with this name */ public DocumentType getDocumentType(DataTypeName name) { return documentTypes.get(name); } /** * Returns a registered document type * * @param name the type name of the document type * @return returns the document type having this name, or null if none */ public DocumentType getDocumentType(String name) { return documentTypes.get(new DataTypeName(name)); } final public Document createDocument(GrowableByteBuffer buf) { DocumentDeserializer data = DocumentDeserializerFactory.create6(this, buf); return new Document(data); } public Document createDocument(DocumentDeserializer data) { return new Document(data); } /** * Returns a read only view of the registered data types * * @return collection of types */ public Collection<DataType> getDataTypes() { return Collections.unmodifiableCollection(dataTypes.values()); } /** * A read only view of the registered document types * @return map of types */ public Map<DataTypeName, DocumentType> getDocumentTypes() { return Collections.unmodifiableMap(documentTypes); } public Iterator<DocumentType> documentTypeIterator() { return documentTypes.values().iterator(); } /** * Clears the DocumentTypeManager. After this operation, * only the default document type and data types are available. */ public void clear() { documentTypes.clear(); dataTypes.clear(); registerDefaultDataTypes(); } public AnnotationTypeRegistry getAnnotationTypeRegistry() { return annotationTypeRegistry; } public void shutdown() { if (subscriber!=null) subscriber.close(); } }
package com.microsoft.rest; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang3.ClassUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.Period; import java.lang.reflect.Field; import java.util.List; import java.util.Map; /** * Validates user provided parameters are not null if they are required. */ public class Validator { /** * Validates a user provided required parameter to be not null. * A {@link ServiceException} is thrown if a property fails the validation. * * @param parameter the parameter to validate * @throws ServiceException failures wrapped in {@link ServiceException} */ public static void validate(Object parameter) throws ServiceException { // Validation of top level payload is done outside if (parameter == null) { return; } Class parameterType = parameter.getClass(); if (ClassUtils.isPrimitiveOrWrapper(parameterType) || parameterType.isEnum() || ClassUtils.isAssignable(parameterType, LocalDate.class) || ClassUtils.isAssignable(parameterType, DateTime.class) || ClassUtils.isAssignable(parameterType, String.class) || ClassUtils.isAssignable(parameterType, DateTimeRfc1123.class) || ClassUtils.isAssignable(parameterType, Period.class)) { return; } Field[] fields = FieldUtils.getAllFields(parameterType); for (Field field : fields) { field.setAccessible(true); JsonProperty annotation = field.getAnnotation(JsonProperty.class); Object property; try { property = field.get(parameter); } catch (IllegalAccessException e) { throw new ServiceException(e); } if (property == null) { if (annotation != null && annotation.required()) { throw new ServiceException( new IllegalArgumentException(field.getName() + " is required and cannot be null.")); } } else { try { Class propertyType = property.getClass(); if (ClassUtils.isAssignable(propertyType, List.class)) { List<?> items = (List<?>)property; for (Object item : items) { Validator.validate(item); } } else if (ClassUtils.isAssignable(propertyType, Map.class)) { Map<?, ?> entries = (Map<?, ?>)property; for (Map.Entry<?, ?> entry : entries.entrySet()) { Validator.validate(entry.getKey()); Validator.validate(entry.getValue()); } } else if (parameter.getClass().getDeclaringClass() != propertyType) { Validator.validate(property); } } catch (ServiceException ex) { IllegalArgumentException cause = (IllegalArgumentException)(ex.getCause()); if (cause != null) { // Build property chain throw new ServiceException( new IllegalArgumentException(field.getName() + "." + cause.getMessage())); } else { throw ex; } } } } } /** * Validates a user provided required parameter to be not null. Returns if * the parameter passes the validation. A {@link ServiceException} is passed * to the {@link ServiceCallback#failure(Throwable)} if a property fails the validation. * * @param parameter the parameter to validate * @param serviceCallback the callback to call with the failure */ public static void validate(Object parameter, ServiceCallback<?> serviceCallback) { try { validate(parameter); } catch (ServiceException ex) { serviceCallback.failure(ex); } } }
package com.dpforge.droidgif.decoder2; import java.util.ArrayList; import java.util.List; public class GIFImage { private ColorTable mGlobalColorTable; private List<GIFImageFrame> mFrames = new ArrayList<>(1); GIFImage() { } ColorTable globalColorTable() { return mGlobalColorTable; } public boolean isEmpty() { return mFrames.isEmpty(); } public int framesCount() { return mFrames.size(); } public GIFImageFrame getFrame(final int index) { return mFrames.get(index); } void setGlobalColorTable(final ColorTable colorTable) { mGlobalColorTable = colorTable; } GIFImageFrame addFrame(final TableBasedImageDecoder imageDecoder, final GraphicControlExtensionDecoder decoder) { GIFImageFrame frame = new GIFImageFrame(this, imageDecoder, decoder); mFrames.add(frame); return frame; } }
package org.flymine.dataconversion; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Properties; 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.io.File; import java.io.FileWriter; import java.io.IOException; import org.intermine.InterMineException; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.xml.full.ItemHelper; import org.intermine.metadata.Model; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.FieldNameAndValue; import org.intermine.dataconversion.ItemPrefetchDescriptor; import org.intermine.dataconversion.ItemPrefetchConstraintDynamic; import org.intermine.dataconversion.ItemReader; import org.intermine.dataconversion.ItemWriter; import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl; import org.intermine.dataconversion.ObjectStoreItemReader; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.SimpleConstraint; import org.apache.log4j.Logger; /** * DataTranslator specific to uniprot. * * @author Matthew Wakeling * @author Richard Smith */ public class UniprotDataTranslator extends DataTranslator { private static final Logger LOG = Logger.getLogger(UniprotDataTranslator.class); private Map databases = new HashMap(); private Map pubMedIdToPublicationId = new HashMap(); private Map geneIdentifierToId = new HashMap(); private int pubLinkCount = 0; private Map organisms = new HashMap(); private FileWriter fw = null; private boolean outputIdentifiers = false; private Map identifierToOrganismDbId = new HashMap(); //geneIdentifier is hugo id from ensembl-human, don't create private boolean createGeneIdentifier = true; private Item uniprotDataSet; private Reference uniprotDataSetRef; private Set geneIdentifiers = new HashSet(); private static final String SRC_NS = "http://www.flymine.org/model/uniprot /** * @see DataTranslator */ public UniprotDataTranslator(ItemReader srcItemReader, Properties mapping, Model srcModel, Model tgtModel) { super(srcItemReader, mapping, srcModel, tgtModel); this.tgtNs = tgtNs; this.srcItemReader = srcItemReader; uniprotDataSet = createItem("DataSet"); // TODO: the dataset name shouldn't be hard coded: uniprotDataSet.addAttribute(new Attribute("title", "UniProt data set")); uniprotDataSetRef = new Reference("source", uniprotDataSet.getIdentifier()); } /** * @see DataTranslator#getItemIterator */ public Iterator getItemIterator() throws ObjectStoreException { Query q = new Query(); q.setDistinct(false); QueryClass qc1 = new QueryClass(org.intermine.model.fulldata.Item.class); q.addFrom(qc1); q.addToSelect(qc1); SimpleConstraint sc1 = new SimpleConstraint(new QueryField(qc1, "className"), ConstraintOp.EQUALS, new QueryValue(SRC_NS + "Entry")); q.setConstraint(sc1); // TODO batch size usually 1000, increase again if ObjectStoreItemPathFollowingImpl query // generation creates queries that can use bag temprorary tables more effectively return ((ObjectStoreItemReader) srcItemReader).itemIterator(q, 1000); } /** * @see DataTranslator#translate */ public void translate(ItemWriter tgtItemWriter) throws ObjectStoreException, InterMineException { try { tgtItemWriter.store(ItemHelper.convert(uniprotDataSet)); if (outputIdentifiers) { fw = new FileWriter(new File("uniprot_gene_identifiers")); } super.translate(tgtItemWriter); // store databases Iterator i = databases.values().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } // store organisms i = organisms.values().iterator(); while (i.hasNext()) { tgtItemWriter.store(ItemHelper.convert((Item) i.next())); } if (outputIdentifiers) { fw.flush(); fw.close(); } } catch (IOException e) { throw new InterMineException(e); } } /** * @see DataTranslator#translateItem */ protected Collection translateItem(Item srcItem) throws ObjectStoreException, InterMineException { // This Item should be an EntryType and only have proteins associated with one organism. if (!(SRC_NS + "Entry").equals(srcItem.getClassName())) { throw new IllegalArgumentException("Attempted to translate and Uniprot source Item that" + " is not of class " + SRC_NS + "Entry"); } // First things first: find out the taxonid of the organism of this entry. int taxonId = 0; List organismList = getItemsInCollection(srcItem.getCollection("organisms")); Iterator organismIter = organismList.iterator(); while (organismIter.hasNext()) { // Drosophila melanogaster = 7227 // Caenorhabditis elegans 6239 // Anopheles gambiae = 7165 // Homo sapiens = 9606 Item organism = (Item) organismIter.next(); Iterator dbRefIter = getItemsInCollection( organism.getCollection("dbReferences")).iterator(); while (dbRefIter.hasNext()) { Item dbReference = (Item) dbRefIter.next(); String type = getAttributeValue(dbReference, "type"); if ("NCBI Taxonomy".equals(type)) { String taxonString = getAttributeValue(dbReference, "id"); if (taxonId != 0) { throw new IllegalStateException("Attempting to set taxon id to " + taxonString + " when it is already " + taxonId); } taxonId = Integer.parseInt(taxonString); } } } if (taxonId != 0) { Set retval = new HashSet(); Reference organismReference = new Reference("organism", getOrganismId(taxonId)); // 1. create Protein, same for all organisms // <entry> Item protein = createItem(tgtNs + "Protein", ""); // find name and set all names as synonyms List proteinNames = getItemsInCollection(srcItem.getCollection("names")); String proteinName = (String) getAttributeValue((Item) proteinNames.get(0), "name"); protein.addAttribute(new Attribute("identifier", proteinName)); protein.addReference(organismReference); retval.add(createSynonym(protein.getIdentifier(), "identifier", proteinName, getDataSourceId("UniProt"))); // find primary accession and set others as synonyms <entry><accession>* List srcAccessions = getItemsInCollection(srcItem.getCollection("accessions")); if (srcAccessions.isEmpty()) { // do not create store Protein if no primary accession LOG.info("Entry " + proteinName + " does not have any accessions"); return Collections.EMPTY_SET; } else { // primary accession is first in list Item srcPrimaryAccession = (Item) srcAccessions.get(0); protein.addAttribute(new Attribute("primaryAccession", getAttributeValue( srcPrimaryAccession, "accession"))); // all accessions should be Synonyms Iterator srcAccIter = srcAccessions.iterator(); while (srcAccIter.hasNext()) { Item srcAccession = (Item) srcAccIter.next(); String srcAccessionString = getAttributeValue(srcAccession, "accession"); retval.add(createSynonym(protein.getIdentifier(), "accession", srcAccessionString, getDataSourceId("UniProt"))); } } // add UniProt Database to evidence collection ReferenceList evidence = new ReferenceList("evidence", new ArrayList()); evidence.addRefId(getDataSourceId("UniProt")); protein.addCollection(evidence); // 2. first name should be protein name, all should be Synonyms // <entry><protein><name>* Item srcProtein = ItemHelper.convert(srcItemReader.getItemById(srcItem .getReference("protein").getRefId())); if (srcProtein != null) { List srcProteinNames = getItemsInCollection(srcProtein.getCollection("names")); Iterator srcProtNameIter = srcProteinNames.iterator(); while (srcProtNameIter.hasNext()) { Item srcProteinName = (Item) srcProtNameIter.next(); String srcProteinNameStr = getAttributeValue(srcProteinName, "name"); if (!protein.hasAttribute("name")) { protein.setAttribute("name", srcProteinNameStr); } String srcProteinNameEvidence = getAttributeValue(srcProteinName, "evidence"); if (srcProteinNameEvidence != null) { srcProteinNameStr += " (Evidence " + srcProteinNameEvidence + ")"; } retval.add(createSynonym(protein.getIdentifier(), "name", srcProteinNameStr, getDataSourceId("UniProt"))); } } // 3. get collection of Comments // <entry><comment>* List srcComments = getItemsInCollection(srcItem.getCollection("comments")); ReferenceList comments = new ReferenceList("comments", new ArrayList()); Iterator srcComIter = srcComments.iterator(); while (srcComIter.hasNext()) { Item srcComment = (Item) srcComIter.next(); String srcCommentType = getAttributeValue(srcComment, "type"); String srcCommentText = getAttributeValue(srcComment, "text"); if ((srcCommentType != null) && (srcCommentText != null)) { Item comment = createItem(tgtNs + "Comment", ""); comment.addAttribute(new Attribute("type", srcCommentType)); comment.addAttribute(new Attribute("text", srcCommentText)); comment.addReference(uniprotDataSetRef); comments.addRefId(comment.getIdentifier()); retval.add(comment); } } if (comments.getRefIds().size() > 0) { protein.addCollection(comments); } // 4. create a collection of Publications related to this protein // <entry><reference>* List srcReferences = getItemsInCollection(srcItem.getCollection("references")); ReferenceList publications = null; Iterator srcRefIter = srcReferences.iterator(); while (srcRefIter.hasNext()) { Item srcReference = (Item) srcRefIter.next(); Item srcCitation = ItemHelper.convert(srcItemReader.getItemById(srcReference .getReference("citation").getRefId())); List srcDbReferences = getItemsInCollection(srcCitation .getCollection("dbReferences")); Iterator srcDbRefIter = srcDbReferences.iterator(); while (srcDbRefIter.hasNext()) { Item srcDbReference = (Item) srcDbRefIter.next(); String type = getAttributeValue(srcDbReference, "type"); if ("PubMed".equals(type)) { String pubMedString = new String(getAttributeValue(srcDbReference, "id")); String publicationId = (String) pubMedIdToPublicationId .get(pubMedString); pubLinkCount++; if (publicationId == null) { Item publication = createItem(tgtNs + "Publication", ""); publication.addAttribute(new Attribute("pubMedId", pubMedString)); retval.add(publication); publicationId = publication.getIdentifier(); pubMedIdToPublicationId.put(pubMedString, publicationId); if (pubMedIdToPublicationId.size() % 100 == 0) { LOG.info("Processed " + pubMedIdToPublicationId.size() + " publications, with " + pubLinkCount + " references to publications"); } } if (publications == null) { publications = new ReferenceList("publications", new ArrayList()); protein.addCollection(publications); } publications.addRefId(publicationId); } } } // 5. create a Sequence object and reference from Protein // <entry><sequence> Reference seqRef = srcItem.getReference("sequence"); if (seqRef != null) { Item srcSeq = ItemHelper.convert(srcItemReader.getItemById(seqRef.getRefId())); if (srcSeq != null) { Item sequence = createItem(tgtNs + "Sequence", ""); String residues = srcSeq.getAttribute("sequence").getValue(); sequence.addAttribute(new Attribute("residues", residues)); sequence.addAttribute(new Attribute("length", "" + residues.length())); retval.add(sequence); protein.addReference(new Reference("sequence", sequence.getIdentifier())); } } // TODO many dbReference types are present in uniprot records - e.g. Pfam, InterPro. // Specifc code could be add to create additional objects // 6. now try to create reference to gene, choice of identifier is organism specific // <entry><gene>* // <entry><dbReference> // a protein can be related to multiple genes List srcGenes = getItemsInCollection(srcItem.getCollection("genes")); ReferenceList geneCollection = null; Iterator srcGeneIter = srcGenes.iterator(); while (srcGeneIter.hasNext()) { Item srcGene = (Item) srcGeneIter.next(); List srcGeneNames = getItemsInCollection(srcGene.getCollection("names")); // Gene.identifier = <entry><gene><name type="ORF"> String geneIdentifier = null; // Gene.name = <entry><gene><name type="primary"> String primaryGeneName = null; Set geneNames = new HashSet(); { Iterator srcGeneNameIter = srcGeneNames.iterator(); String notCG = null; while (srcGeneNameIter.hasNext()) { Item srcGeneName = (Item) srcGeneNameIter.next(); if ("primary".equals(getAttributeValue(srcGeneName, "type"))) { primaryGeneName = new String(getAttributeValue(srcGeneName, "name")); } else if ("ORF".equals(getAttributeValue(srcGeneName, "type"))) { String tmp = getAttributeValue(srcGeneName, "name"); if ((taxonId == 7227) && (!tmp.startsWith("CG"))) { notCG = tmp; } else { geneIdentifier = tmp; } } geneNames.add(new String(getAttributeValue(srcGeneName, "name"))); } // Some UniProt entries have CGxxx as Dmel_CGxxx - need to strip prefix // so that they match identifiers from other sources. Some genes have // embl identifiers and no FlyBase id, ignore these. if (geneIdentifier == null && notCG != null) { if (notCG.startsWith("Dmel_")) { geneIdentifier = notCG.substring(5); } else { LOG.info("Found a Drosophila gene without a CG identifer: " + notCG); } } } String dbId = null; boolean createGene = false; // geneOrganismDbId = <entry><dbReference><type="FlyBase/WormBase/.."> // where designation = primary gene name String geneOrganismDbId = null; if (taxonId == 7227) { // D. melanogaster geneOrganismDbId = getDataSourceReferenceValue(srcItem, "FlyBase", geneNames); // For fly data use CGxxx as key instead of FBgnxxx if (geneIdentifier != null) { createGene = true; dbId = getDataSourceId("FlyBase"); } } else if (taxonId == 6239) { // C. elegans geneOrganismDbId = getDataSourceReferenceValue(srcItem, "WormBase", geneNames); if (geneOrganismDbId != null) { createGene = true; dbId = getDataSourceId("WormBase"); } } else if (taxonId == 180454) { // A. gambiae str. PEST // no organismDbId and no specific dbxref to enembl - assume that geneIdentifier // is always ensembl gene stable id and set organismDbId to be identifier if (geneIdentifier != null) { createGene = true; geneOrganismDbId = geneIdentifier; dbId = getDataSourceId("ensembl"); } } else if (taxonId == 9606) { // H. sapiens geneOrganismDbId = getDataSourceReferenceValue(srcItem, "Ensembl", null); if (geneOrganismDbId != null) { createGene = true; dbId = getDataSourceId("Ensembl"); createGeneIdentifier = false; } } // output gene identifier details if (outputIdentifiers) { try { fw.write(taxonId + "\tprotein: " + proteinName + "\tname: " + primaryGeneName + "\tidentifier: " + geneIdentifier + "\tgeneOrganismDbId: " + geneOrganismDbId + System.getProperty("line.separator")); } catch (IOException e) { throw new InterMineException(e); } } // uniprot data source has primary key of Gene.organismDbId // only create gene if a value was found if (createGene) { // may alrady have created this gene String geneItemId = (String) geneIdentifierToId.get(geneOrganismDbId); ReferenceList geneSynonyms = new ReferenceList("synonyms", new ArrayList()); // UniProt sometimes has same identifier paired with two organismDbIds // causes problems merging other data sources. Simple check to prevent // creating a gene with a duplicate identifier. // log problem genes boolean isDuplicateIdentifier = false; if ((geneItemId == null) && geneIdentifiers.contains(geneIdentifier)) { LOG.warn("already created a gene for identifier: " + geneIdentifier + " with different organismDbId, discarding this one"); isDuplicateIdentifier = true; } if ((geneItemId == null) && !isDuplicateIdentifier) { Item gene = createItem(tgtNs + "Gene", ""); if (geneOrganismDbId != null) { if (geneOrganismDbId.equals("")) { LOG.info("geneOrganismDbId was empty string"); } gene.addAttribute(new Attribute("organismDbId", geneOrganismDbId)); Item synonym = createSynonym(gene.getIdentifier(), "identifier", geneOrganismDbId, dbId); geneSynonyms.addRefId(synonym.getIdentifier()); retval.add(synonym); } if (geneIdentifier != null && createGeneIdentifier) { gene.addAttribute(new Attribute("identifier", geneIdentifier)); // don't create duplicate synonym if (!geneIdentifier.equals(geneOrganismDbId)) { Item synonym = createSynonym(gene.getIdentifier(), "identifier", geneIdentifier, dbId); geneSynonyms.addRefId(synonym.getIdentifier()); retval.add(synonym); } // keep a track of non-null gene identifiers geneIdentifiers.add(geneIdentifier); } // Problem with gene names for drosophila - ignore if (primaryGeneName != null && taxonId != 7227) { gene.addAttribute(new Attribute("symbol", primaryGeneName)); } gene.addReference(organismReference); // add UniProt Database to evidence collection ReferenceList evidence1 = new ReferenceList("evidence", new ArrayList()); evidence1.addRefId(getDataSourceId("UniProt")); gene.addCollection(evidence1); // everything in <entry><gene><name>* becomes a Synonym Iterator srcGeneNameIter = srcGeneNames.iterator(); while (srcGeneNameIter.hasNext()) { Item srcGeneName = (Item) srcGeneNameIter.next(); String type = getAttributeValue(srcGeneName, "type"); String symbol = getAttributeValue(srcGeneName, "name"); // synonym already created for ORF as identifer if (!type.equals("ORF")) { Item synonym = createSynonym(gene.getIdentifier(), (type.equals("primary") || type.equals("synonym")) ? "symbol" : type, symbol, dbId); geneSynonyms.addRefId(synonym.getIdentifier()); retval.add(synonym); } } gene.addCollection(geneSynonyms); geneItemId = gene.getIdentifier(); geneIdentifierToId.put(geneOrganismDbId, geneItemId); retval.add(gene); } // TODO untidy - sould just do this check once if (!isDuplicateIdentifier) { if (geneCollection == null) { geneCollection = new ReferenceList("genes", new ArrayList()); protein.addCollection(geneCollection); } geneCollection.addRefId(geneItemId); } } } retval.add(protein); return retval; } return Collections.EMPTY_SET; } private Item createSynonym(String subjectId, String type, String value, String dbId) { Item synonym = createItem(tgtNs + "Synonym", ""); synonym.addReference(new Reference("subject", subjectId)); synonym.addAttribute(new Attribute("type", type)); synonym.addAttribute(new Attribute("value", value)); synonym.addReference(new Reference("source", dbId)); return synonym; } private String getDataSourceId(String title) { return getDataSource(title).getIdentifier(); } private Item getDataSource(String title) { Item database = (Item) databases.get(title); if (database == null) { database = createItem(tgtNs + "DataSource", ""); database.addAttribute(new Attribute("name", title)); databases.put(title, database); } return database; } private String getOrganismId(int taxonId) { return getOrganism(taxonId).getIdentifier(); } private Item getOrganism(int taxonId) { Integer taxonIdObj = new Integer(taxonId); if (organisms.get(taxonIdObj) == null) { Item organism = createItem(tgtNs + "Organism", ""); organism.addAttribute(new Attribute("taxonId", taxonIdObj.toString())); organisms.put(taxonIdObj, organism); } return (Item) organisms.get(taxonIdObj); } /** * Get a value for a DBReference relating to a gene that has a "gene designation" property * that marches a gene name. * @param srcItem the uniprot Entry item * @param dbName the type of the DBReference to find * @param geneNames the available names for the gene * @return the DBReference value or null of none found * @throws ObjectStoreException if problem reading database */ protected String getDataSourceReferenceValue(Item srcItem, String dbName, Set geneNames) throws ObjectStoreException { String geneIdentifier = null; List srcDbRefs = getItemsInCollection(srcItem.getCollection("dbReferences"), "type", dbName); Iterator srcDbRefIter = srcDbRefs.iterator(); while (srcDbRefIter.hasNext()) { Item srcDbReference = (Item) srcDbRefIter.next(); String type = getAttributeValue(srcDbReference, "type"); if (dbName.equals(type)) { // uncomment to set geneIdentifier if there is no propertys collection present (?) //if ((srcDbRefs.size() == 1) && (srcGenes.size() == 1)) { // geneIdentifier = new String(getAttributeValue(srcDbReference,"id")); //} else { List srcProperties = getItemsInCollection(srcDbReference .getCollection("propertys")); Iterator srcPropertyIter = srcProperties.iterator(); while (srcPropertyIter.hasNext()) { Item srcProperty = (Item) srcPropertyIter.next(); String srcPropertyValue = getAttributeValue(srcProperty, "value"); if ("gene designation".equals(getAttributeValue(srcProperty, "type")) && (geneNames.contains(srcPropertyValue) || geneNames.contains(srcPropertyValue .substring(srcPropertyValue .lastIndexOf("\\") + 1)))) { geneIdentifier = new String(getAttributeValue( srcDbReference, "id")); } else if (geneNames == null && srcDbRefs.size() == 1) { geneIdentifier = new String(getAttributeValue(srcDbReference, "id")); } } if (geneIdentifier == null) { LOG.info("Found dbRefs (" + srcDbRefs.size() + ") but unable to match gene designation"); } } } return geneIdentifier; } /** * Given a ReferenceList fetch items and return a list of Items in the order that their * identifiers appear in the original ReferenceList. * @param col name of the referencelist to retrieve * @return list of items in order their identifiers appeared in ReferenceList * @throws ObjectStoreException if problems accessing database */ public List getItemsInCollection(ReferenceList col) throws ObjectStoreException { return getItemsInCollection(col, null, null); } /** * Given a ReferenceList fetch items and return a list of Items in the order that their * identifiers appear in the original ReferenceList. * @param col name of the referencelist to retrieve * @param attributeName if not null only retrieve items with given attribute name and value * @param attributeValue if not null only retrieve items with given attribute name and value * @return list of items in order their identifiers appeared in ReferenceList * @throws ObjectStoreException if problems accessing database */ public List getItemsInCollection(ReferenceList col, String attributeName, String attributeValue) throws ObjectStoreException { if ((col == null) || col.getRefIds().isEmpty()) { return Collections.EMPTY_LIST; } StringBuffer refIds = new StringBuffer(); boolean needComma = false; Iterator refIdIter = col.getRefIds().iterator(); while (refIdIter.hasNext()) { if (needComma) { refIds.append(" "); } needComma = true; refIds.append((String) refIdIter.next()); } FieldNameAndValue fnav = new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.IDENTIFIER, refIds.toString(), true); Set description; if (attributeName == null) { description = Collections.singleton(fnav); } else { description = new HashSet(); description.add(fnav); description.add(new FieldNameAndValue(attributeName, attributeValue, false)); } List unconvertedResults = srcItemReader.getItemsByDescription(description); Map itemMap = new HashMap(); Iterator uncoIter = unconvertedResults.iterator(); while (uncoIter.hasNext()) { Item item = ItemHelper.convert((org.intermine.model.fulldata.Item) uncoIter.next()); itemMap.put(item.getIdentifier(), item); } // now put items in same order as identifiers in ReferenceList List retval = new ArrayList(); refIdIter = col.getRefIds().iterator(); while (refIdIter.hasNext()) { Item tmpItem = (Item) itemMap.get(refIdIter.next()); if (tmpItem != null) { retval.add(tmpItem); } } return retval; } private String getAttributeValue(Item item, String name) { Attribute attribute = item.getAttribute(name); if (attribute != null) { return attribute.getValue(); } return null; } /** * @see org.flymine.task.DataTranslatorTask#execute */ public static Map getPrefetchDescriptors() { Map paths = new HashMap(); Set descs = new HashSet(); ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("entry.organisms"); desc.addConstraint(new ItemPrefetchConstraintDynamic("organisms", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor( "entry.organisms.dbReference"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("dbReference", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); desc = new ItemPrefetchDescriptor("entry.accessions"); desc.addConstraint(new ItemPrefetchConstraintDynamic("accessions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descs.add(desc); desc = new ItemPrefetchDescriptor("entry.comments"); desc.addConstraint(new ItemPrefetchConstraintDynamic("comments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descs.add(desc); desc = new ItemPrefetchDescriptor("entry.protein"); desc.addConstraint(new ItemPrefetchConstraintDynamic("protein", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("entry.protein.names"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("names", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); desc = new ItemPrefetchDescriptor("entry.references"); desc.addConstraint(new ItemPrefetchConstraintDynamic("references", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("entry.references.citation"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("citation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); ItemPrefetchDescriptor desc3 = new ItemPrefetchDescriptor( "entry.references.citation.dbReferences"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("dbReferences", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); descs.add(desc); desc = new ItemPrefetchDescriptor("entry.dbReferences"); desc.addConstraint(new ItemPrefetchConstraintDynamic("dbReferences", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addConstraint(new FieldNameAndValue("type", "FlyBase", false)); desc2 = new ItemPrefetchDescriptor("entry.dbReferences.propertys"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("propertys", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); desc = new ItemPrefetchDescriptor("entry.genes"); desc.addConstraint(new ItemPrefetchConstraintDynamic("genes", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("entry.genes.names"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("names", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); paths.put(SRC_NS + "Entry", descs); return paths; } }
package org.broad.igv.feature.tribble; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import org.apache.commons.lang.StringUtils; import org.broad.igv.AbstractHeadlessTest; import org.broad.igv.Globals; import org.broad.igv.feature.BasicFeature; import org.broad.igv.track.Track; import org.broad.igv.track.TrackLoader; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.TestUtils; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertTrue; public class IGVBEDCodecTest extends AbstractHeadlessTest { @Test public void decodeSpeedTest() throws Exception { long benchTime = TestUtils.getBenchmarkTime(); int nTrials = 5000000; BEDStringSupplier supplier = new BEDStringSupplier(nTrials); final IGVBEDCodec codec = new IGVBEDCodec(); Predicate<String> decodePredicate = new Predicate<String>() { @Override public boolean apply(String input) { BasicFeature feat = codec.decode(input); return true; } }; supplier.reset(); String jVersion = System.getProperty(Globals.JAVA_VERSION_STRING); System.out.println("\nIGVBEDCodec.decode. java version " + jVersion); long[] times = TestUtils.timeMethod(supplier, decodePredicate, nTrials); //Calculate average (in nanoseconds) double average = TestUtils.average(times); int maxMultiplier = 200000; if (jVersion.contains("1.7")) { maxMultiplier = 10000; } //we are somewhat forgiving, for the sake of portability. Less than 2 uSec okay, even if it //breaks benchmark assertTrue("Decoding median speed too slow", average < benchTime / maxMultiplier || average < 2000); } public void timeLoadBigFile() throws Exception { //File not in repo final String path = "GSM288345_Nanog.bed"; Supplier<String> supplier = new Supplier<String>() { @Override public String get() { return path; } }; final TrackLoader loader = new TrackLoader(); Predicate<String> loadFile = new Predicate<String>() { @Override public boolean apply(String input) { List<Track> newTrack = loader.load(new ResourceLocator(path), genome); return true; } }; TestUtils.timeMethod(supplier, loadFile, 1); } private class BEDStringSupplier implements Supplier<String> { //final String[] testStrings; private int counter = 0; private final String chr = "chr1"; private final int maxLength = 500; BEDStringSupplier(int nTrials) { // testStrings = new String[nTrials]; // for(int ft=0; ft < nTrials; ft++){ // testStrings[ft] = gen(ft); } private String gen(int start) { String end = "" + (start + (int) Math.random() * maxLength); String[] dat = {chr, "" + start, end, "0", "0", "+"}; return StringUtils.join(dat, '\t'); } @Override public String get() { return gen(counter++); //return testStrings[counter++]; } public void reset() { counter = 0; } } }
package org.flymine.dataconversion; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; 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 com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.model.ModelFactory; import org.intermine.InterMineException; import org.intermine.xml.full.Attribute; import org.intermine.xml.full.Item; import org.intermine.xml.full.Reference; import org.intermine.xml.full.ReferenceList; import org.intermine.xml.full.ItemHelper; import org.intermine.dataconversion.DataTranslator; import org.intermine.dataconversion.FieldNameAndValue; import org.intermine.dataconversion.ItemPrefetchDescriptor; import org.intermine.dataconversion.ItemPrefetchConstraintDynamic; import org.intermine.dataconversion.ItemReader; import org.intermine.dataconversion.ItemWriter; import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl; import org.intermine.dataconversion.ObjectStoreItemReader; import org.intermine.dataconversion.ObjectStoreItemWriter; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.util.XmlUtil; import org.apache.log4j.Logger; /** * DataTranslator specific to uniprot. * * @author Matthew Wakeling */ public class UniprotDataTranslator extends DataTranslator { private static final Logger LOG = Logger.getLogger(UniprotDataTranslator.class); private String databaseId = null; private String drosophilaId = null; private String caenorhabditisId = null; private Map pubMedIdToPublicationId = new HashMap(); private Map geneIdentifierToId = new HashMap(); private int idSequence = 0; private int pubLinkCount = 0; private int drosophilaCount = 0; private int caenorhabditisCount = 0; private static final String SRC_NS = "http://www.flymine.org/model private static final String TGT_NS = "http://www.flymine.org/model/genomic /** * @see DataTranslator */ public UniprotDataTranslator(ItemReader srcItemReader, String tgtNs) { //super(srcItemReader, model, tgtNs); this.tgtNs = tgtNs; this.srcItemReader = srcItemReader; } /** * @see DataTranslator#getItemIterator */ public Iterator getItemIterator() throws ObjectStoreException { Query q = new Query(); q.setDistinct(false); QueryClass qc1 = new QueryClass(org.intermine.model.fulldata.Item.class); q.addFrom(qc1); q.addToSelect(qc1); SimpleConstraint sc1 = new SimpleConstraint(new QueryField(qc1, "className"), ConstraintOp.EQUALS, new QueryValue(SRC_NS + "EntryType")); QueryClass qc2 = new QueryClass(org.intermine.model.fulldata.ReferenceList.class); q.addFrom(qc2); ContainsConstraint cc1 = new ContainsConstraint(new QueryObjectReference(qc2, "item"), ConstraintOp.CONTAINS, qc1); SimpleConstraint sc2 = new SimpleConstraint(new QueryField(qc2, "name"), ConstraintOp.EQUALS, new QueryValue("organisms")); QueryClass qc3 = new QueryClass(org.intermine.model.fulldata.Item.class); q.addFrom(qc3); SimpleConstraint sc3 = new SimpleConstraint(new QueryField(qc2, "refIds"), ConstraintOp.EQUALS, new QueryField(qc3, "identifier")); QueryClass qc4 = new QueryClass(org.intermine.model.fulldata.Reference.class); q.addFrom(qc4); ContainsConstraint cc2 = new ContainsConstraint(new QueryObjectReference(qc4, "item"), ConstraintOp.CONTAINS, qc3); SimpleConstraint sc4 = new SimpleConstraint(new QueryField(qc4, "name"), ConstraintOp.EQUALS, new QueryValue("dbReference")); QueryClass qc5 = new QueryClass(org.intermine.model.fulldata.Item.class); q.addFrom(qc5); SimpleConstraint sc5 = new SimpleConstraint(new QueryField(qc4, "refId"), ConstraintOp.EQUALS, new QueryField(qc5, "identifier")); QueryClass qc6 = new QueryClass(org.intermine.model.fulldata.Attribute.class); q.addFrom(qc6); ContainsConstraint cc3 = new ContainsConstraint(new QueryObjectReference(qc6, "item"), ConstraintOp.CONTAINS, qc5); SimpleConstraint sc6 = new SimpleConstraint(new QueryField(qc6, "name"), ConstraintOp.EQUALS, new QueryValue("id")); ConstraintSet cs1 = new ConstraintSet(ConstraintOp.OR); SimpleConstraint sc7 = new SimpleConstraint(new QueryField(qc6, "value"), ConstraintOp.EQUALS, new QueryValue("7227")); SimpleConstraint sc8 = new SimpleConstraint(new QueryField(qc6, "value"), ConstraintOp.EQUALS, new QueryValue("6239")); cs1.addConstraint(sc7); cs1.addConstraint(sc8); ConstraintSet cs2 = new ConstraintSet(ConstraintOp.AND); cs2.addConstraint(sc1); cs2.addConstraint(cc1); cs2.addConstraint(sc2); cs2.addConstraint(sc3); cs2.addConstraint(cc2); cs2.addConstraint(sc4); cs2.addConstraint(sc5); cs2.addConstraint(cc3); cs2.addConstraint(sc6); cs2.addConstraint(cs1); q.setConstraint(cs2); // TODO: This query will fetch all the Drosophila & Caenorhabditis entries that have only // one organism. There are three that have multiple organisms, but we can add those later. return ((ObjectStoreItemReader) srcItemReader).itemIterator(q); } /** * @see DataTranslator#translateItem */ protected Collection translateItem(Item srcItem) throws ObjectStoreException, InterMineException { // This Item should be an EntryType. if ((SRC_NS + "EntryType").equals(srcItem.getClassName())) { // First things first: find out the taxonid of the organism of this entry. int taxonId = 0; List organisms = getItemsInCollection(srcItem.getCollection("organisms")); Iterator organismIter = organisms.iterator(); while (organismIter.hasNext()) { Item organism = (Item) organismIter.next(); Item dbReference = ItemHelper.convert(srcItemReader.getItemById(organism .getReference("dbReference").getRefId())); String type = getAttributeValue(dbReference, "type"); if ("NCBI Taxonomy".equals(type)) { String taxonString = getAttributeValue(dbReference, "id"); if ("7227".equals(taxonString)) { // Drosophila melanogaster if (taxonId != 0) { throw new IllegalStateException("Attempting to set taxon id to " + taxonString + " when it is already " + taxonId); } taxonId = 7227; } else if ("6239".equals(taxonString)) { // Caenorhabditis elegans if (taxonId != 0) { throw new IllegalStateException("Attempting to set taxon id to " + taxonString + " when it is already " + taxonId); } taxonId = 6239; } } } if (taxonId != 0) { // We have a recognised organism Set retval = new HashSet(); if (databaseId == null) { Item database = new Item(getUniqueIdentifier(), TGT_NS + "Database", ""); database.addAttribute(new Attribute("title", "UniProt")); databaseId = database.getIdentifier(); retval.add(database); } Item protein = new Item(getUniqueIdentifier(), TGT_NS + "Protein", ""); String proteinName = getAttributeValue(srcItem, "name"); protein.addAttribute(new Attribute("identifier", proteinName)); List srcAccessions = getItemsInCollection(srcItem.getCollection("accessions")); if (srcAccessions.isEmpty()) { LOG.info("Entry " + proteinName + " does not have any accessions"); } else { Item srcPrimaryAccession = (Item) srcAccessions.get(0); protein.addAttribute(new Attribute("primaryAccession", getAttributeValue( srcPrimaryAccession, "accession"))); Iterator srcAccIter = srcAccessions.iterator(); while (srcAccIter.hasNext()) { Item srcAccession = (Item) srcAccIter.next(); String srcAccessionString = getAttributeValue(srcAccession, "accession"); Item synonym = new Item(getUniqueIdentifier(), TGT_NS + "Synonym", ""); synonym.addAttribute(new Attribute("value", srcAccessionString)); synonym.addAttribute(new Attribute("type", "accession")); synonym.addReference(new Reference("subject", protein.getIdentifier())); synonym.addReference(new Reference("source", databaseId)); retval.add(synonym); } } List srcComments = getItemsInCollection(srcItem.getCollection("comments")); Iterator srcComIter = srcComments.iterator(); while (srcComIter.hasNext()) { Item srcComment = (Item) srcComIter.next(); String srcCommentType = getAttributeValue(srcComment, "type"); String srcCommentText = getAttributeValue(srcComment, "text"); if ((srcCommentType != null) && (srcCommentText != null)) { Item comment = new Item(getUniqueIdentifier(), TGT_NS + "Comment", ""); comment.addAttribute(new Attribute("type", srcCommentType)); comment.addAttribute(new Attribute("text", srcCommentText)); comment.addReference(new Reference("subject", protein.getIdentifier())); comment.addReference(new Reference("source", databaseId)); retval.add(comment); } } Item srcProtein = ItemHelper.convert(srcItemReader.getItemById(srcItem .getReference("protein").getRefId())); if (srcProtein != null) { List srcProteinNames = getItemsInCollection(srcProtein.getCollection("names")); Iterator srcProtNameIter = srcProteinNames.iterator(); while (srcProtNameIter.hasNext()) { Item srcProteinName = (Item) srcProtNameIter.next(); String srcProteinNameString = getAttributeValue(srcProteinName, "name"); String srcProteinNameEvidence = getAttributeValue(srcProteinName, "evidence"); if (srcProteinNameEvidence != null) { srcProteinNameString += " (Evidence " + srcProteinNameEvidence + ")"; } Item synonym = new Item(getUniqueIdentifier(), TGT_NS + "Synonym", ""); synonym.addAttribute(new Attribute("type", "name")); synonym.addAttribute(new Attribute("value", srcProteinNameString)); synonym.addReference(new Reference("subject", protein.getIdentifier())); synonym.addReference(new Reference("source", databaseId)); retval.add(synonym); } } Reference geneOrganismReference = null; if (taxonId == 7227) { if (drosophilaId == null) { Item drosophila = new Item(getUniqueIdentifier(), TGT_NS + "Organism", ""); drosophila.addAttribute(new Attribute("taxonId", "7227")); retval.add(drosophila); drosophilaId = drosophila.getIdentifier(); } protein.addReference(new Reference("organism", drosophilaId)); geneOrganismReference = new Reference("organism", drosophilaId); drosophilaCount++; if (drosophilaCount % 100 == 0) { LOG.info("Processed " + drosophilaCount + " Drosophila proteins"); } } else if (taxonId == 6239) { if (caenorhabditisId == null) { Item caenorhabditis = new Item(getUniqueIdentifier(), TGT_NS + "Organism", ""); caenorhabditis.addAttribute(new Attribute("taxonId", "6239")); retval.add(caenorhabditis); caenorhabditisId = caenorhabditis.getIdentifier(); } protein.addReference(new Reference("organism", caenorhabditisId)); geneOrganismReference = new Reference("organism", caenorhabditisId); caenorhabditisCount++; if (caenorhabditisCount % 100 == 0) { LOG.info("Processed " + caenorhabditisCount + " Caenorhabditis proteins"); } } List srcReferences = getItemsInCollection(srcItem.getCollection("references")); ReferenceList publications = null; Iterator srcRefIter = srcReferences.iterator(); while (srcRefIter.hasNext()) { Item srcReference = (Item) srcRefIter.next(); Item srcCitation = ItemHelper.convert(srcItemReader.getItemById(srcReference .getReference("citation").getRefId())); List srcDbReferences = getItemsInCollection(srcCitation .getCollection("dbReferences")); Iterator srcDbRefIter = srcDbReferences.iterator(); while (srcDbRefIter.hasNext()) { Item srcDbReference = (Item) srcDbRefIter.next(); String type = getAttributeValue(srcDbReference, "type"); if ("PubMed".equals(type)) { String pubMedString = new String(getAttributeValue(srcDbReference, "id")); String publicationId = (String) pubMedIdToPublicationId .get(pubMedString); pubLinkCount++; if (publicationId == null) { Item publication = new Item(getUniqueIdentifier(), TGT_NS + "Publication", ""); publication.addAttribute(new Attribute("pubMedId", pubMedString)); retval.add(publication); publicationId = publication.getIdentifier(); pubMedIdToPublicationId.put(pubMedString, publicationId); if (pubMedIdToPublicationId.size() % 100 == 0) { LOG.info("Processed " + pubMedIdToPublicationId.size() + " publications, with " + pubLinkCount + " references to publications"); } } if (publications == null) { publications = new ReferenceList("publications", new ArrayList()); protein.addCollection(publications); } publications.addRefId(publicationId); } } } List srcGenes = getItemsInCollection(srcItem.getCollection("genes")); ReferenceList geneCollection = null; Iterator srcGeneIter = srcGenes.iterator(); while (srcGeneIter.hasNext()) { Item srcGene = (Item) srcGeneIter.next(); String geneIdentifier = null; List srcGeneNames = getItemsInCollection(srcGene.getCollection("names")); String primaryGeneName = null; Set geneNames = new HashSet(); { Iterator srcGeneNameIter = srcGeneNames.iterator(); while (srcGeneNameIter.hasNext()) { Item srcGeneName = (Item) srcGeneNameIter.next(); if ("primary".equals(getAttributeValue(srcGeneName, "type"))) { primaryGeneName = new String(getAttributeValue(srcGeneName, "name")); } geneNames.add(new String(getAttributeValue(srcGeneName, "name"))); } if ((primaryGeneName == null) && (!srcGeneNames.isEmpty())) { primaryGeneName = new String(getAttributeValue((Item) srcGeneNames .get(0), "name")); } } if (taxonId == 7227) { // Drosophila - take the gene id from the FlyBase dbReference that has a // property type = "gene designation" value = the primary gene name if (primaryGeneName == null) { throw new InterMineException("primaryGeneName is null for Drosophila" + " gene for protein with name " + proteinName); } List srcDbReferences = getItemsInCollection(srcItem .getCollection("dbReferences"), "type", "FlyBase"); Iterator srcDbRefIter = srcDbReferences.iterator(); while (srcDbRefIter.hasNext()) { Item srcDbReference = (Item) srcDbRefIter.next(); String type = getAttributeValue(srcDbReference, "type"); if ("FlyBase".equals(type)) { if ((srcDbReferences.size() == 1) && (srcGenes.size() == 1)) { geneIdentifier = new String(getAttributeValue(srcDbReference, "id")); } else { List srcProperties = getItemsInCollection(srcDbReference .getCollection("propertys")); Iterator srcPropertyIter = srcProperties.iterator(); while (srcPropertyIter.hasNext()) { Item srcProperty = (Item) srcPropertyIter.next(); String srcPropertyValue = getAttributeValue(srcProperty, "value"); if ("gene designation".equals(getAttributeValue(srcProperty, "type")) && (geneNames.contains(srcPropertyValue) || geneNames.contains(srcPropertyValue .substring(srcPropertyValue .lastIndexOf("\\") + 1)))) { geneIdentifier = new String(getAttributeValue( srcDbReference, "id")); } } } } else { LOG.error("Found a non-FlyBase dbReference when it should have been" + " filtered out"); } } if (geneIdentifier == null) { LOG.warn("Could not find identifier for Drosophila gene with name " + primaryGeneName + " for protein with name " + proteinName); } } else if (taxonId == 6239) { // Caenorhabditis - get the gene id from the ORF name Iterator srcGeneNameIter = srcGeneNames.iterator(); while (srcGeneNameIter.hasNext()) { Item srcGeneName = (Item) srcGeneNameIter.next(); if ("ORF".equals(getAttributeValue(srcGeneName, "type"))) { geneIdentifier = new String(getAttributeValue(srcGeneName, "name")); } } if (geneIdentifier == null) { LOG.warn("Could not find identifier for C. Elegans gene with name " + primaryGeneName + " for protein with name " + proteinName); } } if (geneIdentifier != null) { // We have a gene id. String geneId = (String) geneIdentifierToId.get(geneIdentifier); if (geneId == null) { Item gene = new Item(getUniqueIdentifier(), TGT_NS + "Gene", ""); gene.addAttribute(new Attribute("organismDbId", geneIdentifier)); if (primaryGeneName != null) { gene.addAttribute(new Attribute("identifier", primaryGeneName)); } else { gene.addAttribute(new Attribute("identifier", geneIdentifier)); } gene.addReference(geneOrganismReference); ReferenceList geneSynonyms = new ReferenceList("synonyms", new ArrayList()); String primaryName = null; Iterator srcGeneNameIter = srcGeneNames.iterator(); while (srcGeneNameIter.hasNext()) { Item srcGeneName = (Item) srcGeneNameIter.next(); String type = getAttributeValue(srcGeneName, "type"); String name = getAttributeValue(srcGeneName, "name"); if ("primary".equals(type)) { gene.addAttribute(new Attribute("name", name)); } else { Item synonym = new Item(getUniqueIdentifier(), TGT_NS + "Synonym", ""); synonym.addAttribute(new Attribute("value", name)); synonym.addAttribute(new Attribute("type", type)); synonym.addReference(new Reference("subject", gene.getIdentifier())); synonym.addReference(new Reference("source", databaseId)); retval.add(synonym); } } gene.addCollection(geneSynonyms); geneId = gene.getIdentifier(); geneIdentifierToId.put(geneIdentifier, geneId); retval.add(gene); } if (geneCollection == null) { geneCollection = new ReferenceList("genes", new ArrayList()); protein.addCollection(geneCollection); } geneCollection.addRefId(geneId); } } retval.add(protein); return retval; } } else { LOG.warn("Found non-EntryType Item"); } return Collections.EMPTY_SET; } public List getItemsInCollection(ReferenceList col) throws ObjectStoreException { return getItemsInCollection(col, null, null); } public List getItemsInCollection(ReferenceList col, String attributeName, String attributeValue) throws ObjectStoreException { if ((col == null) || col.getRefIds().isEmpty()) { return Collections.EMPTY_LIST; } StringBuffer refIds = new StringBuffer(); boolean needComma = false; Iterator refIdIter = col.getRefIds().iterator(); while (refIdIter.hasNext()) { if (needComma) { refIds.append(" "); } needComma = true; refIds.append((String) refIdIter.next()); } FieldNameAndValue fnav = new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.IDENTIFIER, refIds.toString(), true); Set description; if (attributeName == null) { description = Collections.singleton(fnav); } else { description = new HashSet(); description.add(fnav); description.add(new FieldNameAndValue(attributeName, attributeValue, false)); } List unconvertedResults = srcItemReader.getItemsByDescription(description); List retval = new ArrayList(); Iterator uncoIter = unconvertedResults.iterator(); while (uncoIter.hasNext()) { org.intermine.model.fulldata.Item item = (org.intermine.model.fulldata.Item) uncoIter .next(); retval.add(ItemHelper.convert(item)); } return retval; } public static String getAttributeValue(Item item, String name) { Attribute attribute = item.getAttribute(name); if (attribute != null) { return attribute.getValue(); } return null; } public String getUniqueIdentifier() { return "0_" + (idSequence++); } /** * Main method * @param args command line arguments * @throws Exception if something goes wrong */ public static void main (String[] args) throws Exception { String srcOsName = args[0]; String tgtOswName = args[1]; String modelName = args[2]; String format = args[3]; String namespace = args[4]; Map paths = new HashMap(); Set descs = new HashSet(); ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("entryType.organisms"); desc.addConstraint(new ItemPrefetchConstraintDynamic("organisms", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor( "entryType.organisms.dbReference"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("dbReference", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); desc = new ItemPrefetchDescriptor("entryType.accessions"); desc.addConstraint(new ItemPrefetchConstraintDynamic("accessions", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descs.add(desc); desc = new ItemPrefetchDescriptor("entryType.comments"); desc.addConstraint(new ItemPrefetchConstraintDynamic("comments", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); descs.add(desc); desc = new ItemPrefetchDescriptor("entryType.protein"); desc.addConstraint(new ItemPrefetchConstraintDynamic("protein", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("entryType.protein.names"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("names", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); desc = new ItemPrefetchDescriptor("entryType.references"); desc.addConstraint(new ItemPrefetchConstraintDynamic("references", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("entryType.references.citation"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("citation", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); ItemPrefetchDescriptor desc3 = new ItemPrefetchDescriptor( "entryType.references.citation.dbReferences"); desc3.addConstraint(new ItemPrefetchConstraintDynamic("dbReferences", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2.addPath(desc3); descs.add(desc); desc = new ItemPrefetchDescriptor("entryType.dbReferences"); desc.addConstraint(new ItemPrefetchConstraintDynamic("dbReferences", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addConstraint(new FieldNameAndValue("type", "FlyBase", false)); desc2 = new ItemPrefetchDescriptor("entryType.dbReferences.propertys"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("propertys", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); desc = new ItemPrefetchDescriptor("entryType.genes"); desc.addConstraint(new ItemPrefetchConstraintDynamic("genes", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc2 = new ItemPrefetchDescriptor("entryType.genes.names"); desc2.addConstraint(new ItemPrefetchConstraintDynamic("names", ObjectStoreItemPathFollowingImpl.IDENTIFIER)); desc.addPath(desc2); descs.add(desc); paths.put(SRC_NS + "EntryType", descs); ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName); ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName); ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt); ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths); //OntModel model = ModelFactory.createOntologyModel(); //model.read(new FileReader(new File(modelName)), null, format); UniprotDataTranslator dt = new UniprotDataTranslator(srcItemReader, namespace); //model = null; dt.translate(tgtItemWriter); tgtItemWriter.close(); } }
package picscout.depend.console; import picscout.depend.dependency.main.Runner; public class Main { public static void main(String[] args) { //Test jar run System.out.println("Going to run calc dependencies"); Runner runner = new Runner(); runner.CalculateDependencies(); } }
package com.foc.vaadin.gui.layouts.validationLayout; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import org.apache.poi.xwpf.usermodel.Borders; import org.apache.poi.xwpf.usermodel.BreakClear; import org.apache.poi.xwpf.usermodel.BreakType; import org.apache.poi.xwpf.usermodel.Document; import org.apache.poi.xwpf.usermodel.LineSpacingRule; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import org.apache.poi.xwpf.usermodel.UnderlinePatterns; import org.apache.poi.xwpf.usermodel.VerticalAlign; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import com.foc.ConfigInfo; import com.foc.Globals; import com.foc.IFocEnvironment; import com.foc.OptionDialog; import com.foc.access.AccessSubject; import com.foc.access.FocDataMap; import com.foc.admin.FocGroup; import com.foc.admin.FocUser; import com.foc.admin.FocUserHistory; import com.foc.admin.FocUserHistoryDesc; import com.foc.admin.FocUserHistoryList; import com.foc.admin.GroupXMLViewDesc; import com.foc.business.notifier.DocMsg; import com.foc.business.notifier.DocMsgDesc; import com.foc.business.notifier.FocPageLink; import com.foc.business.notifier.FocPageLinkDesc; import com.foc.business.photoAlbum.PhotoAlbumAppGroup; import com.foc.business.printing.PrnContext; import com.foc.business.printing.PrnLayoutDesc; import com.foc.business.printing.ReportFactory; import com.foc.business.printing.gui.PrintingAction; import com.foc.business.workflow.implementation.IWorkflowDesc; import com.foc.business.workflow.map.WFMap; import com.foc.business.workflow.map.WFTransactionConfigDesc; import com.foc.dataDictionary.FocDataDictionary; import com.foc.desc.FocConstructor; import com.foc.desc.FocDesc; import com.foc.desc.FocObject; import com.foc.desc.field.FField; import com.foc.link.FocLinkOutRights; import com.foc.list.FocList; import com.foc.modules.link.DocMsg_Form; import com.foc.property.FProperty; import com.foc.shared.dataStore.IFocData; import com.foc.shared.xmlView.XMLViewKey; import com.foc.util.ASCII; import com.foc.util.Utils; import com.foc.vaadin.FocCentralPanel; import com.foc.vaadin.FocWebApplication; import com.foc.vaadin.FocWebVaadinWindow; import com.foc.vaadin.ICentralPanel; import com.foc.vaadin.gui.FVIconFactory; import com.foc.vaadin.gui.FocXMLGuiComponentStatic; import com.foc.vaadin.gui.components.FVCheckBox; import com.foc.vaadin.gui.components.FVLabel; import com.foc.vaadin.gui.components.menuBar.FVMenuBar; import com.foc.vaadin.gui.components.menuBar.FVMenuBarCommand; import com.foc.vaadin.gui.layouts.FVTableWrapperLayout; import com.foc.vaadin.gui.layouts.link.FVLinkLayout; import com.foc.vaadin.gui.mswordGenerator.FocXmlMSWordParser; import com.foc.vaadin.gui.pdfGenerator.FocXmlPDFParser; import com.foc.vaadin.gui.xmlForm.FXML; import com.foc.vaadin.gui.xmlForm.FocXMLAttributes; import com.foc.vaadin.gui.xmlForm.FocXMLLayout; import com.foc.vaadin.gui.xmlForm.IValidationListener; import com.foc.web.gui.INavigationWindow; import com.foc.web.modules.business.PrnLayout_Table; import com.foc.web.modules.photoAlbum.PhotoAlbumWebModule; import com.foc.web.server.xmlViewDictionary.XMLViewDictionary; import com.foc.web.unitTesting.FocUnitRecorder; import com.vaadin.event.MouseEvents; import com.vaadin.event.ShortcutAction.KeyCode; import com.vaadin.event.ShortcutAction.ModifierKey; import com.vaadin.server.BrowserWindowOpener; import com.vaadin.server.Page; import com.vaadin.server.StreamResource.StreamSource; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Component; import com.vaadin.ui.Embedded; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.JavaScript; import com.vaadin.ui.MenuBar; import com.vaadin.ui.MenuBar.MenuItem; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.themes.BaseTheme; @SuppressWarnings("serial") public class FVValidationLayout extends VerticalLayout {//extends HorizontalLayout private FValidationSettings validationSettings = null; private ArrayList<IValidationListener> validationListeners = null; private ICentralPanel centralPanel = null; // private ChatSlider chatSlider = null; private HorizontalLayout mainHorizontalLayout = null; // private FVHorizontalLayout buttonsLayout = null; /* private Button nextContextHelpButton = null; private Button previousContextHelpButton = null; private Button exitContextHelpButton = null; */ private Button sendInternalEmailButton = null; private Button printAndExitButton = null; private Button pdfGeneratorButton = null; private Button attachImageButton = null; private Button fullScreenButton = null; private Button sendEmailButton = null; private Button discardButton = null; private Button deleteButton = null; private Button discardLink = null; private Button applyButton = null; private Button printButton = null; private Button saveButton = null; private Button backButton = null; private Embedded valo_SendInternalEmailEmbedded = null; private Embedded valo_PrintAndExitEmbedded = null; private Embedded valo_PdfGeneratorEmbedded = null; private Embedded valo_MSWordGeneratorEmbedded = null; private Embedded valo_AttachImageEmbedded = null; private Embedded valo_FullScreenEmbedded = null; private Embedded valo_SendEmailEmbedded = null; private Embedded valo_PDFPrintEmbedded = null; private Embedded valo_DeleteEmbedded = null; private Embedded valo_PrintEmbedded = null; private Embedded valo_BackEmbedded = null; private Button valo_DiscardButton = null; private Button valo_ApplyButton = null; private Button valo_SaveButton = null; private FVCheckBox valo_NotCompletedYet = null; private FocXmlPDFParser focXmlPDFParser = null; private FocXmlMSWordParser focXmlMSWordParser = null; private FVHelpButton tipsButton = null; // private FVStatusLayout_ComboBox statusLayout_ComboBox = null; private FVStatusLayout_MenuBar statusLayout_MenuBar = null; private FVStatusLayout statusLayout = null; private FVStageLayout stageLayout = null; // private FVStageLayout_ComboBox stageLayout_ComboBox = null; private FVStageLayout_MenuBar stageLayout_MenuBar = null; private FVViewSelector_MenuBar viewSelector = null; private FVLinkLayout linkLayout = null; private FVLabel titleLabel = null; private INavigationWindow focVaadinMainWindow = null; private FVMenuBar moreMenuBar = null; private boolean askForConfirmationForExit_Forced = false; // private HelpContextComponentFocusable helpContextComponentFocusable = null; private boolean helpOn = false; private boolean goingBackAfterDoneClicked = false; public FVValidationLayout(INavigationWindow focVaadinMainWindow, ICentralPanel centralPanel, FValidationSettings validationSettings, boolean showBackButton) { super(); // addStyleName("noPrint"); this.validationSettings = validationSettings; this.focVaadinMainWindow = focVaadinMainWindow; this.centralPanel = centralPanel; setMargin(false); setSpacing(false); setCaption(null); setWidth("100%"); setHeight("-1px"); mainHorizontalLayout = new HorizontalLayout(); addComponent(mainHorizontalLayout); mainHorizontalLayout.setMargin(false); mainHorizontalLayout.setSpacing(true); mainHorizontalLayout.setCaption(null); mainHorizontalLayout.setWidth("100%"); mainHorizontalLayout.setHeight("-1px"); mainHorizontalLayout.setStyleName("foc-validation"); if(Globals.isValo()){ // We get problems when we apply this style // in trees the scroll bar is hidden so we can't scroll over the tree // addStyleName("floatPosition"); } if(Globals.isValo()){ mainHorizontalLayout.addStyleName("foc-footerLayout"); } mainHorizontalLayout.addStyleName("noPrint"); addStyleName("noPrint"); initButtonsLayout(showBackButton); validationListeners = new ArrayList<IValidationListener>(); addTransactionToRecentVisited(); } public void dispose(){ if(validationListeners != null){ validationListeners.clear(); validationListeners = null; } if(focXmlPDFParser != null){ focXmlPDFParser.dispose(); focXmlPDFParser = null; } if(focXmlMSWordParser != null){ focXmlMSWordParser.dispose(); focXmlMSWordParser = null; } if(stageLayout_MenuBar != null){ stageLayout_MenuBar.dispose(); stageLayout_MenuBar = null; } // dispose_HelpContextComponentFocusable(); // buttonsLayout = null; discardButton = null; applyButton = null; saveButton = null; printButton = null; backButton = null; attachImageButton = null; viewSelector = null; titleLabel = null; focVaadinMainWindow = null; validationSettings = null; mainHorizontalLayout = null; // nextContextHelpButton = null; // exitContextHelpButton = null; // previousContextHelpButton = null; } // public void dispose_HelpContextComponentFocusable(){ // if(helpContextComponentFocusable != null){ // helpContextComponentFocusable.dispose(); // helpContextComponentFocusable = null; public void adjustStyleForInnerLayoutsWithPositionUP() { if(mainHorizontalLayout != null) mainHorizontalLayout.addStyleName("foc-white"); } public void adjustForSignatureSlideShow(){ if(titleLabel != null) mainHorizontalLayout.removeComponent(titleLabel); if(getApplyButton(false) != null){ mainHorizontalLayout.setComponentAlignment(getApplyButton(false), Alignment.BOTTOM_LEFT); } if(getDiscardButton(false) != null){ mainHorizontalLayout.setComponentAlignment(getDiscardButton(false), Alignment.BOTTOM_LEFT); } } public boolean isRTL(){ return ConfigInfo.isGuiRTL(); } public FVLabel addTitle(){ titleLabel = new FVLabel(validationSettings == null || validationSettings.getTitle() == null ? "" : validationSettings.getTitle()); titleLabel.addStyleName("foc-f16"); titleLabel.addStyleName("foc-bold"); titleLabel.addStyleName("foc-text-center"); titleLabel.addStyleName("noPrint"); if(ConfigInfo.isGuiRTL()) { titleLabel.addStyleName("foc-floatNone"); } titleLabel.setWidth("-1px"); titleLabel.setHeight("-1px"); mainHorizontalLayout.addComponent(titleLabel); mainHorizontalLayout.setComponentAlignment(titleLabel, Alignment.MIDDLE_CENTER); mainHorizontalLayout.setExpandRatio(titleLabel, 1f); return titleLabel; } public Button getGoBackButton(boolean createIfNeeded){ if(backButton == null && createIfNeeded){ backButton = new Button(""); if(validationSettings.getDiscardLink() != null && !validationSettings.getDiscardLink().isEmpty()){ backButton.setCaption(validationSettings.getDiscardLink()); }else{ backButton.setIcon(FVIconFactory.getInstance().getFVIcon(FVIconFactory.ICON_CANCEL)); } backButton.setStyleName(BaseTheme.BUTTON_LINK); backButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { goBack(); } }); } return backButton; } public Button getPdfGeneratorButton(boolean createIfNeeded){ if(pdfGeneratorButton == null && createIfNeeded && ConfigInfo.isForDevelopment()){ pdfGeneratorButton = new Button(); pdfGeneratorButton.setStyleName(BaseTheme.BUTTON_LINK); pdfGeneratorButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_ADOBE)); focXmlPDFParser = new FocXmlPDFParser(getCentralPanel(), getFocData()); focXmlMSWordParser = new FocXmlMSWordParser(getCentralPanel(), getFocData()); pdfGeneratorButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { } }); BrowserWindowOpener opener = new BrowserWindowOpener(focXmlMSWordParser.getStreamResource()); opener.extend(pdfGeneratorButton); } return pdfGeneratorButton; } public void poiAddPictureTest(){ try{ XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); int format; String imgFilePath = "C://Users//user//Pictures//forward.png"; format = XWPFDocument.PICTURE_TYPE_PNG; run.setText(imgFilePath); run.addBreak(); run.setText("This is where a picture would be.\r\nAnd here would be another image"); run.addBreak(BreakType.PAGE); FileOutputStream out = new FileOutputStream("C://Users//user//Desktop//images.docx"); byte[] byts = new byte[1000000]; out.write(byts); document.addPictureData(byts, format); document.write(out); out.close(); }catch(Exception e){ } } private void createWordTableRows(){ try{ XWPFDocument document = new XWPFDocument(); XWPFTable tableOne = document.createTable(); XWPFTableRow row = null; for(int i=0; i<10; i++){ row = tableOne.createRow(); row.getCell(0).setText("Row Number: " + i); } FileOutputStream outStream = new FileOutputStream("C://Users//user//Desktop//POI Word Doc Sample Table 1.docx"); document.write(outStream); outStream.close(); }catch(Exception ex){ Globals.logException(ex); } } private void createWordTable(){ try{ XWPFDocument document = new XWPFDocument(); // New 2x2 table XWPFTable tableOne = document.createTable(); XWPFTableRow tableOneRowOne = tableOne.getRow(0); tableOneRowOne.setRepeatHeader(true); tableOneRowOne.getCell(0).setText("Hello"); tableOneRowOne.addNewTableCell().setText("World"); XWPFTableRow tableOneRowTwo = tableOne.createRow(); tableOneRowTwo.getCell(0).setText("This is"); tableOneRowTwo.getCell(1).setText("a table"); for(int i=1; i<50; i++){ tableOneRowTwo = tableOne.createRow(); tableOneRowTwo.getCell(0).setText("row " + i + " tol 0 bla bla very long string"); tableOneRowTwo.getCell(1).setText("row " + i + " col 1"); } //Add a break between the tables document.createParagraph().createRun().addBreak(); // New 3x3 table XWPFTable tableTwo = document.createTable(); XWPFTableRow tableTwoRowOne = tableTwo.getRow(0); tableTwoRowOne.getCell(0).setText("col one, row one"); tableTwoRowOne.addNewTableCell().setText("col two, row one"); tableTwoRowOne.addNewTableCell().setText("col three, row one"); XWPFTableRow tableTwoRowTwo = tableTwo.createRow(); tableTwoRowTwo.getCell(0).setText("col one, row two"); tableTwoRowTwo.getCell(1).setText("col two, row two"); tableTwoRowTwo.getCell(2).setText("col three, row two"); XWPFTableRow tableTwoRowThree = tableTwo.createRow(); tableTwoRowThree.getCell(0).setText("col one, row three"); tableTwoRowThree.getCell(1).setText("col two, row three"); tableTwoRowThree.getCell(2).setText("col three, row three"); FileOutputStream outStream = new FileOutputStream("C://Users//user//Desktop//POI Word Doc Sample Table 1.docx"); document.write(outStream); outStream.close(); }catch(Exception e){ e.printStackTrace(); } } private void createWordDocument(){ try{ XWPFDocument doc = new XWPFDocument(); fillWordDocument(doc); InputStream pic = new FileInputStream("C://Users/user//Desktop//adobe.png"); doc.addPictureData(pic, Document.PICTURE_TYPE_JPEG); FileOutputStream out = new FileOutputStream("C://temp//POIWord_1.docx"); doc.write(out); out.close(); }catch(Exception e){ e.printStackTrace(); } } public static void fillWordDocument(XWPFDocument doc){ try{ XWPFParagraph p1 = doc.createParagraph(); p1.setAlignment(ParagraphAlignment.CENTER); p1.setBorderBottom(Borders.DOUBLE); p1.setBorderTop(Borders.DOUBLE); p1.setBorderRight(Borders.DOUBLE); p1.setBorderLeft(Borders.DOUBLE); p1.setBorderBetween(Borders.SINGLE); p1.setVerticalAlignment(TextAlignment.TOP); XWPFRun r1 = p1.createRun(); r1.setBold(true); r1.setText("The quick brown fox"); r1.setBold(true); r1.setFontFamily("Courier"); r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); r1.setTextPosition(100); XWPFParagraph p2 = doc.createParagraph(); p2.setAlignment(ParagraphAlignment.RIGHT); //BORDERS p2.setBorderBottom(Borders.DOUBLE); p2.setBorderTop(Borders.DOUBLE); p2.setBorderRight(Borders.DOUBLE); p2.setBorderLeft(Borders.DOUBLE); p2.setBorderBetween(Borders.SINGLE); XWPFRun r2 = p2.createRun(); r2.setText("jumped over the lazy dog"); r2.setStrike(true); r2.setFontSize(20); XWPFRun r3 = p2.createRun(); r3.setText("and went away"); r3.setStrike(true); r3.setFontSize(20); r3.setSubscript(VerticalAlign.SUPERSCRIPT); XWPFParagraph p3 = doc.createParagraph(); p3.setWordWrap(true); p3.setPageBreak(true); p3.setAlignment(ParagraphAlignment.BOTH); p3.setSpacingLineRule(LineSpacingRule.EXACT); p3.setIndentationFirstLine(600); XWPFRun r4 = p3.createRun(); r4.setTextPosition(200); r4.setText("To be, or not to be: that is the question: " + "Whether 'tis nobler in the mind to suffer " + "The slings and arrows of outrageous fortune, " + "Or to take arms against a sea of troubles, " + "And by opposing end them? To die: to sleep; "); r4.addBreak(BreakType.PAGE); r4.setText("No more; and by a sleep to say we end " + "The heart-ache and the thousand natural shocks " + "That flesh is heir to, 'tis a consummation " + "Devoutly to be wish'd. To die, to sleep; " + "To sleep: perchance to dream: ay, there's the rub; " + "......."); r4.setItalic(true); //This would imply that this break shall be treated as a simple line break, and break the line after that word: XWPFRun r5 = p3.createRun(); r5.setTextPosition(-10); r5.setText("For in that sleep of death what dreams may come"); r5.addCarriageReturn(); r5.setText("When we have shuffled off this mortal coil," + "Must give us pause: there's the respect" + "That makes calamity of so long life;"); r5.addBreak(); r5.setText("For who would bear the whips and scorns of time," + "The oppressor's wrong, the proud man's contumely,"); r5.addBreak(BreakClear.ALL); r5.setText("The pangs of despised love, the law's delay," + "The insolence of office and the spurns" + "......."); }catch(Exception e){ e.printStackTrace(); } } private FocDataDictionary newFocDataDictionary_ForPrinting(){ FocDataDictionary dictionary = null; if(getCentralPanel() instanceof FocXMLLayout){ FocXMLLayout layout = (FocXMLLayout) getCentralPanel(); FocDataDictionary oldDictionary = layout.getFocDataDictionary(false); if(oldDictionary != null){ dictionary = new FocDataDictionary(); dictionary.copy(oldDictionary); } } return dictionary; } public Button getPrintButton(boolean createIfNeeded){ if(printButton == null && createIfNeeded){ // A button to open the printer-friendly page. printButton = new Button(""); //Do not show tool tip text for this button because it will apear on the printout!!! // printButton.setDescription("Print"); printButton.setStyleName(BaseTheme.BUTTON_LINK); printButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_PRINT)); printButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { printClickListener(); } }); } return printButton; } public void printClickListener(){ if(!Globals.getApp().checkSession()){ INavigationWindow nw = getNavigationWindow(); saveAndRefreshWithoutGoBack(); getCentralPanel().copyGuiToMemory(); FocDataDictionary dictionary = newFocDataDictionary_ForPrinting(); IFocData focDataToPrint = getFocData(); if(getCentralPanel() != null && getCentralPanel() instanceof FocXMLLayout){ FocXMLLayout focXMLLayout = (FocXMLLayout) getCentralPanel(); focDataToPrint = focXMLLayout.getFocDataToPrint() != null ? focXMLLayout.getFocDataToPrint() : getFocData(); } FocWebApplication.getFocWebSession_Static().setPrintingData(dictionary, getCentralPanel().getXMLView().getXmlViewKey(), focDataToPrint, false); refreshPendingSignatureButtonCaption(nw); } } public Button getPrintAndExitButton(boolean createIfNeeded){ if(printAndExitButton == null && createIfNeeded){ printAndExitButton = new Button(""); printAndExitButton.setDescription("Print and Exit"); printAndExitButton.setStyleName(BaseTheme.BUTTON_LINK); printAndExitButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_PRINT_AND_EXIT)); printAndExitButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { printAndExitClickListener(); } }); } return printAndExitButton; } private void printAndExitClickListener(){ if(!Globals.getApp().checkSession()){ getCentralPanel().copyGuiToMemory(); FocDataDictionary dictionary = newFocDataDictionary_ForPrinting(); FocWebApplication.getFocWebSession_Static().setPrintingData(dictionary, getCentralPanel().getXMLView().getXmlViewKey(), getFocData(), true); apply(); } } public void applyBrowserWindowOpenerToPrintButton(AbstractComponent printButton){ BrowserWindowOpener opener = null; if(validationSettings != null && validationSettings.avoidRowBreak()){ opener = new BrowserWindowOpener(PrintUI_Break.class); }else{ opener = new BrowserWindowOpener(PrintUI.class); } opener.setFeatures("height=700,width=900,resizable,titlebar=no"); opener.extend(printButton); } private void navigateToPrintingForm(String printingView){ FVViewSelector_MenuBar viewSelector = getViewSelector(false); viewSelector.setView_WithoutSavingSelection(printingView); } public Button getAttachButton(boolean createIfNeeded){ if(attachImageButton == null && createIfNeeded){ attachImageButton = new Button(); attachImageButton.setDescription("Upload Image"); attachImageButton.setStyleName(BaseTheme.BUTTON_LINK); attachImageButton.setIcon(FVIconFactory.getInstance().getFVIcon(FVIconFactory.ICON_ATTACH)); attachImageButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { attachClickListener(); } }); } return attachImageButton; } private void attachClickListener(){ FocObject focObject = getFocObject(); if(focObject != null){ if(focObject.hasRealReference()){ ICentralPanel centralPanel = PhotoAlbumWebModule.newAttachmentCentralPanel(getFocVaadinMainWindow(), focObject); getFocVaadinMainWindow().changeCentralPanelContent(centralPanel, true); } } } public Button getFullScreenButton(boolean createIfNeeded){ boolean inPopup = true; if(focVaadinMainWindow == null || focVaadinMainWindow instanceof FocWebVaadinWindow){ inPopup = false; } if(fullScreenButton == null && createIfNeeded && !inPopup && !FocWebApplication.getInstanceForThread().isMobile() && ConfigInfo.showFullScreenButton()){ fullScreenButton = new Button(); fullScreenButton.setDescription("Full screen"); fullScreenButton.setStyleName(BaseTheme.BUTTON_LINK); refreshFullScreenIcon(); fullScreenButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { fullScreenButtonClickListener(); } }); } return fullScreenButton; } private void fullScreenButtonClickListener(){ INavigationWindow comp = getNavigationWindow();//findAncestor(FocWebVaadinWindow.class); if(comp instanceof FocWebVaadinWindow){ int format = ((FocWebVaadinWindow) comp).getFullScreenMode(); if(format == FocWebVaadinWindow.FORMAT_FULL_SCREEN){ ((FocWebVaadinWindow) comp).setFullScreenMode(FocWebVaadinWindow.FORMAT_PORTRAIT); FocUser user = FocWebApplication.getFocUser(); if(user != null) user.saveFullScreenSettings(FocUserHistory.MODE_WINDOWED); }else if(format == FocWebVaadinWindow.FORMAT_PORTRAIT){ ((FocWebVaadinWindow) comp).setFullScreenMode(FocWebVaadinWindow.FORMAT_FULL_SCREEN); FocUser user = FocWebApplication.getFocUser(); if(user != null) user.saveFullScreenSettings(FocUserHistory.MODE_FULLSCREEN); } refreshFullScreenIcon(); } } public void refreshFullScreenIcon(){ if(getFocVaadinMainWindow() != null && getFocVaadinMainWindow() instanceof FocWebVaadinWindow){ int format = ((FocWebVaadinWindow) getFocVaadinMainWindow()).getFullScreenMode(); if(format == FocWebVaadinWindow.FORMAT_FULL_SCREEN){ if(Globals.isValo()){ if(valo_GetFullScreenEmbedded(false) != null){ valo_GetFullScreenEmbedded(false).setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_SMALL_SCREEN)); } }else{ if(getFullScreenButton(false) != null){ getFullScreenButton(false).setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_SMALL_SCREEN)); } } }else if(format == FocWebVaadinWindow.FORMAT_PORTRAIT){ if(Globals.isValo()){ if(valo_GetFullScreenEmbedded(false) != null){ valo_GetFullScreenEmbedded(false).setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_FULL_SCREEN)); } }else{ if(getFullScreenButton(false) != null){ getFullScreenButton(false).setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_FULL_SCREEN)); } } } } } public Button getApplyButton(boolean createIfNeeded){ if(applyButton == null && createIfNeeded){ applyButton = new Button(""); applyButton.setStyleName(BaseTheme.BUTTON_LINK); applyButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_APPLY)); applyButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { applyButtonClickListener(); } }); } return applyButton; } public void applyButtonClickListener(){ INavigationWindow nw = getNavigationWindow(); Window parentWindowIfDialog = findAncestor(Window.class); if( FocWebApplication.getInstanceForThread() == null || !FocWebApplication.getInstanceForThread().hasModalWindowOverIt(parentWindowIfDialog)){ apply(); refreshPendingSignatureButtonCaption(nw); } } public Button getSaveButton(boolean createIfNeeded){ if(saveButton == null && createIfNeeded){ if(Globals.isValo()){ saveButton = new Button(BaseTheme.BUTTON_LINK); }else{ saveButton = new Button(); saveButton.setStyleName(BaseTheme.BUTTON_LINK); saveButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_SAVE)); } saveButton = new Button(""); // saveButton.setDescription("Save changes and stay in this form"); saveButton.setStyleName(BaseTheme.BUTTON_LINK); saveButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_SAVE)); saveButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { saveButtonClickListener(); } }); } return saveButton; } private void saveButtonClickListener(){ if(!Globals.getApp().checkSession()){ INavigationWindow nw = getNavigationWindow(); Window parentWindowIfDialog = findAncestor(Window.class); if( FocWebApplication.getInstanceForThread() == null || !FocWebApplication.getInstanceForThread().hasModalWindowOverIt(parentWindowIfDialog)){ saveAndRefreshWithoutGoBack(); refreshPendingSignatureButtonCaption(nw); } } } public boolean saveAndRefreshWithoutGoBack(){ boolean error = commit(); //This refresh is important for example in WBS BKDN_TREE view. //BEcause all new created nodes Would appear as small whilte lines after this save if we do not have this refresh line. //This is due to the fact that ref of new BKDN is changing after the save and thus without this refresh the ids of the lines //are not found and the properties are not found if(getCentralPanel() != null && getCentralPanel() instanceof FocXMLLayout){ FocXMLLayout centralPanel = (FocXMLLayout) getCentralPanel(); centralPanel.refresh(); } return error; } public void addTransactionToRecentVisited(){ FocObject focObject = getFocObject(); if(focObject != null){ FocUserHistoryList historyList = (FocUserHistoryList) FocUserHistoryDesc.getInstance().getFocList(); if(historyList != null){ historyList.addRecentTransaction(focObject); } } } private boolean isObjectLocked(){ return isObjectLocked(getFocObject()); } public boolean isObjectLocked(FocObject focObject){ boolean locked = false; if(focObject != null){ locked = focObject.focObject_IsLocked(); } return locked; // boolean isFocList = getFocData() instanceof FocList; // if(getFocData() instanceof FocDataMap){ // FocDataMap focDataMap = (FocDataMap) getFocData(); // isFocList = focDataMap.getMainFocData() instanceof FocList; // isFocList = !isFocList && focDataMap.getMainFocData() instanceof FTree; // boolean allowModification = isFocList && focObject == null; // if(!allowModification){ // allowModification = focObject.workflow_IsAllowDeletion(); // return allowModification; } // public boolean isAllowObjectModification(){ // FocObject focObject = getFocObject(); // boolean allowModification = (focObject != null && focObject.focObject_AllowModification()) // || !(getFocData() instanceof FocObject);//If we are in a BkdnTree or Table... We should not return not allowed! // return allowModification; public boolean commit(){ return commit(true, true); } public boolean commit(boolean check, boolean commit){ boolean error = false; try{ if(!isObjectLocked()){ addTransactionToRecentVisited(); ArrayList<IValidationListener> cloneValidationListeners = new ArrayList<IValidationListener>(); if(validationListeners != null){ for(int i=0; i<validationListeners.size(); i++){ cloneValidationListeners.add(validationListeners.get(i)); } } if(check){ for(int i=0; i<cloneValidationListeners.size(); i++){ error = error || cloneValidationListeners.get(i).validationCheckData(FVValidationLayout.this); } } if(commit){ for(int i=0; i<cloneValidationListeners.size(); i++){ error = error || cloneValidationListeners.get(i).validationCommit(FVValidationLayout.this); } for(int i=0; i<cloneValidationListeners.size(); i++){ cloneValidationListeners.get(i).validationAfter(FVValidationLayout.this, !error); } } cloneValidationListeners.clear(); cloneValidationListeners = null; }else{ error = true; Globals.showNotification("Modifications are not allowed.", "", IFocEnvironment.TYPE_WARNING_MESSAGE); } }catch (Exception e){ Globals.logException(e); if(ConfigInfo.isPopupExceptionDialog()){ Globals.showNotification("Could not save data.", e.getMessage(), IFocEnvironment.TYPE_ERROR_MESSAGE); }else{ Globals.logString("ERROR : Could not save data." + e.getMessage()); } error = false; // Ingnored, we'll let the Form handle the errors } return error; } private INavigationWindow getNavigationWindow(){ ICentralPanel centralPanel = getCentralPanel(); INavigationWindow iNavigationWindow = null; if(centralPanel instanceof FocXMLLayout){ iNavigationWindow = ((FocXMLLayout)centralPanel).getMainWindow(); } return iNavigationWindow; } public void refreshPendingSignatureButtonCaption(INavigationWindow iNavigationWindow){ if(iNavigationWindow == null){ iNavigationWindow = getNavigationWindow(); } if(iNavigationWindow instanceof FocWebVaadinWindow){ FocWebVaadinWindow focWebVaadinWindow = (FocWebVaadinWindow)iNavigationWindow; focWebVaadinWindow.resetPendingSignatureButtonCaption(null); } } private Button newButton(String iconName){ Button button = new Button(""); if(validationSettings.getDiscardLink() != null && !validationSettings.getDiscardLink().isEmpty()){ button.setCaption(validationSettings.getDiscardLink()); }else{ button.setIcon(FVIconFactory.getInstance().getFVIcon_Big(iconName)); } if(!Globals.isValo()) button.setStyleName(BaseTheme.BUTTON_LINK); return button; } public Button getDiscardButton(boolean createIfNeeded){ if(discardButton == null && createIfNeeded){ discardButton = new Button(""); if(validationSettings.getDiscardLink() != null && !validationSettings.getDiscardLink().isEmpty()){ discardButton.setCaption(validationSettings.getDiscardLink()); }else{ discardButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_CANCEL)); if(Globals.isValo()){ discardButton.addStyleName("noFocusHighlight"); discardButton.setWidth("32px"); discardButton.setHeight("32px"); } } discardButton.setStyleName(BaseTheme.BUTTON_LINK); discardButton.addStyleName("noPrint"); discardButton.addClickListener(new Button.ClickListener() { public void buttonClick(ClickEvent event) { discardButtonClickListener(); } }); } return discardButton; } private void discardButtonClickListener(){ INavigationWindow nw = getNavigationWindow(); cancel(); refreshPendingSignatureButtonCaption(nw); } private Button getInternalEmailButton(boolean createIfNeeded){ if(sendInternalEmailButton == null && createIfNeeded){ sendInternalEmailButton = new Button(""); sendInternalEmailButton.setDescription("Send Internal Email"); sendInternalEmailButton.setStyleName(BaseTheme.BUTTON_LINK); sendInternalEmailButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_EMAIL)); sendInternalEmailButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { sendInternalEmailClickListener(); } }); } return sendInternalEmailButton; } private void sendInternalEmailClickListener(){ if(!Globals.getApp().checkSession()){ FocConstructor constructor = new FocConstructor(DocMsgDesc.getInstance(), null); DocMsg docMsg = (DocMsg) constructor.newItem(); XMLViewKey xmlViewKey = new XMLViewKey(DocMsgDesc.getInstance().getStorageName(), XMLViewKey.TYPE_FORM); DocMsg_Form docMsg_Form = (DocMsg_Form) XMLViewDictionary.getInstance().newCentralPanel_NoParsing(getFocVaadinMainWindow(), xmlViewKey, docMsg); docMsg_Form.setPreviousXmlView(getCentralPanel().getXMLView()); docMsg_Form.setPreviousFocData(getFocObject()); docMsg_Form.parseXMLAndBuildGui(); getFocVaadinMainWindow().changeCentralPanelContent(docMsg_Form, true); } } public Button getEmailButton(boolean createIfNeeded){ if(sendEmailButton == null && createIfNeeded){ sendEmailButton = new Button(""); sendEmailButton.setDescription("Send Email"); sendEmailButton.setStyleName(BaseTheme.BUTTON_LINK); sendEmailButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_EMAIL)); sendEmailButton.addStyleName("noPrint"); sendEmailButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { emailClickListener(); } }); } return sendEmailButton; } private void emailClickListener(){ if(!Globals.getApp().checkSession()){ FocList focList = FocPageLinkDesc.getList(FocList.LOAD_IF_NEEDED); FocPageLink focPageLink = (FocPageLink) focList.newEmptyItem(); String randomKeyStringForURL = getUrlKey(focList); FocObject focObj = (getFocObject() != null && getFocObject() instanceof FocObject) ? (FocObject) getFocObject() : null; XMLViewKey xmlViewKey = getCentralPanel() != null ? getCentralPanel().getXMLView().getXmlViewKey() : null; String serialisation = getCentralPanel().getLinkSerialisation(); focPageLink.fill(focObj, xmlViewKey, serialisation, randomKeyStringForURL); focPageLink.validate(true); String javaScript = "var win = window.open('mailto:?body=Hello,%20%0d%0a%20%0d%0aClick on this link or copy it in you internet browser to open the document:%20%0d%0a"+Page.getCurrent().getLocation()+randomKeyStringForURL+"%20%0d%0a%20%0d%0aRegards,', '_blank'); win.close();"; Globals.logString("FVValidationLayout, Line: 897, mail line: " + Page.getCurrent().getLocation()+randomKeyStringForURL); JavaScript.getCurrent().execute(javaScript); } } public String getUrlKey(FocList list){ String randomKeyStringForURL = ASCII.generateRandomString(50).trim(); for(int i=0;i<list.size();i++){ FocPageLink focPageLink = (FocPageLink) list.getFocObject(i); if(focPageLink !=null){ String key = focPageLink.getKey().trim(); if(key.equals(randomKeyStringForURL)){ randomKeyStringForURL = ASCII.generateRandomString(50); i=0; } } } return randomKeyStringForURL; } public FVViewSelector_MenuBar getViewSelector(boolean createIfNeeded){ if(viewSelector == null && createIfNeeded){ viewSelector = new FVViewSelector_MenuBar(centralPanel); } return viewSelector; } public FVLinkLayout getLinkLayout(boolean createIfNeeded){ FocGroup group = null; FocLinkOutRights rights = null; if( Globals.getApp().getUser_ForThisSession() != null && Globals.getApp().getUser_ForThisSession().getGroup() != null){ group = Globals.getApp().getUser_ForThisSession().getGroup(); rights = Globals.getApp().getUser_ForThisSession().getGroup().getLinkOutRights(); } //The link layout button only shows up if the user has the right to post. if(linkLayout == null && createIfNeeded && rights != null){ FocDesc thisDesc = null; if(getFocData() instanceof FocObject){ FocObject obj = (FocObject) getFocData(); thisDesc = obj.getThisFocDesc(); } if(rights.hasRightsForTableDesc(thisDesc)){ linkLayout = new FVLinkLayout(null); if(getFocData() != null){ linkLayout.setFocData(getFocData()); } } } return linkLayout; } public void apply(){ if(!Globals.getApp().checkSession()){ FocCentralPanel focCentralPanel = ((AbstractComponent)getCentralPanel()).findAncestor(FocCentralPanel.class); setGoingBackAfterDoneClicked(true); if(!commit() && getCentralPanel() != null){ //2017-06-29 //This part is useful in the following case only: //1- From a table we open the Form as Popup //2- We edit this existing Row and we Apply. //In this case the refreshGuiForContainer is not called and thus //without these lines we will not see the impact of the changes on the //initial table if(getCentralPanel() instanceof FocXMLLayout){ FocXMLLayout layout = (FocXMLLayout) getCentralPanel(); if( layout.getTableTreeThatOpenedThisForm() != null && layout.getTableTreeThatOpenedThisForm().getFocDataWrapper() != null){ layout.getTableTreeThatOpenedThisForm().getFocDataWrapper().refreshGuiForContainerChanges(); } } getCentralPanel().goBack(focCentralPanel); } } } public void cancel(){ if(!Globals.getApp().checkSession()){ if(isAskForConfirmationForExit() && !isObjectLocked()){ confirmBeforeExit(); }else{ cancel_ExecutionWithoutPrompt(); } } } public void cancel_ExecutionWithoutPrompt(){ if(validationListeners != null){ ArrayList<IValidationListener> cloneValidationListeners = new ArrayList<IValidationListener>(); for(int i=0; i<validationListeners.size(); i++){ cloneValidationListeners.add(validationListeners.get(i)); } for(int i=0; i<cloneValidationListeners.size(); i++){ cloneValidationListeners.get(i).validationDiscard(FVValidationLayout.this); } for(int i=0; i<cloneValidationListeners.size(); i++){ cloneValidationListeners.get(i).validationAfter(FVValidationLayout.this, false); } cloneValidationListeners.clear(); cloneValidationListeners = null; } goBack(); } public boolean isWithStatus(){ return validationSettings == null || validationSettings.isWithStatus(); } public FVStatusLayout_MenuBar getStatusLayout(boolean createIfNeeded){ if( statusLayout_MenuBar == null && createIfNeeded && isWithStatus() && Globals.getApp() != null && Globals.getApp().getUser_ForThisSession() != null && !Globals.getApp().getUser_ForThisSession().isGuest()){ if(getCentralPanel() != null && getCentralPanel() instanceof FocXMLLayout){ FocXMLLayout xmlLayout = (FocXMLLayout) getCentralPanel(); FocObject focObject = xmlLayout.getFocObject(); if(focObject != null && focObject.status_hasStatus() /*&& !((FocObject)getCentralPanel().getFocData()).isCreated()*/){ statusLayout_MenuBar = new FVStatusLayout_MenuBar(xmlLayout, focObject); if(statusLayout_MenuBar.getRootMenuItem() != null && statusLayout_MenuBar.getRootMenuItem().getSize() > 0){//If the status bar is empty then do not show it mainHorizontalLayout.addComponent(statusLayout_MenuBar); mainHorizontalLayout.setComponentAlignment(statusLayout_MenuBar, Alignment.MIDDLE_LEFT); } } } } return statusLayout_MenuBar; } public FVStageLayout_MenuBar getStageLayout(boolean createIfNeeded){ if(stageLayout_MenuBar == null && createIfNeeded && isWithStatus() && Globals.getApp() != null && Globals.getApp().getUser_ForThisSession() != null && !Globals.getApp().getUser_ForThisSession().isGuest()){ ICentralPanel centralPanel = getCentralPanel(); if(centralPanel != null && centralPanel instanceof FocXMLLayout){ FocXMLLayout xmlLayout = (FocXMLLayout) centralPanel; FocObject focObject = xmlLayout.getFocObject(); if(focObject != null){ if(focObject.workflow_IsWorkflowSubject()){ FocDesc focDesc = focObject.getThisFocDesc(); if(focDesc != null && focDesc instanceof IWorkflowDesc){ IWorkflowDesc iWorkflowDesc = (IWorkflowDesc) focDesc; WFMap map = WFTransactionConfigDesc.getMap_ForTransaction(iWorkflowDesc.iWorkflow_getDBTitle()); if(map != null){ stageLayout_MenuBar = new FVStageLayout_MenuBar(xmlLayout, focObject); mainHorizontalLayout.addComponent(stageLayout_MenuBar); mainHorizontalLayout.setComponentAlignment(stageLayout_MenuBar, Alignment.MIDDLE_LEFT); } } } } } } return stageLayout_MenuBar; } private void initButtonsLayout(boolean showBackButton) { if(validationSettings != null){ if (validationSettings.isWithPrint() && !FocWebApplication.getInstanceForThread().isMobile()) { if(Globals.isValo()){ mainHorizontalLayout.addComponent(valo_GetPrintEmbedded(true)); PrintingAction printingAction = newPrintingAction(); if(printingAction != null){ printingAction.dispose(); mainHorizontalLayout.addComponent(valo_GetPDFPrintEmbedded(true)); } applyBrowserWindowOpenerToPrintButton(valo_GetPrintEmbedded(false)); mainHorizontalLayout.setComponentAlignment(valo_GetPrintEmbedded(false), Alignment.BOTTOM_LEFT); }else{ mainHorizontalLayout.addComponent(getPrintButton(true)); applyBrowserWindowOpenerToPrintButton(getPrintButton(false)); mainHorizontalLayout.setComponentAlignment(getPrintButton(false), Alignment.BOTTOM_LEFT); } if(getFocData() != null && getFocData() instanceof FocObject && validationSettings.isWithPrintAndExit()){ if(Globals.isValo()){ mainHorizontalLayout.addComponent(valo_GetPrintEmbedded(true)); applyBrowserWindowOpenerToPrintButton(valo_GetPrintEmbedded(false)); mainHorizontalLayout.setComponentAlignment(valo_GetPrintEmbedded(false), Alignment.BOTTOM_LEFT); }else{ mainHorizontalLayout.addComponent(getPrintAndExitButton(true)); applyBrowserWindowOpenerToPrintButton(getPrintAndExitButton(false)); mainHorizontalLayout.setComponentAlignment(getPrintAndExitButton(false), Alignment.BOTTOM_LEFT); } } } if (validationSettings.hasPDFGenerator()) { if(Globals.isValo()){ if(valo_GetPdfGeneratorEmbedded(true) != null){ mainHorizontalLayout.addComponent(valo_GetPdfGeneratorEmbedded(false)); mainHorizontalLayout.setComponentAlignment(valo_GetPdfGeneratorEmbedded(false), Alignment.BOTTOM_LEFT); } }else{ if(getPdfGeneratorButton(true) != null){ mainHorizontalLayout.addComponent(getPdfGeneratorButton(true)); mainHorizontalLayout.setComponentAlignment(getPdfGeneratorButton(true), Alignment.BOTTOM_LEFT); } } } if (validationSettings.hasMSWordGenerator()) { if(valo_GetMSWordGeneratorEmbedded(true) != null){ mainHorizontalLayout.addComponent(valo_GetMSWordGeneratorEmbedded(false)); mainHorizontalLayout.setComponentAlignment(valo_GetMSWordGeneratorEmbedded(false), Alignment.BOTTOM_LEFT); } } if (validationSettings.isWithAttach() && isAttachementApplicable()) { if(Globals.isValo()){ mainHorizontalLayout.addComponent(valo_GetAttachEmbedded(true)); mainHorizontalLayout.setComponentAlignment(valo_GetAttachEmbedded(false), Alignment.BOTTOM_LEFT); }else{ mainHorizontalLayout.addComponent(getAttachButton(true)); mainHorizontalLayout.setComponentAlignment(getAttachButton(false), Alignment.BOTTOM_LEFT); } } if (validationSettings.isWithEmail() && !FocWebApplication.getInstanceForThread().isMobile()){ if(Globals.isValo()){ mainHorizontalLayout.addComponent(valo_GetEmailEmbedded(true)); mainHorizontalLayout.setComponentAlignment(valo_GetEmailEmbedded(false), Alignment.BOTTOM_LEFT); }else{ mainHorizontalLayout.addComponent(getEmailButton(true)); mainHorizontalLayout.setComponentAlignment(getEmailButton(false), Alignment.BOTTOM_LEFT); } } //DO NOT DELETE THIS //UNDER DEVELOPMENT /* if (validationSettings.isWithInternalEmail() && !FocWebApplication.getInstanceForThread().isMobile()){ addComponent(getInternalEmailButton(true)); setComponentAlignment(getInternalEmailButton(false), Alignment.BOTTOM_LEFT); } */ } if(Globals.isValo()){ Embedded embedded = valo_GetFullScreenEmbedded(true); if(embedded != null){ mainHorizontalLayout.addComponent(embedded); mainHorizontalLayout.setComponentAlignment(embedded, Alignment.BOTTOM_LEFT); } }else{ Button fullScreenButton = getFullScreenButton(true); if(fullScreenButton != null){ mainHorizontalLayout.addComponent(fullScreenButton); mainHorizontalLayout.setComponentAlignment(fullScreenButton, Alignment.BOTTOM_LEFT); } } Component lastAdded = null; if (validationSettings.isWithViewSelector() && !FocWebApplication.getInstanceForThread().isMobile() && Globals.getApp() != null && Globals.getApp().getUser_ForThisSession() != null && Globals.getApp().getUser_ForThisSession().getGroup() != null && Globals.getApp().getUser_ForThisSession().getGroup().getViewsRight() < GroupXMLViewDesc.ALLOW_NOTHING){ mainHorizontalLayout.addComponent(getViewSelector(true)); lastAdded = getViewSelector(false); mainHorizontalLayout.setComponentAlignment(getViewSelector(false), Alignment.MIDDLE_LEFT); } if(getStatusLayout(true) != null){ lastAdded = (Component) getStatusLayout(false); } if(getStageLayout(true) != null){ FocDesc focDesc = getFocObject().getThisFocDesc(); if(focDesc instanceof IWorkflowDesc){ IWorkflowDesc iWorkflowDesc = (IWorkflowDesc) focDesc; WFMap map = WFTransactionConfigDesc.getMap_ForTransaction(iWorkflowDesc.iWorkflow_getDBTitle()); if(map != null){ lastAdded = (Component) getStageLayout(false); } } } IValidationLayoutMoreMenuFiller filler = FVValidationMore.getInstance().getIValidationLayoutMoreMenuFiller(); if(filler != null && (FocWebApplication.getFocUser() == null || !FocWebApplication.getFocUser().isGuest())){ filler.addMenuItems(this); centralPanel.addMoreMenuItems(this); } MenuBar menuBar = getMenubar(false); if(menuBar != null && !FocWebApplication.getInstanceForThread().isMobile()){ mainHorizontalLayout.addComponent(menuBar); mainHorizontalLayout.setComponentAlignment(menuBar, Alignment.MIDDLE_LEFT); lastAdded = menuBar; } /* if( getFocObject() != null && getFocObject().workflow_IsWorkflowSubject() && FChatModule.userHasChat() && getCentralPanel() != null && getCentralPanel() instanceof FocXMLLayout && getCentralPanel().getMainWindow() != null) { chatSlider = new FChatSlider((FocXMLLayout)getCentralPanel()); chatSlider.build(FVValidationLayout.this); } */ if(getLinkLayout(true) != null){ mainHorizontalLayout.addComponent(getLinkLayout(false)); mainHorizontalLayout.setComponentAlignment(getLinkLayout(false), Alignment.BOTTOM_LEFT); } // addHelpButtons(); addTitle(); addApplyDiscardButtons(showBackButton); } /* private void addHelpButtons(){ Button button_PreviousContextHelp = getPreviousContextHelpButton(true); addComponent(button_PreviousContextHelp); setComponentAlignment(button_PreviousContextHelp, Alignment.MIDDLE_CENTER); Button button_ExitContextHelp = getExitContextHelpButton(true); addComponent(button_ExitContextHelp); setComponentAlignment(button_ExitContextHelp, Alignment.MIDDLE_CENTER); setExpandRatio(button_ExitContextHelp, 1f); Button button_NextContextHelp = getNextContextHelpButton(true); addComponent(button_NextContextHelp); setComponentAlignment(button_NextContextHelp, Alignment.MIDDLE_CENTER); } public void toggleContextHelpButtonsVisibility(boolean showContextHelp){ helpOn = !helpOn; dispose_HelpContextComponentFocusable(); if(helpOn){ addStyleName("foc-validationHelpOn"); }else{ removeStyleName("foc-validationHelpOn"); } for(int i=0; i<getComponentCount(); i++){ getComponent(i).setVisible(!getComponent(i).isVisible()); } getPreviousContextHelpButton(false).setVisible(getPreviousContextHelpButton(false).isVisible()); getNextContextHelpButton(false).setVisible(getNextContextHelpButton(false).isVisible()); getExitContextHelpButton(false).setVisible(getExitContextHelpButton(false).isVisible()); if(helpOn && showContextHelp){ getHelpContextComponentFocusable(true).showHelpAtIndex(0); } } private Button getPreviousContextHelpButton(boolean createIfNeeded){ if(previousContextHelpButton == null && createIfNeeded){ previousContextHelpButton = new Button("< Previous Help Tip", new ClickListener() { @Override public void buttonClick(ClickEvent event) { getHelpContextComponentFocusable(true).onButtonClickListener(false); } }); previousContextHelpButton.setDescription("Previous Field Tip"); previousContextHelpButton.setVisible(false); } return previousContextHelpButton; } private Button getNextContextHelpButton(boolean createIfNeeded){ if(nextContextHelpButton == null && createIfNeeded){ nextContextHelpButton = new Button("Next Help Tip>", new ClickListener() { @Override public void buttonClick(ClickEvent event) { getHelpContextComponentFocusable(true).onButtonClickListener(true); } }); nextContextHelpButton.setDescription("Next Field Tip"); nextContextHelpButton.setVisible(false); } return nextContextHelpButton; } private Button getExitContextHelpButton(boolean createIfNeeded){ if(exitContextHelpButton == null && createIfNeeded){ exitContextHelpButton = new Button("Exit Help Tip", new ClickListener() { @Override public void buttonClick(ClickEvent event) { FocXMLLayout focXMLLayout = (FocXMLLayout) getCentralPanel(); if(focXMLLayout != null && focXMLLayout.getMainWindow() != null && focXMLLayout.getMainWindow() instanceof FocWebVaadinWindow){ FocWebVaadinWindow focWebVaadinWindow = (FocWebVaadinWindow) focXMLLayout.getMainWindow(); if(focWebVaadinWindow.getHelpButton(false) != null){ focWebVaadinWindow.getHelpButton(false).click(); } } } }); exitContextHelpButton.setDescription("Exit Help Tip"); exitContextHelpButton.setVisible(false); } return exitContextHelpButton; } */ public void addApplyDiscardButtons(boolean showBackButton){ boolean showValidationAndSave = validationSettings != null && validationSettings.isWithApply(); boolean showSave = validationSettings != null && validationSettings.isWithSave(); boolean showDiscard = validationSettings != null && validationSettings.isWithDiscard(); boolean showGoBack = validationSettings == null && showBackButton; ICentralPanel centralPanel = getCentralPanel(); if(centralPanel instanceof FocXMLLayout){ FocXMLLayout layout = (FocXMLLayout) centralPanel; if(Globals.isValo()){ Component comp = valo_GetNotCompletedYet(true); if(comp != null){ mainHorizontalLayout.addComponent(comp); mainHorizontalLayout.setComponentAlignment(comp, Alignment.MIDDLE_RIGHT); } } if( layout.getTableTreeThatOpenedThisForm() != null && layout.getTableTreeThatOpenedThisForm().getTableTreeDelegate() != null && layout.getTableTreeThatOpenedThisForm().getTableTreeDelegate().isDeleteEnabled() && getFocObject() != null){ if(Globals.isValo()){ Embedded deleteButtton = valo_GetDeleteEmbedded(true); if(deleteButtton != null){ mainHorizontalLayout.addComponent(deleteButtton); mainHorizontalLayout.setComponentAlignment(deleteButtton, Alignment.BOTTOM_LEFT); } }else{ Button deleteButtton = getDeleteButton(true); if(deleteButtton != null){ mainHorizontalLayout.addComponentAsFirst(deleteButtton); mainHorizontalLayout.setComponentAlignment(deleteButtton, Alignment.BOTTOM_LEFT); } } } } Component discardOrGoBackButton = null; if(showDiscard){ if(Globals.isValo()){ discardOrGoBackButton = valo_GetDiscardButton(true); }else{ discardOrGoBackButton = getDiscardButton(true); } } else if(showGoBack){ if(Globals.isValo()){ discardOrGoBackButton = valo_GetGoBackEmbedded(true); }else{ discardOrGoBackButton = getGoBackButton(true); } } if(discardOrGoBackButton != null){ mainHorizontalLayout.addComponent(discardOrGoBackButton); if(Globals.isValo()){ mainHorizontalLayout.setComponentAlignment(discardOrGoBackButton, Alignment.MIDDLE_RIGHT); }else{ mainHorizontalLayout.setComponentAlignment(discardOrGoBackButton, Alignment.BOTTOM_RIGHT); } if(titleLabel == null){ } } if (showValidationAndSave) { if(showSave){ if(Globals.isValo()){ mainHorizontalLayout.addComponent(valo_GetSaveButton(true)); mainHorizontalLayout.setComponentAlignment(valo_GetSaveButton(false), Alignment.MIDDLE_LEFT); }else{ mainHorizontalLayout.addComponent(getSaveButton(true)); mainHorizontalLayout.setComponentAlignment(getSaveButton(false), Alignment.BOTTOM_LEFT); } } if(Globals.isValo()){ mainHorizontalLayout.addComponent(valo_GetApplyButton(true)); mainHorizontalLayout.setComponentAlignment(valo_GetApplyButton(false), Alignment.MIDDLE_LEFT); }else{ mainHorizontalLayout.addComponent(getApplyButton(true)); mainHorizontalLayout.setComponentAlignment(getApplyButton(false), Alignment.BOTTOM_LEFT); } } } public void hideApplyButtons(boolean hide){ Button button = valo_GetSaveButton(false); if(button != null) button.setVisible(!hide); button = valo_GetApplyButton(false); if(button != null) button.setVisible(!hide); } public FocObject getFocObject(){ FocObject focObject = null; IFocData focData = getFocData(); if(focData instanceof FocObject){ focObject = (FocObject) focData; }else if(focData instanceof FocDataMap){ FocDataMap map = ((FocDataMap) focData); focData = map.getMainFocData(); if(focData instanceof FocObject){ focObject = (FocObject) focData; } } return focObject; } public FVMenuBar getMenubar(boolean createIfNeeded){ if(moreMenuBar == null && createIfNeeded){ moreMenuBar = new FVMenuBar(this); moreMenuBar.addItem("More", null); moreMenuBar.setStyleName("moreMenuBar"); moreMenuBar.addStyleName("noPrint"); } return moreMenuBar; } public void addMoreItem(String title, FVMenuBarCommand command){ addMoreItem(title, true, null, command); } public void addMoreItem(String title, boolean enabled, String description, FVMenuBarCommand command){ if(command != null && title != null){ FVMenuBar menuBar = getMenubar(true); command.setMenuBar(menuBar); if(menuBar.getItems() != null && menuBar.getItems().size() > 0){ MenuItem moreMenu = menuBar.getItems().get(0); MenuItem newItem = moreMenu.addItem(title, command); newItem.setEnabled(enabled); if(description != null){ newItem.setDescription(description); } } } } public IFocData getFocData(){ IFocData focData = getCentralPanel() != null ? getCentralPanel().getFocData() : null; return focData; } public boolean isAttachementApplicable(){ boolean applicable = false; IFocData focData = getCentralPanel().getFocData(); if(focData instanceof FocDataMap){ focData = ((FocDataMap) focData).getMainFocData(); } if(focData != null && focData instanceof FocObject){ applicable = true; } if(applicable){ PhotoAlbumAppGroup group = PhotoAlbumAppGroup.getCurrentAppGroup(); applicable = group != null && group.isAllowDownload(); } return applicable; } public void goBack(){ //The condition on root prevents the navigation from going out of the main layout //when we click on "Back" of an internal layout if(getCentralPanel() != null && getCentralPanel().isRootLayout()){ getCentralPanel().goBack(null); } } public boolean isAskForConfirmationForExit() { IFocData focData = getFocData(); boolean askForConfirmation = isAskForConfirmationForExit_Forced(); if(!askForConfirmation && focData != null && focData instanceof AccessSubject && getValidationSettings().isWithApply() && (getCentralPanel() == null || getCentralPanel().isRootLayout())){//If not root, internal we do not want to ask for confirmation askForConfirmation = ((AccessSubject) getFocData()).needValidationWithPropagation(); } return askForConfirmation; } public void confirmBeforeExit(){ OptionDialog dialog = new OptionDialog("Confirmation", "Do you want to confirm the changes you made?") { @Override public boolean executeOption(String optionName) { if(optionName != null){ if(optionName.equals("SAVE_EXIT")){ apply(); }else if(optionName.equals("DISCARD")){ cancel_ExecutionWithoutPrompt(); }else if(optionName.equals("CANCEL")){ } } return false; } }; dialog.addOption("SAVE_EXIT", "Save & Exit"); dialog.addOption("DISCARD", "Discard changes"); dialog.addOption("CANCEL", "Cancel"); dialog.setWidth("400px"); dialog.setHeight("200px"); Globals.popupDialog(dialog); } public INavigationWindow getFocVaadinMainWindow() { FocWebApplication focWebApplication = FocWebApplication.getInstanceForThread(); return focWebApplication != null ? focWebApplication.getNavigationWindow() : null; } public void setFocVaadinMainWindow(FocWebVaadinWindow focVaadinMainWindow) { this.focVaadinMainWindow = focVaadinMainWindow; } public void addValidationListener(IValidationListener listener){ if(validationListeners != null){ validationListeners.add(listener); } } public void removeValidationListener(IValidationListener listener){ if(validationListeners != null){ validationListeners.remove(listener); } } public String getTitle() { return validationSettings != null ? validationSettings.getTitle() : ""; } public void setTitle(String title) { if(validationSettings != null){ validationSettings.setTitle(title); } titleLabel.setValue(title); } public FValidationSettings getValidationSettings() { return validationSettings; } public void setValidationSettings(FValidationSettings validationSettings) { this.validationSettings = validationSettings; } public ICentralPanel getCentralPanel() { return centralPanel; } public Window getWindow(){ return findAncestor(Window.class); } public Button getDeleteButton(boolean createIfNeeded){ if(deleteButton == null && createIfNeeded){ deleteButton = new Button(); deleteButton.setStyleName(BaseTheme.BUTTON_LINK); if(FocWebApplication.getInstanceForThread().isMobile()){ deleteButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_TRASH_WHITE)); }else{ deleteButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_TRASH_BLACK)); } deleteButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { deleteButtonClickListener(); } }); } return deleteButton; } public void deleteButtonClickAction(){ deleteButtonClickListener(); } private void deleteButtonClickListener(){ if(FocUnitRecorder.isRecording()) { FocUnitRecorder.recordLine("button_ClickDelete();"); } FocObject focObj = getFocObject(); if(focObj != null){ StringBuffer message = focObj.checkDeletionWithMessage(); if(message != null){ Globals.showNotification("Cannot delete Item.", message.toString(), IFocEnvironment.TYPE_WARNING_MESSAGE); }else{ OptionDialog dialog = new OptionDialog("Confirm Deletion", "Are you sure you want to delete this item", getFocData()) { @Override public boolean executeOption(String optionName) { if(optionName.equals("DELETE")){ ICentralPanel centralPanel = getCentralPanel(); if(centralPanel instanceof FocXMLLayout){ FocXMLLayout layout = (FocXMLLayout) centralPanel; FocObject focObject = getFocObject(); if(focObject != null){ if(layout.getTableTreeThatOpenedThisForm() != null){ layout.getTableTreeThatOpenedThisForm().delete(focObject.getReference().getInteger()); } else { focObject.delete(); // if(getCentralPanel() != null) getCentralPanel().refresh(); } goBack(); } } }else if(optionName.equals("CANCEL")){ } return false; } }; dialog.addOption("DELETE", "Delete"); dialog.addOption("CANCEL", "Cancel"); dialog.setWidth("300px"); dialog.setHeight("200px"); dialog.popup(); } } } public boolean isAskForConfirmationForExit_Forced() { return askForConfirmationForExit_Forced; } public void setAskForConfirmationForExit_Forced(boolean isCustomDiscaaskForConfirmation) { this.askForConfirmationForExit_Forced = isCustomDiscaaskForConfirmation; } public Embedded valo_GetGoBackEmbedded(boolean createIfNeeded){ if(valo_BackEmbedded == null && createIfNeeded){ valo_BackEmbedded = new Embedded(); valo_BackEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); if(validationSettings.getDiscardLink() != null && !validationSettings.getDiscardLink().isEmpty()){ backButton.setCaption(validationSettings.getDiscardLink()); }else{ backButton.setIcon(FVIconFactory.getInstance().getFVIcon(FVIconFactory.ICON_CANCEL)); } valo_BackEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { goBack(); } }); } return valo_BackEmbedded; } public Embedded valo_GetPdfGeneratorEmbedded(boolean createIfNeeded){ if(valo_PdfGeneratorEmbedded == null && createIfNeeded && ConfigInfo.isForDevelopment()){ valo_PdfGeneratorEmbedded = new Embedded(); valo_PdfGeneratorEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_PdfGeneratorEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_ADOBE)); focXmlPDFParser = new FocXmlPDFParser(getCentralPanel(), getFocData()); valo_PdfGeneratorEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { } }); BrowserWindowOpener opener = new BrowserWindowOpener(focXmlPDFParser.getStreamResource()); opener.extend(valo_PdfGeneratorEmbedded); } return valo_PdfGeneratorEmbedded; } public Embedded valo_GetMSWordGeneratorEmbedded(boolean createIfNeeded){ if(valo_MSWordGeneratorEmbedded == null && createIfNeeded && ConfigInfo.isForDevelopment()){ valo_MSWordGeneratorEmbedded = new Embedded(); valo_MSWordGeneratorEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_MSWordGeneratorEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_WORD)); focXmlMSWordParser = new FocXmlMSWordParser(getCentralPanel(), getFocData()); valo_MSWordGeneratorEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { } }); BrowserWindowOpener opener = new BrowserWindowOpener(focXmlMSWordParser.getStreamResource()); opener.extend(valo_MSWordGeneratorEmbedded); } return valo_MSWordGeneratorEmbedded; } private PrintingAction newPrintingAction(){ PrintingAction printingAction = null; if(getCentralPanel() instanceof FocXMLLayout){ FocXMLLayout focXMLLayout = (FocXMLLayout) getCentralPanel(); printingAction = focXMLLayout.getPrintingAction(); } return printingAction; } public Embedded valo_GetPDFPrintEmbedded(boolean createIfNeeded){ if(valo_PDFPrintEmbedded == null && createIfNeeded){ valo_PDFPrintEmbedded = new Embedded(); valo_PDFPrintEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_PDFPrintEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_ADOBE)); valo_PDFPrintEmbedded.setImmediate(true); valo_PDFPrintEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { printJasperFireEvent(); } }); } return valo_PDFPrintEmbedded; } public void printJasperFireEvent(){ boolean requireCommit = !isObjectLocked(); if(requireCommit) requireCommit = valo_SaveButton != null || valo_ApplyButton != null; if(!requireCommit || !commit()){//If the Object is locked the commit would return error and thus we will never be able to print locked objects. //This is why when locked we do not even call the commit and we proceed with the printing // PrintingAction printingAction = newPrintingAction(); // if(printingAction != null){ // printingAction.setObjectToPrint(getFocData()); // printingAction.initLauncher(); // popupPrintLayout_Table((FocXMLLayout) getCentralPanel(), getNavigationWindow(), printingAction); if(getCentralPanel() instanceof FocXMLLayout){ PrintingAction printingAction = newPrintingAction(); popupPrintPdf_Table((FocXMLLayout) getCentralPanel(), getNavigationWindow(), printingAction, getFocData()); } } } public static void popupPrintPdf_Table(FocXMLLayout previousLayout, INavigationWindow navigationWindow, PrintingAction printingAction, IFocData objectToPrint){ if(printingAction != null){ printingAction.setObjectToPrint(objectToPrint); printingAction.initLauncher(); popupPrintLayout_Table(previousLayout, navigationWindow, printingAction); } } public static ICentralPanel popupPrintLayout_Table(FocXMLLayout previousLayout, INavigationWindow iNavigationWindow, PrintingAction printingAction){ PrnLayout_Table centralPanel = null; if(iNavigationWindow != null && printingAction != null){ PrnContext prnContext = ReportFactory.getInstance().findContext(printingAction.getPrintingContext()); if(prnContext != null){ FocList layoutList = prnContext.getLayoutList(); if(layoutList != null){ layoutList.loadIfNotLoadedFromDB(); XMLViewKey xmlViewKey = new XMLViewKey(PrnLayoutDesc.getInstance().getStorageName(), XMLViewKey.TYPE_TABLE); centralPanel = (PrnLayout_Table) XMLViewDictionary.getInstance().newCentralPanel_NoParsing(iNavigationWindow, xmlViewKey, layoutList); centralPanel.setPrintingAction_AndBecomeOwner(printingAction); centralPanel.parseXMLAndBuildGui(); iNavigationWindow.changeCentralPanelContent(centralPanel, true); } } } return centralPanel; } private class FVStreamSource implements StreamSource{ private byte[] bytes = null; public FVStreamSource(byte[] bytes) { this.bytes = bytes; } public void dispsoe(){ bytes = null; } public InputStream getStream() { return new ByteArrayInputStream(bytes); } } public Embedded valo_GetPrintEmbedded(boolean createIfNeeded){ if(valo_PrintEmbedded == null && createIfNeeded){ valo_PrintEmbedded = new Embedded(); valo_PrintEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_PrintEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_PRINT)); valo_PrintEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { printClickListener(); } }); } return valo_PrintEmbedded; } public Embedded valo_GetPrintAndExitEmbedded(boolean createIfNeeded){ if(valo_PrintAndExitEmbedded == null){ valo_PrintAndExitEmbedded = new Embedded(); valo_PrintAndExitEmbedded.setDescription("Print and Exit"); valo_PrintAndExitEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_PrintAndExitEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_PRINT_AND_EXIT)); valo_PrintAndExitEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { printAndExitClickListener(); } }); } return valo_PrintAndExitEmbedded; } public Embedded valo_GetAttachEmbedded(boolean createIfNeeded){ if(valo_AttachImageEmbedded == null && createIfNeeded){ valo_AttachImageEmbedded = new Embedded(); valo_AttachImageEmbedded.setDescription("Upload Image"); valo_AttachImageEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_AttachImageEmbedded.setSource(FVIconFactory.getInstance().getFVIcon(FVIconFactory.ICON_ATTACH)); valo_AttachImageEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { attachClickListener(); } }); } return valo_AttachImageEmbedded; } public Embedded valo_GetFullScreenEmbedded(boolean createIfNeeded){ boolean inPopup = true; if(focVaadinMainWindow == null || focVaadinMainWindow instanceof FocWebVaadinWindow){ inPopup = false; } if(valo_FullScreenEmbedded == null && createIfNeeded && !inPopup && !FocWebApplication.getInstanceForThread().isMobile() && ConfigInfo.showFullScreenButton()){ valo_FullScreenEmbedded = new Embedded(); valo_FullScreenEmbedded.setDescription("Full screen"); valo_FullScreenEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); refreshFullScreenIcon(); valo_FullScreenEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { fullScreenButtonClickListener(); } }); } return valo_FullScreenEmbedded; } public Button valo_GetApplyButton(boolean createIfNeeded){ if(valo_ApplyButton == null && createIfNeeded){ valo_ApplyButton = new Button("Done"); if(isRTL()){ valo_ApplyButton.setCaption("إنتهاء"); FocXMLGuiComponentStatic.applyStyleForArabicLabel(valo_ApplyButton); } valo_ApplyButton.setClickShortcut(KeyCode.ENTER, ModifierKey.CTRL); valo_ApplyButton.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); if(validationSettings != null && validationSettings.getApplyLink() != null && !validationSettings.getApplyLink().isEmpty()){ valo_ApplyButton.setCaption(validationSettings.getApplyLink()); } valo_ApplyButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if(FocUnitRecorder.isRecording()) { FocUnitRecorder.recordLine("button_ClickApply();"); } applyButtonClickListener(); } }); } return valo_ApplyButton; } public Embedded valo_GetDeleteEmbedded(boolean createIfNeeded){ if(valo_DeleteEmbedded == null && createIfNeeded && !isObjectLocked()){ valo_DeleteEmbedded = new Embedded(); valo_DeleteEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); if(FocWebApplication.getInstanceForThread().isMobile()){ valo_DeleteEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_TRASH_WHITE)); }else{ valo_DeleteEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_TRASH_BLACK)); } valo_DeleteEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { deleteButtonClickListener(); } }); } return valo_DeleteEmbedded; } public void setDeleteButtonVisible(boolean visible){ if(valo_DeleteEmbedded != null){ valo_DeleteEmbedded.setVisible(visible); } if(deleteButton != null){ deleteButton.setVisible(visible); } } public FVCheckBox valo_GetNotCompletedYet(boolean createIfNeeded){ if(valo_NotCompletedYet == null && createIfNeeded){// && !isObjectLocked()){ FocObject focObj = getFocObject(); if(focObj != null){ FProperty prop = focObj.getFocProperty(FField.FLD_NOT_COMPLETED_YET); if(prop != null){ FocXMLAttributes attr = new FocXMLAttributes(); String dataPath = prop.getFocField() != null ? prop.getFocField().getName() : null; if(dataPath != null){ attr.addAttribute(FXML.ATT_DATA_PATH, prop.getFocField().getName()); } valo_NotCompletedYet = new FVCheckBox(prop, attr); if(dataPath != null){ FocXMLGuiComponentStatic.setRootFocDataWithDataPath(valo_NotCompletedYet, focObj, dataPath); } valo_NotCompletedYet.copyMemoryToGui(); valo_NotCompletedYet.setImmediate(true);//Was not taken into account sometimes! FENIX Station showing it if(ConfigInfo.isGuiRTL()){ valo_NotCompletedYet.setCaption("غير مكتمل"); }else{ valo_NotCompletedYet.setCaption("Not Completed Yet"); } if(getCentralPanel() != null && getCentralPanel() instanceof FocXMLLayout && prop.getFocField() != null){ FocXMLLayout focXMLLayout = (FocXMLLayout) getCentralPanel(); focXMLLayout.putComponent(prop.getFocField().getName(), valo_NotCompletedYet); } } } } return valo_NotCompletedYet; } private Embedded valo_GetInternalEmailEmbedded(boolean createIfNeeded){ if(valo_SendInternalEmailEmbedded == null && createIfNeeded){ valo_SendInternalEmailEmbedded = new Embedded(); valo_SendInternalEmailEmbedded.setDescription("Send Internal Email"); valo_SendInternalEmailEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_SendInternalEmailEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_EMAIL)); valo_SendInternalEmailEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { sendInternalEmailClickListener(); } }); } return valo_SendInternalEmailEmbedded; } public Embedded valo_GetEmailEmbedded(boolean createIfNeeded){ if(valo_SendEmailEmbedded == null && createIfNeeded){ valo_SendEmailEmbedded = new Embedded(); valo_SendEmailEmbedded.setDescription("Send Email"); valo_SendEmailEmbedded.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_SendEmailEmbedded.setSource(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_EMAIL)); valo_SendEmailEmbedded.addStyleName("noPrint"); valo_SendEmailEmbedded.addClickListener(new MouseEvents.ClickListener() { @Override public void click(com.vaadin.event.MouseEvents.ClickEvent event) { emailClickListener(); } }); } return valo_SendEmailEmbedded; } public Button valo_GetDiscardButton(boolean createIfNeeded){ if(valo_DiscardButton == null && createIfNeeded){ valo_DiscardButton = new Button("Cancel"); if(isRTL()){ valo_DiscardButton.setCaption("إلغاء"); FocXMLGuiComponentStatic.applyStyleForArabicLabel(valo_DiscardButton); } valo_DiscardButton.addStyleName("noPrint"); valo_DiscardButton.setDescription("Discard Changes"); valo_DiscardButton.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); if(validationSettings.getDiscardLink() != null && !validationSettings.getDiscardLink().isEmpty()){ valo_DiscardButton.setCaption(validationSettings.getDiscardLink()); }else{ valo_DiscardButton.addStyleName("noFocusHighlight"); } valo_DiscardButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if(FocUnitRecorder.isRecording()) { String innerLayoutName = getInnerLayoutName(); if(!Utils.isStringEmpty(innerLayoutName)) { FocUnitRecorder.recordLine("button_ClickDiscard("+innerLayoutName+");"); }else { FocUnitRecorder.recordLine("button_ClickDiscard();"); } } discardButtonClickListener(); } }); } return valo_DiscardButton; } protected String getInnerLayoutName() { String innerLayoutName = null; FVTableWrapperLayout tableWrapperLayout = FVValidationLayout.this.findAncestor(FVTableWrapperLayout.class); if(tableWrapperLayout != null && tableWrapperLayout.getDelegate() != null && !Utils.isStringEmpty(tableWrapperLayout.getDelegate().getNameInMap())) { innerLayoutName = tableWrapperLayout.getDelegate().getNameInMap(); } return innerLayoutName; } public Button valo_GetSaveButton(boolean createIfNeeded){ if(valo_SaveButton == null && createIfNeeded){ valo_SaveButton = new Button("Save"); if(isRTL()){ valo_SaveButton.setCaption("حفظ"); FocXMLGuiComponentStatic.applyStyleForArabicLabel(valo_SaveButton); } valo_SaveButton.addStyleName(FocXMLGuiComponentStatic.STYLE_HAND_POINTER_ON_HOVER); valo_SaveButton.setClickShortcut(KeyCode.S, ModifierKey.CTRL); valo_SaveButton.setDescription("Save changes and stay in this form"); valo_SaveButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { if(FocUnitRecorder.isRecording()) { String innerLayoutName = getInnerLayoutName(); if(!Utils.isStringEmpty(innerLayoutName)) { FocUnitRecorder.recordLine("button_ClickSave("+innerLayoutName+");"); }else { FocUnitRecorder.recordLine("button_ClickSave();"); } } saveButtonClickListener(); } }); } return valo_SaveButton; } public boolean isGoingBackAfterDoneClicked() { return goingBackAfterDoneClicked; } private void setGoingBackAfterDoneClicked(boolean goingBackDoneClicked) { this.goingBackAfterDoneClicked = goingBackDoneClicked; } public int getHorizontalComponentCount() { return mainHorizontalLayout != null ? mainHorizontalLayout.getComponentCount() : 0; } public Component getHorizontalComponentAt(int i) { return mainHorizontalLayout != null ? mainHorizontalLayout.getComponent(i) : null; } public void addHorizontalComponentAt(Component comp, int index) { if(mainHorizontalLayout != null) { mainHorizontalLayout.addComponent(comp, index); mainHorizontalLayout.setComponentAlignment(comp, Alignment.MIDDLE_RIGHT); } } /* private HelpContextComponentFocusable getHelpContextComponentFocusable(boolean createIfNeeded){ if(helpContextComponentFocusable == null && createIfNeeded){ helpContextComponentFocusable = new HelpContextComponentFocusable(); } return helpContextComponentFocusable; } private class HelpContextComponentFocusable { private List<FocXMLGuiComponent> contextHelpComponentsList = null; private int currentContextHelpIndex = 0; public HelpContextComponentFocusable() { FocXMLLayout focXMLLayout = (FocXMLLayout) (getCentralPanel() != null && getCentralPanel() instanceof FocXMLLayout ? getCentralPanel() : null); if(focXMLLayout != null){ contextHelpComponentsList = newContextHelpComponentsList(); } } public void dispose(){ if(contextHelpComponentsList != null){ contextHelpComponentsList.clear(); contextHelpComponentsList = null; } currentContextHelpIndex = 0; } public void onButtonClickListener(boolean isNextFocus){ if(contextHelpComponentsList != null){ currentContextHelpIndex = isNextFocus ? currentContextHelpIndex+1 : currentContextHelpIndex-1; if(currentContextHelpIndex >= contextHelpComponentsList.size()){ currentContextHelpIndex = 0; } if(currentContextHelpIndex < 0){ currentContextHelpIndex = contextHelpComponentsList.size(); } if(contextHelpComponentsList != null && currentContextHelpIndex < contextHelpComponentsList.size()){ showHelpAtIndex(currentContextHelpIndex); } } } public List<FocXMLGuiComponent> newContextHelpComponentsList(){ ICentralPanel cp = getCentralPanel(); if(cp instanceof FocXMLLayout){ FocXMLLayout xmlLayout = (FocXMLLayout) cp; contextHelpComponentsList = new ArrayList<FocXMLGuiComponent>(); Iterator<FocXMLGuiComponent> iter = xmlLayout.getXMLComponentIterator(); while(iter != null && iter.hasNext()){ FocXMLGuiComponent focXMLGuiComponent = iter.next(); if(focXMLGuiComponent != null && focXMLGuiComponent.getAttributes() != null){ String help = focXMLGuiComponent.getAttributes().getValue(FXML.ATT_HELP); if(help != null){ contextHelpComponentsList.add(focXMLGuiComponent); } } } Collections.sort(contextHelpComponentsList, new Comparator<FocXMLGuiComponent>() { public int compare(FocXMLGuiComponent c1, FocXMLGuiComponent c2) { int value = 0; int index1 = Utils.parseInteger(c1.getAttributes().getValue(FXML.ATT_HELP_INDEX), -1); int index2 = Utils.parseInteger(c2.getAttributes().getValue(FXML.ATT_HELP_INDEX), -1); value = index1 - index2; return value; } }); } return contextHelpComponentsList; } public void showHelpAtIndex(int currentContextHelpIndex){ if(contextHelpComponentsList != null){ FocXMLGuiComponent guiComponent = contextHelpComponentsList.get(currentContextHelpIndex); if(guiComponent != null && guiComponent instanceof AbstractField){ AbstractField<?> abstractField = (AbstractField<?>) guiComponent; String help = guiComponent.getAttributes().getValue(FXML.ATT_HELP); ContextHelp contextHelp = new ContextHelp(); contextHelp.extend(FocWebApplication.getInstanceForThread()); contextHelp.addHelpForComponent(abstractField, help); contextHelp.showHelpFor(abstractField); } } } public void showScreenDescriptionWindow(){ } } public boolean isHelpOn() { return helpOn; } public void setHelpOn(boolean helpOn) { this.helpOn = helpOn; } */ }
package com.haskforce.settings; import com.haskforce.utils.ExecUtil; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SearchableConfigurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.ui.TextAccessor; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * The "Haskell Tools" option in Preferences->Project Settings. */ public class HaskellToolsConfigurable implements SearchableConfigurable { public static final String HASKELL_TOOLS_ID = "Haskell Tools"; private Project project; // Old values to detect user updates. private String oldParserHelperPath; private String oldStylishPath; // Swing components. private JPanel mainPanel; private TextFieldWithBrowseButton parserHelperPath; private JLabel parserHelperVersion; private JButton parserHelperAutoFind; private TextFieldWithBrowseButton stylishPath; private JButton stylishAutoFind; private JLabel stylishVersion; public HaskellToolsConfigurable(@NotNull Project inProject) { project = inProject; oldParserHelperPath = PropertiesComponent.getInstance(project).getValue("parserHelperPath", ""); oldStylishPath = PropertiesComponent.getInstance(project).getValue("stylishPath", ""); } @NotNull @Override public String getId() { return HASKELL_TOOLS_ID; } @Nullable @Override public Runnable enableSearch(String s) { return null; } @Nls @Override public String getDisplayName() { return HASKELL_TOOLS_ID; } @Nullable @Override public String getHelpTopic() { return null; } @Nullable @Override public JComponent createComponent() { if (!oldParserHelperPath.isEmpty()) { parserHelperPath.setText(oldParserHelperPath); } if (!oldStylishPath.isEmpty()) { stylishPath.setText(oldStylishPath); } addFolderListener(parserHelperPath, "parser-helper"); addFolderListener(stylishPath, "stylish-haskell"); parserHelperAutoFind.addActionListener(createApplyPathAction(parserHelperPath, "parser-helper")); stylishAutoFind.addActionListener(createApplyPathAction(stylishPath, "stylish-haskell")); updateVersionInfoFields(); return mainPanel; } private static void addFolderListener(final TextFieldWithBrowseButton textField, final String executable) { textField.addBrowseFolderListener("Select " + executable + " path", "", null, FileChooserDescriptorFactory.createSingleLocalFileDescriptor()); } private static ActionListener createApplyPathAction(final TextAccessor textField, final String executable) { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String guessedPath = ExecUtil.locateExecutableByGuessing(executable); if (guessedPath != null) { textField.setText(guessedPath); } else { Messages.showErrorDialog("Could not find '" + executable + "'.", "HaskForce"); } } }; } /** * Enables the apply button if anything changed. */ @Override public boolean isModified() { return !(parserHelperPath.getText().equals(oldParserHelperPath) && stylishPath.getText().equals(oldStylishPath)); } /** * Triggered when the user pushes the apply button. */ @Override public void apply() throws ConfigurationException { updateVersionInfoFields(); saveState(); } /** * Triggered when the user pushes the cancel button. */ @Override public void reset() { restoreState(); } @Override public void disposeUIResources() { } /** * Heuristically finds the version number. Current implementation is the * identity function since cabal plays nice. */ private static String getVersion(String cmd, String versionflag) { return ExecUtil.exec(cmd + ' ' + versionflag); } /** * Updates the version info fields for all files configured. */ private void updateVersionInfoFields() { // Parser-helper. if (!parserHelperPath.getText().isEmpty()) { parserHelperVersion.setText(getVersion(parserHelperPath.getText(), "--numeric-version")); } // Stylish-Haskell. if (!stylishPath.getText().isEmpty()) { stylishVersion.setText(getVersion(stylishPath.getText(), "--version")); } } /** * Persistent save of the current state. */ private void saveState() { PropertiesComponent.getInstance(project).setValue("parserHelperPath", parserHelperPath.getText()); PropertiesComponent.getInstance(project).setValue("stylishPath", stylishPath.getText()); oldParserHelperPath = parserHelperPath.getText(); oldStylishPath = stylishPath.getText(); } /** * Restore components to the initial state. */ private void restoreState() { parserHelperPath.setText(oldParserHelperPath); stylishPath.setText(oldStylishPath); } }
package org.xins.types; import java.io.IOException; import java.io.StringWriter; import java.util.Iterator; import java.util.List; import java.util.HashMap; import java.util.Map; import nl.wanadoo.util.MandatoryArgumentChecker; import org.apache.log4j.Logger; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.jdom.Document; import org.jdom.Element; /** * Patterns type. An enumeration type only accepts values that match a certain * pattern. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class PatternType extends Type { // Class fields /** * Perl 5 pattern compiler. */ private final Perl5Compiler PATTERN_COMPILER = new Perl5Compiler(); /** * Pattern matcher. */ private final Perl5Matcher PATTERN_MATCHER = new Perl5Matcher(); // Class functions // Constructors protected PatternType(String name, String pattern) throws IllegalArgumentException, MalformedPatternException { super(name, String.class); if (pattern == null) { throw new IllegalArgumentException("pattern == null"); } synchronized (PATTERN_COMPILER) { _pattern = PATTERN_COMPILER.compile(pattern, Perl5Compiler.READ_ONLY_MASK); } } // Fields /** * Compiled pattern. This is the compiled version of {@link #_pattern}. * This field cannot be <code>null</code>. */ private final Pattern _pattern; // Methods protected final void checkValueImpl(String value) throws TypeValueException { if (! PATTERN_MATCHER.matches(value, _pattern)) { throw new TypeValueException(this, value); } } protected final Object fromStringImpl(String value) { return value; } /** * Returns the pattern. * * @return * the pattern, not <code>null</code>. */ public String getPattern() { return _pattern.getPattern(); } }
package me.truekenny.MyLineagePvpSystem; import org.bukkit.ChatColor; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.kitteh.tag.AsyncPlayerReceiveNameTagEvent; import org.kitteh.tag.TagAPI; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class PlayerListener implements Listener { private static final Set<String> types = new HashSet<String>(Arrays.asList( new String[]{"SHEEP", "COW", "ZOMBIE", "SKELETON"} )); private final MyLineagePvpSystem plugin; public PlayerListener(MyLineagePvpSystem instance) { plugin = instance; plugin.log("PlayerListener has been enabled!"); } @EventHandler(priority = EventPriority.HIGH) public void onPlayerDeath(final PlayerDeathEvent event) { final Player player = event.getEntity(); Player killer = player.getKiller(); plugin.log("onPlayerDeath: entity: " + player.getName()); if (killer != null && killer.getType().toString().equalsIgnoreCase("player")) { plugin.log("onPlayerDeath: killer: " + ((Player) killer).getName()); murder(event, player, killer); } died(player); } private void died(Player player) { plugin.log("died: " + player.getName() + " умер", plugin.ANSI_RED); if (plugin.players.getPlayerData(player).died()) { TagAPI.refreshPlayer(player); } } private void murder(PlayerDeathEvent event, final Player player, Player killer) { if (plugin.players.getPlayerData(player).getColor().equals(ChatColor.WHITE)) { event.setKeepLevel(true); event.setDroppedExp(0); final ItemStack[] armor = player.getInventory().getArmorContents(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.getInventory().setArmorContents(armor); } }); for (ItemStack is : armor) { event.getDrops().remove(is); } final ItemStack[] inventory = player.getInventory().getContents(); for (int i = 0; i < inventory.length; i++) { ItemStack is = inventory[i]; if (is != null && Math.random() < 0.95) event.getDrops().remove(is); else inventory[i] = null; } plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { player.getInventory().setContents(inventory); } }); } plugin.log("murder: " + killer.getName() + " убил " + player.getName(), plugin.ANSI_RED); if (plugin.players.getPlayerData(killer).murder(player)) { TagAPI.refreshPlayer(killer); } } @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDeath(EntityDeathEvent event) { LivingEntity livingEntity = event.getEntity(); plugin.log("onEntityDeath: entity: " + livingEntity.getType().toString()); if (!types.contains(livingEntity.getType().toString())) { plugin.log("onEntityDeath: killer: Плохой тип"); return; } Player killer = livingEntity.getKiller(); if (killer != null && killer.getType().toString().equalsIgnoreCase("player")) { plugin.log("onEntityDeath: killer: " + ((Player) killer).getName()); cleansing(killer); } } private void cleansing(Player player) { plugin.log("cleansing: " + player.getName() + " чистит карму", plugin.ANSI_RED); if (plugin.players.getPlayerData(player).cleansing()) { TagAPI.refreshPlayer(player); } } @EventHandler public void onEntityDamage(EntityDamageByEntityEvent entityDamageByEntityEvent) { Entity entity = entityDamageByEntityEvent.getEntity(); plugin.log("onEntityDamage: type: " + (entity == null ? "null" : entity.getType().toString())); if (entity != null && entity.getType().toString().equalsIgnoreCase("player")) { plugin.log("onEntityDamage: entity: " + ((Player) entity).getName()); } Player damager = getDamager(entityDamageByEntityEvent); if (damager != null) { plugin.log("onEntityDamage: damager: " + damager.getName()); } if (entity != null && entity.getType().toString().equalsIgnoreCase("player") && damager != null) { hit((Player) entity, damager); } } private Player getDamager(EntityDamageByEntityEvent entityDamageByEntityEvent) { plugin.log("getDamager: " + entityDamageByEntityEvent.getDamager().getType().toString()); plugin.log("getDamager: " + entityDamageByEntityEvent.getDamager().getClass().toString()); if (entityDamageByEntityEvent.getDamager() instanceof Player) { return (Player) entityDamageByEntityEvent.getDamager(); } if (entityDamageByEntityEvent.getDamager() instanceof Projectile) { Projectile projectile = (Projectile) entityDamageByEntityEvent.getDamager(); if (projectile.getShooter() instanceof Player) { return (Player) projectile.getShooter(); } } return null; } private void hit(Player player, Player damager) { plugin.log("hit: " + damager.getName() + " ударил " + player.getName(), plugin.ANSI_RED); if (plugin.players.getPlayerData(damager).hit(player)) { TagAPI.refreshPlayer(damager); } } @EventHandler public void onNameTag(AsyncPlayerReceiveNameTagEvent event) { Player player = event.getNamedPlayer(); event.setTag(getPlayerColor(player) + player.getName()); // plugin.log("onNameTag: " + player.getName()); } private ChatColor getPlayerColor(Player player) { return plugin.players.getPlayerData(player).getColor(); } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { //plugin.log("onPlayerMove: "); //plugin.players.updateNicks(); } }
package com.haxademic.core.draw.mapping; import java.awt.Point; import java.awt.geom.Point2D; import com.haxademic.core.app.P; import com.haxademic.core.data.ConvertUtil; import com.haxademic.core.draw.context.DrawUtil; import com.haxademic.core.file.FileUtil; import processing.core.PGraphics; import processing.event.KeyEvent; import processing.event.MouseEvent; public class BaseSavedQuadUI { protected int w; protected int h; protected Point topLeft; protected Point topRight; protected Point bottomRight; protected Point bottomLeft; protected Point points[]; public static Point SELECTED_POINT; public static BaseSavedQuadUI DRAGGING_QUAD; protected float mouseActiveDist = 15; protected Point2D.Float center = new Point2D.Float(); protected boolean isPressed = false; protected boolean isHovered = false; protected Point mousePoint = new Point(); protected Point mouseDragged = new Point(); protected String filePath = null; protected boolean writesToFile = false; protected int lastInteractTime = 0; protected int INTERACTION_TIMEOUT = 5000; protected boolean active = true; protected boolean shiftDown = false; public BaseSavedQuadUI(int w, int h, String filePath) { this.filePath = filePath; this.w = w; this.h = h; resetCorners(); P.p.registerMethod("mouseEvent", this); // add mouse listeners P.p.registerMethod("keyEvent", this); // prep txt file if(filePath != null) { filePath = FileUtil.getFile(filePath); writesToFile = true; loadMappingFile(); createMappingFile(); } updateCenter(); } // public points setters public void setActive(boolean debug) { if(active != debug) { // only toggle when dirty active = debug; if(active) { resetInteractionTimeout(); DRAGGING_QUAD = this; SELECTED_POINT = null; } else { for( int i=0; i < points.length; i++ ) { if(points[i] == SELECTED_POINT) SELECTED_POINT = null; } } } } public void resetCorners() { topLeft = new Point(0, 0); topRight = new Point(w, 0); bottomRight = new Point(w, h); bottomLeft = new Point(0, h); points = new Point[] { topLeft, topRight, bottomRight, bottomLeft }; if(filePath != null) save(); // only save after init } public void setPosition(float x, float y, float w, float h) { topLeft.setLocation(x - w/2f, y - h/2f); topRight.setLocation(x + w/2f, y - h/2f); bottomRight.setLocation(x + w/2f, y + h/2f); bottomLeft.setLocation(x - w/2f, y + h/2f); save(); } // state getters public boolean isActive() { return active; } public boolean isHovered() { return isHovered; } public float centerX() { return center.x; } public float centerY() { return center.y; } // USER INTERFACE //////////////////////////////////////////// public void drawDebug(PGraphics pg, boolean offscreen) { if(active && P.p.millis() < lastInteractTime + INTERACTION_TIMEOUT) { if(offscreen) pg.beginDraw(); showSelectedPoint(pg); showMappedRect(pg); if(offscreen) pg.endDraw(); } } protected void showSelectedPoint(PGraphics pg) { if(active == false) return; if(SELECTED_POINT != null) drawPoint(pg, SELECTED_POINT); } protected void drawPoint(PGraphics pg, Point point) { DrawUtil.setDrawCenter(pg); pg.fill(255, 75); pg.stroke(0, 255, 0); pg.strokeWeight(2); float indicatorSize = 20f + 3f * P.sin(P.p.frameCount / 10f); pg.ellipse(point.x, point.y, indicatorSize, indicatorSize); DrawUtil.setDrawCorner(pg); } protected void showMappedRect(PGraphics pg) { pg.noFill(); pg.stroke(0, 255, 0); pg.strokeWeight(1); pg.line(topLeft.x, topLeft.y, topRight.x, topRight.y); pg.line(topRight.x, topRight.y, bottomRight.x, bottomRight.y); pg.line(bottomRight.x, bottomRight.y, bottomLeft.x, bottomLeft.y); pg.line(bottomLeft.x, bottomLeft.y, topLeft.x, topLeft.y); pg.ellipse(center.x - 4, center.y - 4, 8, 8); } public void mouseEvent(MouseEvent event) { mousePoint.setLocation( event.getX(), event.getY() ); checkHoverQuad(event); if(active == false) return; resetInteractionTimeout(); checkMouseDragPoint(event); checkMouseDragQuad(event); } public void checkMouseDragPoint(MouseEvent event) { switch (event.getAction()) { case MouseEvent.PRESS: break; case MouseEvent.RELEASE: if(SELECTED_POINT != null) save(); SELECTED_POINT = null; break; case MouseEvent.MOVE: checkMouseHoverPoint(); break; case MouseEvent.DRAG: if( SELECTED_POINT != null ) { SELECTED_POINT.setLocation( mousePoint ); updateCenter(); } break; } } protected void checkMouseHoverPoint() { boolean hoveredPoint = false; for( int i=0; i < points.length; i++ ) { if(points[i].distance( mousePoint.x, mousePoint.y ) < mouseActiveDist) { SELECTED_POINT = points[i]; hoveredPoint = true; DRAGGING_QUAD = null; } } if(hoveredPoint == false) SELECTED_POINT = null; } public void checkHoverQuad(MouseEvent event) { switch (event.getAction()) { case MouseEvent.MOVE: isHovered = inside(mousePoint, points); break; } } public void checkMouseDragQuad(MouseEvent event) { switch (event.getAction()) { case MouseEvent.PRESS: if(isHovered == true && SELECTED_POINT == null) { DRAGGING_QUAD = this; mouseDragged.setLocation(mousePoint.x, mousePoint.y); updateCenter(); } break; case MouseEvent.RELEASE: if(DRAGGING_QUAD != null) save(); DRAGGING_QUAD = null; break; case MouseEvent.DRAG: if(DRAGGING_QUAD == this) { mouseDragged.setLocation(mousePoint.x - mouseDragged.x, mousePoint.y - mouseDragged.y); for( int i=0; i < points.length; i++ ) { points[i].translate(mouseDragged.x, mouseDragged.y); } mouseDragged.setLocation(mousePoint.x, mousePoint.y); updateCenter(); } break; } } protected boolean inside(Point point, Point[] vertices) { // ray-casting algorithm based on float x = point.x; float y = point.y; boolean inside = false; for (int i = 0, j = vertices.length - 1; i < vertices.length; j = i++) { float xi = vertices[i].x, yi = vertices[i].y; float xj = vertices[j].x, yj = vertices[j].y; boolean intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); if (intersect) inside = !inside; } return inside; }; public void keyEvent(KeyEvent e) { if(active == false) return; if(e.getAction() == KeyEvent.PRESS) { // shift if(e.getKeyCode() == P.SHIFT) shiftDown = true; // reset timeout if(e.getKeyCode() == P.UP || e.getKeyCode() == P.LEFT || e.getKeyCode() == P.RIGHT || e.getKeyCode() == P.DOWN || e.getKeyCode() == P.TAB) resetInteractionTimeout(); // translate if arrow key Point translatePoint = new Point(0, 0); if(e.getKeyCode() == P.UP) translatePoint.setLocation(0, -1); if(e.getKeyCode() == P.LEFT) translatePoint.setLocation(-1, 0); if(e.getKeyCode() == P.RIGHT) translatePoint.setLocation(1, 0); if(e.getKeyCode() == P.DOWN) translatePoint.setLocation(0, 1); if(shiftDown) { translatePoint.x *= 10; translatePoint.y *= 10; } // tab to next point if(e.getKeyCode() == P.TAB) { if(SELECTED_POINT == points[0]) SELECTED_POINT = points[1]; else if(SELECTED_POINT == points[1]) SELECTED_POINT = points[2]; else if(SELECTED_POINT == points[2]) SELECTED_POINT = points[3]; else SELECTED_POINT = points[0]; resetInteractionTimeout(); } // apply transformation if needed if(translatePoint.x != 0 || translatePoint.y != 0) { if(SELECTED_POINT == points[0] || SELECTED_POINT == points[1] || SELECTED_POINT == points[2] || SELECTED_POINT == points[3]) { SELECTED_POINT.translate(translatePoint.x, translatePoint.y); save(); } else if(DRAGGING_QUAD == this) { for( int i=0; i < points.length; i++ ) { points[i].translate(translatePoint.x, translatePoint.y); } save(); } } updateCenter(); } if(e.getAction() == KeyEvent.RELEASE) { if(e.getKeyCode() == P.SHIFT) shiftDown = false; } } protected void resetInteractionTimeout() { lastInteractTime = P.p.millis(); } // SAVE TO FILE ////////////////////////////////// protected void loadMappingFile() { if(FileUtil.fileOrPathExists(filePath) == true) { String[] mappingStr = FileUtil.readTextFromFile(filePath); // p.loadStrings(filePath); String[] posArray = mappingStr[0].split(","); topLeft.setLocation(ConvertUtil.stringToInt(posArray[0]), ConvertUtil.stringToInt(posArray[1])); topRight.setLocation(ConvertUtil.stringToInt(posArray[2]), ConvertUtil.stringToInt(posArray[3])); bottomRight.setLocation(ConvertUtil.stringToInt(posArray[4]), ConvertUtil.stringToInt(posArray[5])); bottomLeft.setLocation(ConvertUtil.stringToInt(posArray[6]), ConvertUtil.stringToInt(posArray[7])); } else { createMappingFile(); } } protected void createMappingFile() { String mappingFilePath = FileUtil.pathForFile(this.filePath); if(FileUtil.fileOrPathExists(mappingFilePath) == false) { FileUtil.createDir(mappingFilePath); } } protected void updateCenter() { center.setLocation( (float) (topLeft.x + topRight.x + bottomRight.x + bottomLeft.x) / 4f, (float) (topLeft.y + topRight.y + bottomRight.y + bottomLeft.y) / 4f ); } protected void save() { updateCenter(); if(this.filePath != null) writeToFile(); } protected void writeToFile() { if(writesToFile == false) return; String coordsStr = String.join(",", new String[] { Integer.toString(topLeft.x), Integer.toString(topLeft.y), Integer.toString(topRight.x), Integer.toString(topRight.y), Integer.toString(bottomRight.x), Integer.toString(bottomRight.y), Integer.toString(bottomLeft.x), Integer.toString(bottomLeft.y) }); FileUtil.writeTextToFile(filePath, coordsStr); } public void enableFileWriting(boolean writes) { writesToFile = writes; } }
package com.astoev.cave.survey.activity.map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.View; import com.astoev.cave.survey.Constants; import com.astoev.cave.survey.R; import com.astoev.cave.survey.activity.UIUtilities; import com.astoev.cave.survey.model.Gallery; import com.astoev.cave.survey.model.Leg; import com.astoev.cave.survey.model.Option; import com.astoev.cave.survey.service.Options; import com.astoev.cave.survey.service.Workspace; import com.astoev.cave.survey.util.DaoUtil; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; public class MapView extends View { public static final int POINT_RADIUS = 3; public static final int MEASURE_POINT_RADIUS = 2; public static final int CURR_POINT_RADIUS = 8; private final static int LABEL_DEVIATION_X = 5; private final static int LABEL_DEVIATION_Y = 5; Paint polygonPaint = new Paint(); Paint polygonWidthPaint = new Paint(); Paint overlayPaint = new Paint(); Paint youAreHerePaint = new Paint(); Paint gridPaint = new Paint(); private float scale = 10; private int mapCenterMoveX = 0; private int mapCenterMoveY = 0; private float initialMoveX = 0; private float initialMoveY = 0; List<Integer> processedLegs = new ArrayList<Integer>(); private SparseArray<Point2D> mapPoints = new SparseArray<Point2D>(); private SparseIntArray galleryColors = new SparseIntArray(); private SparseArray<String> galleryNames = new SparseArray<String>(); public MapView(Context context, AttributeSet attrs) { super(context, attrs); polygonPaint.setColor(Color.RED); polygonPaint.setStrokeWidth(2); polygonWidthPaint.setColor(Color.RED); polygonWidthPaint.setStrokeWidth(1); overlayPaint.setColor(Color.WHITE); youAreHerePaint.setColor(Color.WHITE); youAreHerePaint.setAlpha(50); // semi transparent white gridPaint.setColor(Color.parseColor("#11FFFFFF")); gridPaint.setStrokeWidth(1); } @Override public void onDraw(Canvas canvas) { try { processedLegs.clear(); mapPoints.clear(); galleryColors.clear(); galleryNames.clear(); // prepare map surface int maxX = canvas.getWidth(); int maxY = canvas.getHeight(); int centerX = maxX / 2; int centerY = maxY / 2; int spacing = 5; // grid int gridStep = 20; for (int x=0; x<maxX; x++) { canvas.drawLine(x*gridStep + spacing, spacing, x*gridStep + spacing, maxY - spacing, gridPaint); } for (int y=0; y<maxY; y++) { canvas.drawLine(spacing, y*gridStep + spacing, maxX - spacing, y*gridStep + spacing, gridPaint); } String pointLabel; // load the points List<Leg> legs = DaoUtil.getCurrProjectLegs(); while (processedLegs.size() < legs.size()) { for (Leg l : legs) { if (processedLegs.size() == legs.size()) { break; } if (processedLegs.contains(l.getId())) { // skip processed continue; } else { // first leg ever Point2D first; if (processedLegs.size() == 0) { first = new Point2D(Float.valueOf(centerX), Float.valueOf(centerY), l.getLeft(), l.getRight(), l.getAzimuth()); } else { first = mapPoints.get(l.getFromPoint().getId()); } if (mapPoints.get(l.getFromPoint().getId()) == null) { mapPoints.put(l.getFromPoint().getId(), first); //color if (galleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) { galleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(galleryColors.size())); Gallery gallery = DaoUtil.getGallery(l.getGalleryId()); galleryNames.put(l.getGalleryId(), gallery.getName()); } polygonPaint.setColor(galleryColors.get(l.getGalleryId())); polygonWidthPaint.setColor(galleryColors.get(l.getGalleryId())); DaoUtil.refreshPoint(l.getFromPoint()); pointLabel = galleryNames.get(l.getGalleryId()) + l.getFromPoint().getName(); canvas.drawText(pointLabel, mapCenterMoveX + first.getX() + LABEL_DEVIATION_X, mapCenterMoveY + first.getY() + LABEL_DEVIATION_Y, polygonPaint); canvas.drawCircle(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), POINT_RADIUS, polygonPaint); } float deltaX; float deltaY; double galleryWidthAngle; if (l.getDistance() == null || l.getAzimuth() == null) { deltaX = 0; deltaY = 0; } else { float legDistance = applySlopeToDistance(l.getDistance(), getSlopeInDegrees(l.getSlope())); deltaY = -(float) (legDistance * Math.cos(Math.toRadians(getAzimuthInDegrees(l.getAzimuth())))) * scale; deltaX = (float) (legDistance * Math.sin(Math.toRadians(getAzimuthInDegrees(l.getAzimuth())))) * scale; } Point2D second = new Point2D(first.getX() + deltaX, first.getY() + deltaY); if (l.getLeft() != null) { second.setLeft(l.getLeft()); } if (l.getRight() != null) { second.setRight(l.getRight()); } if (l.getAzimuth() != null) { second.setAzimuth(l.getAzimuth()); } if (mapPoints.get(l.getToPoint().getId()) == null) { mapPoints.put(l.getToPoint().getId(), second); // color if (galleryColors.get(l.getGalleryId(), Constants.NOT_FOUND) == Constants.NOT_FOUND) { galleryColors.put(l.getGalleryId(), MapUtilities.getNextGalleryColor(galleryColors.size())); Gallery gallery = DaoUtil.getGallery(l.getGalleryId()); galleryNames.put(l.getGalleryId(), gallery.getName()); } polygonPaint.setColor(galleryColors.get(l.getGalleryId())); polygonWidthPaint.setColor(galleryColors.get(l.getGalleryId())); // Log.i(Constants.LOG_TAG_UI, "Drawing leg " + l.getFromPoint().getName() + ":" + l.getToPoint().getName() + "-" + l.getGalleryId()); if (Workspace.getCurrentInstance().getActiveLegId().equals(l.getId())) { // you are here canvas.drawCircle(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), CURR_POINT_RADIUS, youAreHerePaint); } DaoUtil.refreshPoint(l.getToPoint()); pointLabel = galleryNames.get(l.getGalleryId()) + l.getToPoint().getName(); canvas.drawText(pointLabel, mapCenterMoveX + second.getX() + LABEL_DEVIATION_X, mapCenterMoveY + second.getY() + LABEL_DEVIATION_Y, polygonPaint); canvas.drawCircle(mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), POINT_RADIUS, polygonPaint); } // leg canvas.drawLine(mapCenterMoveX + first.getX(), mapCenterMoveY + first.getY(), mapCenterMoveX + second.getX(), mapCenterMoveY + second.getY(), polygonPaint); Leg prevLeg = DaoUtil.getLegByToPoint(l.getFromPoint()); // left if (first.getLeft() != null && first.getLeft()> 0) { if (prevLeg == null) { // first point by 90 degree left galleryWidthAngle = Math.toRadians(getAzimuthInDegrees(first.getAzimuth()) - 90); deltaY = -(float) (first.getLeft() * Math.cos(galleryWidthAngle) * scale); deltaX = (float) (first.getLeft() * Math.sin(galleryWidthAngle) * scale); } else { // each other by the bisector galleryWidthAngle = Math.toRadians(getAzimuthInDegrees(Math.abs(prevLeg.getAzimuth()+second.getAzimuth())/2 - 90)); deltaY = - (float) (first.getLeft() * Math.cos(galleryWidthAngle) * scale); deltaX = (float) (first.getLeft() * Math.sin(galleryWidthAngle) * scale); } canvas.drawCircle(mapCenterMoveX + first.getX() + deltaX, mapCenterMoveY + first.getY() + deltaY, MEASURE_POINT_RADIUS, polygonWidthPaint); } // right if (first.getRight() != null && first.getRight()> 0) { if (prevLeg == null) { // first point by 90 degree left galleryWidthAngle = Math.toRadians(getAzimuthInDegrees(first.getAzimuth()) + 90); deltaY = -(float) (first.getRight() * Math.cos(galleryWidthAngle) * scale); deltaX = (float) (first.getRight() * Math.sin(galleryWidthAngle) * scale); } else { // each other by the bisector galleryWidthAngle = Math.toRadians(getAzimuthInDegrees(Math.abs(prevLeg.getAzimuth()+second.getAzimuth())/2 + 90)); deltaY = - (float) (first.getLeft() * Math.cos(galleryWidthAngle) * scale); deltaX = (float) (first.getLeft() * Math.sin(galleryWidthAngle) * scale); } canvas.drawCircle(mapCenterMoveX + first.getX() + deltaX, mapCenterMoveY + first.getY() + deltaY, MEASURE_POINT_RADIUS, polygonWidthPaint); } processedLegs.add(l.getId()); } } } // borders //top canvas.drawLine(spacing, spacing, maxX - spacing, spacing, overlayPaint); //right canvas.drawLine(maxX - spacing, spacing, maxX - spacing, maxY - spacing, overlayPaint); // bottom canvas.drawLine(spacing, maxY - spacing, maxX - spacing, maxY - spacing, overlayPaint); //left canvas.drawLine(spacing, maxY - spacing, spacing, spacing, overlayPaint); // north Point northCenter = new Point(maxX - 20, 30); canvas.drawLine(northCenter.x, northCenter.y, northCenter.x + 10, northCenter.y + 10, overlayPaint); canvas.drawLine(northCenter.x + 10, northCenter.y + 10, northCenter.x, northCenter.y - 20, overlayPaint); canvas.drawLine(northCenter.x, northCenter.y - 20, northCenter.x - 10, northCenter.y + 10, overlayPaint); canvas.drawLine(northCenter.x - 10, northCenter.y + 10, northCenter.x, northCenter.y, overlayPaint); canvas.drawText("N", northCenter.x + 5, northCenter.y - 10, overlayPaint); canvas.drawText("x" + (int)scale, 20, 25, overlayPaint); } catch (Exception e) { Log.e(Constants.LOG_TAG_UI, "Failed to draw map activity", e); UIUtilities.showNotification(R.string.error); } } public void zoomOut() { scale invalidate(); } public void zoomIn() { scale++; invalidate(); } public boolean canZoomOut() { return scale > 1; } public boolean canZoomIn() { return scale < 50; } public void resetMove(float aX, float aY) { initialMoveX = aX; initialMoveY = aY; } public void move(float x, float y) { mapCenterMoveX += (x - initialMoveX); initialMoveX = x; mapCenterMoveY += (y - initialMoveY); initialMoveY = y; invalidate(); } public byte[] getPngDump() { // render Bitmap returnedBitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(),Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(returnedBitmap); Drawable bgDrawable = this.getBackground(); if (bgDrawable!=null) { bgDrawable.draw(canvas); } draw(canvas); // crop borders etc returnedBitmap = Bitmap.createBitmap(returnedBitmap, 30, 30, this.getWidth() - 60, this.getHeight() - 60); // return ByteArrayOutputStream buff = new ByteArrayOutputStream(); returnedBitmap.compress(Bitmap.CompressFormat.PNG, 50, buff); return buff.toByteArray(); } private Float getAzimuthInDegrees(Float anAzimuth) { if (null == anAzimuth) { return null; } if (Option.UNIT_DEGREES.equals(Options.getOptionValue(Option.CODE_AZIMUTH_UNITS))) { return anAzimuth; } else { // convert from grads to degrees return anAzimuth * Constants.GRAD_TO_DEC; } } private Float getSlopeInDegrees(Float aSlope) { if (null == aSlope) { return null; } if (Option.UNIT_DEGREES.equals(Options.getOptionValue(Option.CODE_SLOPE_UNITS))) { return aSlope; } else { // convert from grads to degrees return aSlope * Constants.GRAD_TO_DEC; } } private Float applySlopeToDistance(Float aDistance, Float aSlope) { if (aSlope == null) { return aDistance; } return Double.valueOf(aDistance * Math.cos(Math.toRadians(aSlope))).floatValue(); } }
package com.ilscipio.scipio.ce.service.event; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.ofbiz.base.config.GenericConfigException; import org.ofbiz.base.start.Config; import org.ofbiz.base.start.ExtendedStartupLoader; import org.ofbiz.base.start.StartupException; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.DelegatorFactory; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.util.EntityQuery; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.service.ModelService; import org.ofbiz.service.ServiceDispatcher; import org.ofbiz.service.ServiceUtil; import org.ofbiz.service.config.ServiceConfigUtil; import org.ofbiz.service.config.model.Engine; import org.ofbiz.service.config.model.ServiceEngine; import org.ofbiz.service.engine.XMLRPCClientEngine; /** * Service startup events. * <p> * Supports command-line-level startup service invocation request in the form (default mode: async): * <ul> * <li><code>./ant start -Dscipio.startup.service=serviceName -Dscipio.startup.service.mode=[sync|async] -Dscipio.startup.service.params.userLogin=system -Dscipio.startup.service.params.arg1=val1 -Dscipio.startup.service.params.arg2=val2</code></li> * <li><code>./ant start -Dscipio.startup.service.1=serviceName -Dscipio.startup.service.1.mode=[sync|async] -Dscipio.startup.service.1.params.arg1=val1 -Dscipio.startup.service.1.params.arg2=val2 * -Dscipio.startup.service.2=serviceName -Dscipio.startup.service.2.mode=[sync|async] -Dscipio.startup.service.2.params.arg1=val1 -Dscipio.startup.service.2.params.arg2=val2</code></li> * </ul> * For specific user login pass the userLoginId to the params.userLogin parameter (it will be converted to GenericValue). * <p> * For advanced multi-service control, create a new group service instead. * <p> * Test cases: * <ul> * <li><code> * ./ant start -Dscipio.startup.service=echoService -Dscipio.startup.service.params.arg1a=val1a -Dscipio.startup.service.params.arg2a=val2a * -Dscipio.startup.service.1=echoService -Dscipio.startup.service.1.params.arg1b=val1b -Dscipio.startup.service.1.params.arg2b=val2b * -Dscipio.startup.service.2=echoService -Dscipio.startup.service.2.mode=sync -Dscipio.startup.service.2.params.arg1c=val1c -Dscipio.startup.service.2.params.arg2c=val2c * -Dscipio.startup.service.3=echoService -Dscipio.startup.service.3.mode=async -Dscipio.startup.service.3.params.arg1d=val1d -Dscipio.startup.service.3.params.arg2d=val2d * </code></li> * </ul> */ public class ServiceStartupEvents implements ExtendedStartupLoader { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); @Override public void load(Config config, String[] args) throws StartupException { } @Override public void start() throws StartupException { } @Override public void unload() throws StartupException { } @Override public void execOnRunning() throws StartupException { execCheckEngines(); execStartupServiceAsync(); } protected void execCheckEngines() throws StartupException { try { for(ServiceEngine serviceEngine : ServiceConfigUtil.getServiceConfig().getServiceEngines()) { for(Engine engine : serviceEngine.getEngines()) { if (XMLRPCClientEngine.class.getName().equals(engine.getClassName())) { String urlParam = engine.getParameterValue("url"); if (UtilValidate.isEmpty(urlParam)) { Debug.logError("Missing 'url' parameter in service engine config for XML-RPC engine '" + engine.getName() + "'", module); continue; } try { URL url = new URL(urlParam); if (!"localhost".equals(url.getHost()) && !"127.0.0.1".equals(url.getHost())) { Debug.logWarning("\n" + "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + "\nScipio: WARNING: Insecure XML-RPC service engine configuration!" + "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + "\n" + "\nScipio has detected you have defined the following XML-RPC" + " service engine with a non-local host, '" + url.getHost() + "' (serviceengine.xml):" + "\n" + "\n name: " + engine.getName() + "\n class: " + engine.getClassName() + "\n url: " + urlParam + "\n" + "\nThis configuration is insecure; the XML-RPC implementation is based on" + " Apache XML-RPC (https://ws.apache.org/xmlrpc/), which has not been maintained since" + " 2010 and contains security issues. It is only safe enough to use on localhost addresses." + " Please change to a different service engine implementation for network communication." + "\n" + "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + "\n", module); } } catch (MalformedURLException e) { Debug.logError("Malformed 'url' parameter in service engine config for XML-RPC engine '" + engine.getName() + "': " + urlParam + ": " + e.getMessage(), module); } } } } } catch (GenericConfigException e) { Debug.logError("Unable to read service engine config: " + e.getMessage(), module); } } protected boolean execStartupServiceAsync() throws StartupException { // single service invocation String startupService = System.getProperty("scipio.startup.service"); if (UtilValidate.isNotEmpty(startupService) || UtilValidate.isNotEmpty(System.getProperty("scipio.startup.service.1"))) { LocalDispatcher dispatcher = getDispatcher(); if (dispatcher == null) { Debug.logError("Scipio: Cannot exec startup service; could not get dispatcher", module); return false; } Map<String, String> servParams = UtilProperties.getPropertiesWithPrefix(System.getProperties(), "scipio.startup.service.params."); String mode = System.getProperty("scipio.startup.service.mode"); execStartupService(dispatcher, startupService, servParams, mode, null); // multiple service invocation if (UtilValidate.isNotEmpty(System.getProperty("scipio.startup.service.1"))) { Map<String, String> startupServices = UtilProperties.getPropertiesMatching(System.getProperties(), Pattern.compile("^scipio\\.startup\\.service\\.(\\d+)$"), true); List<Integer> serviceKeys = new ArrayList<>(); for(String key : startupServices.keySet()) serviceKeys.add(Integer.parseInt(key)); Collections.sort(serviceKeys); for(Integer key : serviceKeys) { startupService = startupServices.get(key.toString()); servParams = UtilProperties.getPropertiesWithPrefix(System.getProperties(), "scipio.startup.service." + key + ".params."); mode = System.getProperty("scipio.startup.service." + key + ".mode"); execStartupService(dispatcher, startupService, servParams, mode, key); } } } return false; } protected LocalDispatcher getDispatcher() { return ServiceDispatcher.getLocalDispatcher("default", DelegatorFactory.getDelegator("default")); } protected Map<String, Object> execStartupService(LocalDispatcher dispatcher, String serviceName, Map<String, ?> context, String mode, Integer serviceIndex) { try { if (!"sync".equals(mode) && !"async".equals(mode)) mode = "async"; if (Debug.infoOn()) { final String indexMsg = (serviceIndex != null) ? " [" + serviceIndex + "]" : ""; Debug.logInfo("Scipio: Running startup service '" + serviceName + "'" + indexMsg + " (" + mode + "), params: " + context, module); } String userLoginAuthId = null; if (context.get("userLogin") instanceof String) { userLoginAuthId = (String) context.get("userLogin"); context.remove("userLogin"); } Map<String, Object> ctx = dispatcher.getDispatchContext().makeValidContext(serviceName, ModelService.IN_PARAM, context); if (UtilValidate.isNotEmpty(userLoginAuthId)) { GenericValue userLogin = EntityQuery.use(dispatcher.getDelegator()).from("UserLogin") .where("userLoginId", userLoginAuthId).queryOne(); if (userLogin == null) { Debug.logWarning("Scipio: Could not find UserLogin '" + userLoginAuthId + "' to run startup service '" + serviceName + "'", module); } else { ctx.put("userLogin", userLogin); } } if ("async".equals(mode)) { dispatcher.runAsync(serviceName, ctx, false); return null; } else { Map<String, Object> result = dispatcher.runSync(serviceName, ctx); if (ServiceUtil.isError(result)) { String msg = ServiceUtil.getErrorMessage(result); if (msg != null && !msg.isEmpty()) { Debug.logError("Scipio: Ran startup service '" + serviceName + "', status: " + result.get(ModelService.RESPONSE_MESSAGE) + ", message: " + msg, module); } else { Debug.logError("Scipio: Ran startup service '" + serviceName + "', status: " + result.get(ModelService.RESPONSE_MESSAGE), module); } } else if (ServiceUtil.isFailure(result)) { String msg = ServiceUtil.getErrorMessage(result); if (msg != null && !msg.isEmpty()) { Debug.logWarning("Scipio: Ran startup service '" + serviceName + "', status: " + result.get(ModelService.RESPONSE_MESSAGE) + ", message: " + msg, module); } else { Debug.logWarning("Scipio: Ran startup service '" + serviceName + "', status: " + result.get(ModelService.RESPONSE_MESSAGE), module); } } else { String msg = ServiceUtil.getSuccessMessage(result); if (msg != null && !msg.isEmpty()) { Debug.logInfo("Scipio: Ran startup service '" + serviceName + "', status: " + result.get(ModelService.RESPONSE_MESSAGE) + ", message: " + msg, module); } else { Debug.logInfo("Scipio: Ran startup service '" + serviceName + "', status: " + result.get(ModelService.RESPONSE_MESSAGE), module); } } return result; } } catch (GenericServiceException | GenericEntityException e) { Debug.logError("Scipio: Error running startup service '" + serviceName + "': " + e.getMessage(), module); return ServiceUtil.returnError(e.getMessage()); } } }
package com.astoev.cave.survey.util; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.util.Log; import com.astoev.cave.survey.Constants; import com.astoev.cave.survey.model.Point; import com.astoev.cave.survey.model.Project; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; public class FileStorageUtil { private static final String EXCEL_FILE_EXTENSION = ".xls"; private static final String PNG_FILE_EXTENSION = ".png"; private static final String NAME_DELIMITER = "_"; public static final String JPG_FILE_EXTENSION = ".jpg"; public static final String POINT_PREFIX = "Point"; public static final String MAP_PREFIX = "Map"; private static final String CAVE_SURVEY_FOLDER = "CaveSurvey"; private static final String TIME_PATTERN = "yyyyMMdd"; private static final int MIN_REQUIRED_STORAGE = 50 * 1024; @SuppressLint("SimpleDateFormat") public static String addProjectExport(Project aProject, InputStream aStream) { File projectHome = getProjectHome(aProject.getName()); if (projectHome == null) { return null; } FileOutputStream out = null; try { int index = 1; String exportName; File exportFile; SimpleDateFormat dateFormat = new SimpleDateFormat(TIME_PATTERN); // ensure unique name while (true) { exportName = aProject.getName() + NAME_DELIMITER + dateFormat.format(new Date()) + NAME_DELIMITER + index; exportFile = new File(projectHome, exportName + EXCEL_FILE_EXTENSION); if (exportFile.exists()) { index++; } else { break; } } Log.i(Constants.LOG_TAG_SERVICE, "Store to " + exportFile.getAbsolutePath()); out = new FileOutputStream(exportFile); IOUtils.copy(aStream, out); return exportFile.getAbsolutePath(); } catch (Exception e) { Log.e(Constants.LOG_TAG_UI, "Failed to store export", e); return null; } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(aStream); } } /** * Helper method that obtains Picture's directory (api level 8) * * @param projectName - project's name used as an album * @return File created */ @TargetApi(Build.VERSION_CODES.FROYO) private static File getDirectoryPicture(String projectName){ return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), projectName); } /** * Helper method that adds project's media content to public external storage * * @param contextArg - context * @param aProject - project owner * @param filePrefixArg - file prefix * @param byteArrayArg - media content as a byte array * @return String for the file name created * @throws Exception */ public static String addProjectMedia(Context contextArg, Project aProject, String filePrefixArg, byte[] byteArrayArg) throws Exception { File pictureFile = createPictureFile(contextArg, aProject.getName(), filePrefixArg, PNG_FILE_EXTENSION); OutputStream os = null; try { os = new FileOutputStream(pictureFile); os.write(byteArrayArg); } catch (Exception e) { Log.e(Constants.LOG_TAG_SERVICE, "Unable to write file: " + pictureFile.getAbsolutePath(), e); throw e; } finally { closeOutputStream(os); } Log.i(Constants.LOG_TAG_SERVICE, "Just wrote: " + pictureFile.getAbsolutePath()); // broadcast that picture was added to the project notifyPictureAddedToGalery(contextArg, pictureFile); return pictureFile.getAbsolutePath(); } /** * Helper method that checks if we use a public folder to store files. * * @return if api version 8+ return true, otherwise false */ // public static boolean isPublicFolder(){ // return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO); /** * Helper method that creates a prefix name for picture files based on Point objects * * @param pointArg - parent point * @return */ public static String getFilePrefixForPicture(Point pointArg){ return POINT_PREFIX + NAME_DELIMITER + pointArg.getName(); } /** * Helper method to create a picture file. The file will be named <prefix>-<date_format><extension>. The * file is stored in public folder based on the project's name. ../CaveSurvay/<project_name>/<file> * * @param contextArg - context to use * @param projectName - project's name * @param filePrefix - file prefix * @param fileExtensionArg - extension for the file. * @return * @throws Exception */ @SuppressLint("SimpleDateFormat") public static File createPictureFile(Context contextArg, String projectName, String filePrefix, String fileExtensionArg) throws Exception { // Store in file system File destinationDir = getProjectHome(projectName); if (destinationDir == null){ Log.e(Constants.LOG_TAG_SERVICE, "Directory not created"); throw new Exception(); } Log.i(Constants.LOG_TAG_SERVICE, "Will write at: " + destinationDir.getAbsolutePath()); // build filename Date date = new Date(); SimpleDateFormat df = new SimpleDateFormat(Constants.DATE_FORMAT); StringBuilder fileName = new StringBuilder(filePrefix); fileName.append(NAME_DELIMITER); fileName.append(df.format(date)); fileName.append(fileExtensionArg); return new File(destinationDir, fileName.toString()); }// end of createPictureFile public static File getProjectHome(String projectName) { File storageHome = getStorageHome(); if (storageHome == null) { return null; } //TODO if there is a problem with spaces in project's name substitute spaces with "_" File projectHome = new File(storageHome, projectName); if (!projectHome.exists()) { if (!projectHome.mkdirs()) { Log.e(Constants.LOG_TAG_UI, "Failed to create folder " + projectHome.getAbsolutePath()); return null; } Log.i(Constants.LOG_TAG_SERVICE, "Project home created"); } return projectHome; } @SuppressWarnings("deprecation") private static File getStorageHome() { if (!isExternalStorageWritable()) { Log.e(Constants.LOG_TAG_UI, "Storage unavailable"); return null; } File extdir = Environment.getExternalStorageDirectory(); StatFs stats = new StatFs(extdir.getAbsolutePath()); long availableBytes = stats.getAvailableBlocks() * (long)stats.getBlockSize(); if (availableBytes < MIN_REQUIRED_STORAGE) { Log.e(Constants.LOG_TAG_UI, "No space left"); return null; } File storageHome = new File(Environment.getExternalStorageDirectory() + File.separator + CAVE_SURVEY_FOLDER); if (!storageHome.exists()) { if (!storageHome.mkdirs()) { Log.e(Constants.LOG_TAG_UI, "Failed to create folder " + storageHome.getAbsolutePath()); return null; } Log.i(Constants.LOG_TAG_SERVICE, "Export folder created"); } return storageHome; } /** * Helper method to close safely an OutputStream * * @param os - output stream instance */ public static void closeOutputStream(OutputStream os){ if (os != null){ try { os.close(); } catch (IOException e) { Log.i(Constants.LOG_TAG_SERVICE, "Error while closing output stream"); } } } /** * Helper method that checks if the external storage is available for writing * * @return true if available for writing, otherwise false */ public static boolean isExternalStorageWritable(){ String state = Environment.getExternalStorageState(); return (Environment.MEDIA_MOUNTED.equals(state)); } /** * Helper method that invokes system's media scanner to add a picture to Media Provider's database * * @param contextArg - context to use to send a broadcast * @param addedFileArg - the newly created file to notify for */ public static void notifyPictureAddedToGalery(Context contextArg, File addedFileArg){ if (addedFileArg == null){ return; } Uri contentUri = Uri.fromFile(addedFileArg); notifyPictureAddedToGalery(contextArg, contentUri); } /** * Helper method to broadcast a message that a picture is added * * @param contextArg - context to use * @param addedFileUriArg - uri to picture */ public static void notifyPictureAddedToGalery(Context contextArg, Uri addedFileUriArg){ if (addedFileUriArg == null){ return; } Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); mediaScanIntent.setData(addedFileUriArg); contextArg.sendBroadcast(mediaScanIntent); } /** * Helper method to check if file exists * * @param fileNameArg - file name * @return true if the file exists, otherwise false */ public static final boolean isFileExists(String fileNameArg){ if (fileNameArg == null){ return false; } File file = new File(fileNameArg); return file.exists(); } }
package dungeon_crawler.core; import clojure.lang.RT; import clojure.lang.Symbol; import com.badlogic.gdx.backends.iosrobovm.*; import com.badlogic.gdx.*; import org.robovm.apple.foundation.*; import org.robovm.apple.uikit.*; public class IOSLauncher extends IOSApplication.Delegate { protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); RT.var("clojure.core", "require").invoke(Symbol.intern("dungeon-crawler.core")); try { Game game = (Game) RT.var("dungeon-crawler.core", "dungeon-crawler").deref(); return new IOSApplication(game, config); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, IOSLauncher.class); pool.close(); } }
package fr.paris.lutece.portal.web.role; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import fr.paris.lutece.portal.business.role.Role; import fr.paris.lutece.portal.business.role.RoleHome; import fr.paris.lutece.portal.service.message.AdminMessage; import fr.paris.lutece.portal.service.message.AdminMessageService; import fr.paris.lutece.portal.service.role.RoleRemovalListenerService; import fr.paris.lutece.portal.service.template.AppTemplateService; import fr.paris.lutece.portal.web.admin.AdminFeaturesPageJspBean; import fr.paris.lutece.portal.web.constants.Messages; import fr.paris.lutece.util.html.HtmlTemplate; import fr.paris.lutece.util.string.StringUtil; import fr.paris.lutece.util.url.UrlItem; /** * JspBean for Role management */ public class RoleJspBean extends AdminFeaturesPageJspBean { // Constant // Right public static final String RIGHT_ROLES_MANAGEMENT = "CORE_ROLES_MANAGEMENT"; // Markers private static final String MARK_ROLES_LIST = "roles_list"; private static final String MARK_ROLE = "role"; // Parameters private static final String PARAMETER_PAGE_ROLE = "role"; private static final String PARAMETER_PAGE_ROLE_DESCRIPTION = "role_description"; // Templates private static final String TEMPLATE_MANAGE_ROLES = "admin/role/manage_roles.html"; private static final String TEMPLATE_PAGE_ROLE_MODIFY = "admin/role/modify_page_role.html"; private static final String TEMPLATE_CREATE_PAGE_ROLE = "admin/role/create_page_role.html"; // Jsp private static final String PATH_JSP = "jsp/admin/role/"; private static final String JSP_REMOVE_ROLE = "DoRemovePageRole.jsp"; // Properties private static final String PROPERTY_PAGE_TITLE_CREATE_ROLE = "portal.role.create_role.pageTitle"; private static final String PROPERTY_PAGE_TITLE_MODIFY_ROLE = "portal.role.modify_role.pageTitle"; // Message private static final String MESSAGE_ROLE_EXIST = "portal.role.message.roleexist"; private static final String MESSAGE_ROLE_FORMAT = "portal.role.message.roleformat"; private static final String MESSAGE_CONFIRM_REMOVE = "portal.role.message.confirmRemoveRole"; private static final String MESSAGE_CANNOT_REMOVE_ROLE = "portal.role.message.cannotRemoveRole"; /** * Creates a new RoleJspBean object. */ public RoleJspBean( ) { } /** * Returns Page Role management form * @param request The Http request * @return Html form */ public String getManagePageRole( HttpServletRequest request ) { setPageTitleProperty( null ); Map<String, Object> model = new HashMap<String, Object>( ); model.put( MARK_ROLES_LIST, RoleHome.findAll( ) ); HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_MANAGE_ROLES, getLocale( ), model ); return getAdminPage( template.getHtml( ) ); } /** * Insert a new PageRole * @param request The HTTP request * @return String The html code page */ public String getCreatePageRole( HttpServletRequest request ) { setPageTitleProperty( PROPERTY_PAGE_TITLE_CREATE_ROLE ); HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_CREATE_PAGE_ROLE, getLocale( ) ); return getAdminPage( template.getHtml( ) ); } /** * Create PageRole * @param request The HTTP request * @return String The url page */ public String doCreatePageRole( HttpServletRequest request ) { String strPageRole = request.getParameter( PARAMETER_PAGE_ROLE ); String strPageRoleDescription = request.getParameter( PARAMETER_PAGE_ROLE_DESCRIPTION ); // Mandatory field if ( strPageRole.equals( "" ) || strPageRoleDescription.equals( "" ) ) { return AdminMessageService.getMessageUrl( request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP ); } // Check if code is valid if ( !StringUtil.checkCodeKey( strPageRole ) ) { return AdminMessageService.getMessageUrl( request, MESSAGE_ROLE_FORMAT, AdminMessage.TYPE_STOP ); } // Check if role exist if ( RoleHome.findExistRole( strPageRole ) ) { return AdminMessageService.getMessageUrl( request, MESSAGE_ROLE_EXIST, AdminMessage.TYPE_STOP ); } Role role = new Role( ); role.setRole( strPageRole ); role.setRoleDescription( strPageRoleDescription ); RoleHome.create( role ); return getHomeUrl( request ); } /** * * @param request The HTTP request * @return String The html code page */ public String getModifyPageRole( HttpServletRequest request ) { setPageTitleProperty( PROPERTY_PAGE_TITLE_MODIFY_ROLE ); Map<String, Object> model = new HashMap<String, Object>( ); String strPageRole = (String) request.getParameter( PARAMETER_PAGE_ROLE ); model.put( MARK_ROLE, RoleHome.findByPrimaryKey( strPageRole ) ); HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_PAGE_ROLE_MODIFY, getLocale( ), model ); return getAdminPage( template.getHtml( ) ); } /** * Modify PageRole * @param request The HTTP request * @return String The url page */ public String doModifyPageRole( HttpServletRequest request ) { String strPageRole = request.getParameter( PARAMETER_PAGE_ROLE ); String strPageRoleDescription = request.getParameter( PARAMETER_PAGE_ROLE_DESCRIPTION ); // Mandatory field if ( strPageRoleDescription.equals( "" ) ) { return AdminMessageService.getMessageUrl( request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP ); } Role role = new Role( ); role.setRole( strPageRole ); role.setRoleDescription( strPageRoleDescription ); RoleHome.update( role ); return getHomeUrl( request ); } /** * confirm Delete PageRole * @param request The HTTP request * @return String The html code page */ public String getRemovePageRole( HttpServletRequest request ) { UrlItem url = new UrlItem( PATH_JSP + JSP_REMOVE_ROLE + "?role=" + request.getParameter( PARAMETER_PAGE_ROLE ) ); return AdminMessageService.getMessageUrl( request, MESSAGE_CONFIRM_REMOVE, url.getUrl( ), AdminMessage.TYPE_CONFIRMATION ); } /** * Delete PageRole * @param request The HTTP request * @return String The url page */ public String doRemovePageRole( HttpServletRequest request ) { String strPageRole = (String) request.getParameter( PARAMETER_PAGE_ROLE ); ArrayList<String> listErrors = new ArrayList<String>( ); if ( !RoleRemovalListenerService.getService( ).checkForRemoval( strPageRole, listErrors, getLocale( ) ) ) { String strCause = AdminMessageService.getFormattedList( listErrors, getLocale( ) ); Object[] args = { strCause }; return AdminMessageService.getMessageUrl( request, MESSAGE_CANNOT_REMOVE_ROLE, args, AdminMessage.TYPE_STOP ); } else { RoleHome.remove( strPageRole ); } return getHomeUrl( request ); } }
package eu.ydp.empiria.player.client.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StackMap<K, V> extends TreeMap<K, V> { private static final long serialVersionUID = -5203287630904024114L; protected List<K> keys; protected List<V> values; public StackMap(){ super(); keys = new ArrayList<K>(); values = new ArrayList<V>(); } @Override public V put(K key, V value){ keys.add(key); values.add(value); return super.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> m){ keys.addAll(m.keySet()); values.addAll(m.values()); super.putAll(m); } @Override public void clear(){ keys.clear(); values.clear(); super.clear(); } public List<K> getKeys(){ return keys; } public List<V> getValues(){ return values; } }
package com.interview.tree; import com.interview.bits.NextPowerOf2; public class SegmentTreeMinimumRangeQuery { public int[] createTree(int input[]){ NextPowerOf2 np2 = new NextPowerOf2(); //if input len is pow of then size of //segment tree is 2*len -1 otherwisze //size of segment tree is next (pow of 2 for len) * 2 -1 int nextPowOfTwo = np2.nextPowerOf2(input.length); int segmentTree[] = new int[nextPowOfTwo*2 -1]; for(int i=0; i < segmentTree.length; i++){ segmentTree[i] = Integer.MAX_VALUE; } constructMinSegmentTreeTree(segmentTree,input,0,input.length-1,0); return segmentTree; } private void constructMinSegmentTreeTree(int segmentTree[], int input[], int low, int high,int pos){ if(low == high){ segmentTree[pos] = input[low]; return; } int mid = (low + high)/2; constructMinSegmentTreeTree(segmentTree,input,low,mid,2*pos+1); constructMinSegmentTreeTree(segmentTree,input,mid+1,high,2*pos+2); segmentTree[pos] = Math.min(segmentTree[2*pos+1], segmentTree[2*pos+2]); } public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len){ return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0); } private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos){ if(qlow <= low && qhigh >= high){ return segmentTree[pos]; } if(qlow > high || qhigh < low){ return Integer.MAX_VALUE; } int mid = (low+high)/2; return Math.min(rangeMinimumQuery(segmentTree,low,mid,qlow,qhigh,2*pos+1), rangeMinimumQuery(segmentTree,mid+1,high,qlow,qhigh,2*pos+2)); } /** * Segment tree for given example * -1 * 0 -1 * 0 2 1 -1 * 0 3 4 2 1 6 max max * */ public static void main(String args[]){ SegmentTreeMinimumRangeQuery st = new SegmentTreeMinimumRangeQuery(); int input[] = {0,3,4,2,1,6,-1}; int segTree[] = st.createTree(input); assert 0 == st.rangeMinimumQuery(segTree, 0, 3, input.length); assert 1 == st.rangeMinimumQuery(segTree, 1, 5, input.length); assert -1 == st.rangeMinimumQuery(segTree, 1, 6, input.length); assert 2 == st.rangeMinimumQuery(segTree, 1, 3, input.length); } }
package org.spine3.base; import com.google.common.reflect.TypeToken; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import org.junit.Test; import org.spine3.test.types.Task; import java.lang.reflect.Type; import java.text.ParseException; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.spine3.base.Stringifiers.mapStringifier; /** * @author Illia Shepilov */ @SuppressWarnings({"SerializableInnerClassWithNonSerializableOuterClass", "SerializableNonStaticInnerClassWithoutSerialVersionUID"}) // It is OK for test methods. public class MapStringifierShould { @Test public void convert_string_to_map() throws ParseException { final String rawMap = "1\\:1972-01-01T10:00:20.021-05:00"; final Type type = new TypeToken<Map<Long, Timestamp>>(){}.getType(); final Stringifier<Map<Long, Timestamp>> stringifier = mapStringifier(Long.class, Timestamp.class); StringifierRegistry.getInstance() .register(stringifier, type); final Map<Long, Timestamp> actualMap = Stringifiers.fromString(rawMap, type); final Map<Long, Timestamp> expectedMap = newHashMap(); expectedMap.put(1L, Timestamps.parse("1972-01-01T10:00:20.021-05:00")); assertThat(actualMap, is(expectedMap)); } @Test public void convert_map_to_string() { final Map<String, Integer> mapToConvert = createTestMap(); final Type type = new TypeToken<Map<String, Integer>>(){}.getType(); final Stringifier<Map<String, Integer>> stringifier = mapStringifier(String.class, Integer.class); StringifierRegistry.getInstance() .register(stringifier, type); final String convertedMap = Stringifiers.toString(mapToConvert, type); assertEquals(mapToConvert.toString(), convertedMap); } @Test(expected = IllegalConversionArgumentException.class) public void throw_exception_when_passed_parameter_does_not_match_expected_format() { final String incorrectRawMap = "first\\:1\\,second\\:2"; final Type type = new TypeToken<Map<Integer, Integer>>(){}.getType(); final Stringifier<Map<Integer, Integer>> stringifier = mapStringifier(Integer.class, Integer.class); StringifierRegistry.getInstance() .register(stringifier, type); Stringifiers.fromString(incorrectRawMap, type); } @Test(expected = MissingStringifierException.class) public void throw_exception_when_required_stringifier_is_not_found() { final Type type = new TypeToken<Map<Long, Task>>(){}.getType(); Stringifiers.fromString("1\\:1", type); } @Test(expected = IllegalConversionArgumentException.class) public void throw_exception_when_occurred_exception_during_conversion() { final Type type = new TypeToken<Map<Task, Long>>(){}.getType(); final Stringifier<Map<Task, Long>> stringifier = mapStringifier(Task.class, Long.class); StringifierRegistry.getInstance() .register(stringifier, type); Stringifiers.fromString("first\\:first\\:first", type); } @Test(expected = IllegalConversionArgumentException.class) public void throw_exception_when_key_value_delimiter_is_wrong() { final Type type = new TypeToken<Map<Long, Long>>(){}.getType(); final Stringifier<Map<Long, Long>> stringifier = mapStringifier(Long.class, Long.class); StringifierRegistry.getInstance() .register(stringifier, type); Stringifiers.fromString("1\\-1", type); } @Test public void convert_map_with_custom_delimiter() { final String rawMap = "first\\:1\\|second\\:2\\|third\\:3"; final Type type = new TypeToken<Map<Long, Task>>() {}.getType(); final Stringifier<Map<String, Integer>> stringifier = mapStringifier(String.class, Integer.class, "|"); StringifierRegistry.getInstance() .register(stringifier, type); final Map<String, Integer> convertedMap = Stringifiers.fromString(rawMap, type); assertThat(convertedMap, is(createTestMap())); } private static Map<String, Integer> createTestMap() { final Map<String, Integer> expectedMap = newHashMap(); expectedMap.put("first", 1); expectedMap.put("second", 2); expectedMap.put("third", 3); return expectedMap; } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.util.Range; @TeleOp(name="TeleOp w/ Arm") public class TeleOpWithArm extends OpMode{ private Bot bot = new Bot(); // supposedly the force of gravity according to the best source // the robot that we made... meaning... AI HAS TAKEN OVER private final double g = .3d; private boolean pushed = false; // Y - gamepad 2 private boolean pivotLock = false; // B - gamepad 2 private boolean armLock = false; public void init() { bot.init(hardwareMap); } public void loop() { if (!pushed) { if (gamepad1.y && gamepad2.y) { bot.unfold(); pushed = !pushed; } } if (gamepad2.y) { pivotLock = !pivotLock; telemetry.addData("pivotLock: ", pivotLock); } /*if (gamepad2.b) { armLock = !armLock; telemetry.addData("armLock: ", armLock); }*/ double drive = -gamepad1.right_stick_y / 2, turn = gamepad1.right_stick_x / 2; double straight = gamepad1.right_trigger / 2, back = gamepad1.left_trigger / 2; /*if(gamepad1.left_trigger > 0) { bot.jewel.setPosition(bot.jewelPosition - 0.05); } else if(gamepad1.right_trigger > 0) { bot.jewel.setPosition(bot.jewelPosition + 0.05); }*/ // whole arm motor double armMovement = gamepad2.right_stick_y/6; if(!armLock) { bot.arm.setPower(armMovement); } // arm pivot server double pivot = gamepad2.left_stick_y/3; if(!pivotLock) { bot.pivot.setPosition(bot.pivotPosition + (pivot / 5)); bot.pivotPosition = bot.pivot.getPosition(); } // open arm close arm boolean open = gamepad2.a, close = gamepad2.x; if(close) { bot.clamp.setPosition(0); } else if(open) { bot.clamp.setPosition(.5); } // left trigger = drop double leftTrigger = gamepad2.left_trigger; // right trigger = bring back double rightTrigger = gamepad2.right_trigger; if(leftTrigger > rightTrigger) { bot.arm2.setPower(leftTrigger / 3 * -1); } else { bot.arm2.setPower(rightTrigger / 3); } if(straight > 0) { bot.ld.setPower(straight); bot.rd.setPower(straight); telemetry.addData("driving straight: ", "true"); } else if(back > 0) { bot.ld.setPower(back * -1); bot.rd.setPower(back * -1); telemetry.addData("driving backwards: ", "true"); } else { bot.ld.setPower(Range.clip(drive + turn, -1d, 1d)); bot.rd.setPower(Range.clip(drive - turn, -1d, 1d)); telemetry.addData("left drive power: ", bot.ld.getPowerFloat()); telemetry.addData("right drive power: ", bot.rd.getPowerFloat()); } if(gamepad1.y) { bot.jewel.setPosition(.75); } else if(gamepad1.b) { bot.jewel.setPosition(.15); } } }
package org.neo4j.backup; import static org.neo4j.backup.BackupServer.FRAME_LENGTH; import static org.neo4j.backup.BackupServer.PROTOCOL_VERSION; import org.jboss.netty.buffer.ChannelBuffer; import org.neo4j.com.Client; import org.neo4j.com.ObjectSerializer; import org.neo4j.com.Protocol; import org.neo4j.com.RequestContext; import org.neo4j.com.RequestType; import org.neo4j.com.Response; import org.neo4j.com.StoreWriter; import org.neo4j.com.TargetCaller; import org.neo4j.com.ToNetworkStoreWriter; import org.neo4j.kernel.impl.nioneo.store.StoreId; import org.neo4j.kernel.logging.Logging; class BackupClient extends Client<TheBackupInterface> implements TheBackupInterface { public BackupClient( String hostNameOrIp, int port, Logging logging, StoreId storeId ) { super( hostNameOrIp, port, logging, storeId, FRAME_LENGTH, PROTOCOL_VERSION, 40 * 1000, Client.DEFAULT_MAX_NUMBER_OF_CONCURRENT_CHANNELS_PER_CLIENT, Client.DEFAULT_MAX_NUMBER_OF_CONCURRENT_CHANNELS_PER_CLIENT, FRAME_LENGTH ); } public Response<Void> fullBackup( StoreWriter storeWriter ) { return sendRequest( BackupRequestType.FULL_BACKUP, RequestContext.EMPTY, Protocol.EMPTY_SERIALIZER, new Protocol.FileStreamsDeserializer( storeWriter ) ); } public Response<Void> incrementalBackup( RequestContext context ) { return sendRequest( BackupRequestType.INCREMENTAL_BACKUP, context, Protocol.EMPTY_SERIALIZER, Protocol.VOID_DESERIALIZER ); } @Override protected boolean shouldCheckStoreId( RequestType<TheBackupInterface> type ) { return type != BackupRequestType.FULL_BACKUP; } public static enum BackupRequestType implements RequestType<TheBackupInterface> { FULL_BACKUP( new TargetCaller<TheBackupInterface, Void>() { public Response<Void> call( TheBackupInterface master, RequestContext context, ChannelBuffer input, ChannelBuffer target ) { return master.fullBackup( new ToNetworkStoreWriter( target ) ); } }, Protocol.VOID_SERIALIZER ), INCREMENTAL_BACKUP( new TargetCaller<TheBackupInterface, Void>() { public Response<Void> call( TheBackupInterface master, RequestContext context, ChannelBuffer input, ChannelBuffer target ) { return master.incrementalBackup( context ); } }, Protocol.VOID_SERIALIZER ) ; @SuppressWarnings( "rawtypes" ) private final TargetCaller masterCaller; @SuppressWarnings( "rawtypes" ) private final ObjectSerializer serializer; @SuppressWarnings( "rawtypes" ) private BackupRequestType( TargetCaller masterCaller, ObjectSerializer serializer ) { this.masterCaller = masterCaller; this.serializer = serializer; } @SuppressWarnings( "rawtypes" ) public TargetCaller getTargetCaller() { return masterCaller; } @SuppressWarnings( "rawtypes" ) public ObjectSerializer getObjectSerializer() { return serializer; } public byte id() { return (byte) ordinal(); } } }
package org.apache.commons.codec.digest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Hex; /** * Operations to simplifiy common {@link java.security.MessageDigest} tasks. This * class is thread safe. * * @author Dave Dribin * @author David Graham * @author Gary Gregory */ public class DigestUtils { /** * Returns a MessageDigest for the given <code>algorithm</code>. * * @return An MD5 digest instance. * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught, */ protected static MessageDigest getDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } } /** * Returns an MD5 MessageDigest. * * @return An MD5 digest instance. * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught, */ private static MessageDigest getMd5Digest() { return getDigest("MD5"); } /** * Returns an SHA digest. * * @return An SHA digest instance. * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught, */ private static MessageDigest getShaDigest() { return getDigest("SHA"); } /** * Calculates the MD5 digest and returns the value as a 16 element * <code>byte[]</code>. * * @param data Data to digest * @return MD5 digest */ public static byte[] md5(byte[] data) { return getMd5Digest().digest(data); } /** * Calculates the MD5 digest and returns the value as a 16 element * <code>byte[]</code>. * * @param data Data to digest * @return MD5 digest */ public static byte[] md5(String data) { return md5(data.getBytes()); } /** * Calculates the MD5 digest and returns the value as a 32 character * hex string. * * @param data Data to digest * @return MD5 digest as a hex string */ public static String md5Hex(byte[] data) { return new String(Hex.encodeHex(md5(data))); } /** * Calculates the MD5 digest and returns the value as a 32 character * hex string. * * @param data Data to digest * @return MD5 digest as a hex string */ public static String md5Hex(String data) { return new String(Hex.encodeHex(md5(data))); } /** * Calculates the SHA digest and returns the value as a * <code>byte[]</code>. * * @param data Data to digest * @return SHA digest */ public static byte[] sha(byte[] data) { return getShaDigest().digest(data); } /** * Calculates the SHA digest and returns the value as a * <code>byte[]</code>. * * @param data Data to digest * @return SHA digest */ public static byte[] sha(String data) { return sha(data.getBytes()); } /** * Calculates the SHA digest and returns the value as a hex string. * * @param data Data to digest * @return SHA digest as a hex string */ public static String shaHex(byte[] data) { return new String(Hex.encodeHex(sha(data))); } /** * Calculates the SHA digest and returns the value as a hex string. * * @param data Data to digest * @return SHA digest as a hex string */ public static String shaHex(String data) { return new String(Hex.encodeHex(sha(data))); } }
package com.mebigfatguy.pixelle.dialogs; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.WindowConstants; import com.mebigfatguy.pixelle.PixelleBundle; import com.mebigfatguy.pixelle.PixelleComponent; import com.mebigfatguy.pixelle.utils.GuiUtils; import com.mebigfatguy.pixelle.utils.GuiUtils.Sizing; /** * an expanded popup dialog for editing algorithms */ public class AlgorithmEditor extends JDialog { private static final long serialVersionUID = 7704059483753204128L; private JEditorPane algo; private JButton ok; private JButton cancel; private final String origValue; private JLabel shortcutTrigger; private JPopupMenu shortcuts; private boolean isOK = false; public AlgorithmEditor(PixelleComponent component, Point pt, Dimension dim, String value) { origValue = value; initComponents(); initListeners(); setTitle(component.toString()); pt.y -= dim.height + 5; // 5 is clearly a fudge setLocation(pt); dim.height *= 8; setSize(dim); algo.setText(value); } public String getValue() { if (isOK) { return algo.getText(); } return origValue; } private void initComponents() { Container cp = getContentPane(); cp.setLayout(new BorderLayout(4, 4)); algo = new JEditorPane(); cp.add(new JScrollPane(algo), BorderLayout.CENTER); ok = new JButton(PixelleBundle.getString(PixelleBundle.OK)); cancel = new JButton(PixelleBundle.getString(PixelleBundle.CANCEL)); GuiUtils.sizeUniformly(Sizing.Both, ok, cancel); shortcutTrigger = new JLabel(PixelleBundle.getString(PixelleBundle.SHORTCUTS)); shortcutTrigger.setBorder(BorderFactory.createEtchedBorder()); shortcutTrigger.setEnabled(true); shortcutTrigger.setOpaque(true); buildShortCutsMenu(); shortcutTrigger.setLabelFor(shortcuts); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); p.add(Box.createHorizontalStrut(20)); p.add(shortcutTrigger); p.add(Box.createHorizontalStrut(10)); p.add(Box.createHorizontalGlue()); p.add(ok); p.add(Box.createHorizontalStrut(10)); p.add(cancel); p.add(Box.createHorizontalStrut(20)); cp.add(p, BorderLayout.SOUTH); } private void initListeners() { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { isOK = true; dispose(); } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { dispose(); } }); shortcutTrigger.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { shortcuts.show(e.getComponent(), e.getX(), e.getY()); } }); } public String getText() { return algo.getText(); } private void buildShortCutsMenu() { if (shortcuts != null) { return; } shortcuts = new JPopupMenu(PixelleBundle.getString(PixelleBundle.SHORTCUTS)); JMenu specMenu = new JMenu(PixelleBundle.getString(PixelleBundle.PIXEL_SPECIFICATION)); JMenuItem redSpecItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.RED_ALGORITHM)); JMenuItem greenSpecItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.GREEN_ALGORITHM)); JMenuItem blueSpecItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.BLUE_ALGORITHM)); JMenuItem blackSpecItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.BLACK_ALGORITHM)); JMenuItem transparentSpecItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.TRANSPARENCY_ALGORITHM)); JMenuItem selectionSpecItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.SELECTION_ALGORITHM)); specMenu.add(redSpecItem); specMenu.add(greenSpecItem); specMenu.add(blueSpecItem); specMenu.add(blackSpecItem); specMenu.add(transparentSpecItem); specMenu.add(selectionSpecItem); shortcuts.add(specMenu); JMenu posMenu = new JMenu(PixelleBundle.getString(PixelleBundle.POSITIONS)); JMenuItem leftItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.LEFT)); JMenuItem topItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.TOP)); JMenuItem rightItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.RIGHT)); JMenuItem bottomItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.BOTTOM)); JMenuItem centerXItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.CENTERX)); JMenuItem centerYItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.CENTERY)); posMenu.add(leftItem); posMenu.add(topItem); posMenu.add(rightItem); posMenu.add(bottomItem); posMenu.add(centerXItem); posMenu.add(centerYItem); shortcuts.add(posMenu); JMenu operatorMenu = new JMenu(PixelleBundle.getString(PixelleBundle.OPERATORS)); JMenuItem andItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.AND)); JMenuItem orItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.OR)); JMenuItem trinaryItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.TRINARY)); JMenuItem equalsItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.EQUALS)); JMenuItem notEqualsItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.NOTEQUALS)); JMenuItem lessThanOrEqualsItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.LESS_THAN_OR_EQUALS)); JMenuItem greaterThanOrEqualsItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.GREATER_THAN_OR_EQUALS)); JMenuItem lessThanItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.LESS_THAN)); JMenuItem greaterThanItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.GREATER_THAN)); JMenuItem multiplyItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.MULTIPLY)); JMenuItem divideItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.DIVIDE)); JMenuItem addItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.ADD)); JMenuItem subtractItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.SUBTRACT)); JMenuItem notItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.NOT)); operatorMenu.add(andItem); operatorMenu.add(orItem); operatorMenu.add(trinaryItem); operatorMenu.add(equalsItem); operatorMenu.add(notEqualsItem); operatorMenu.add(lessThanOrEqualsItem); operatorMenu.add(greaterThanOrEqualsItem); operatorMenu.add(lessThanItem); operatorMenu.add(greaterThanItem); operatorMenu.add(multiplyItem); operatorMenu.add(divideItem); operatorMenu.add(addItem); operatorMenu.add(subtractItem); operatorMenu.add(notItem); shortcuts.add(operatorMenu); JMenu functionMenu = new JMenu(PixelleBundle.getString(PixelleBundle.FUNCTIONS)); JMenuItem absItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.ABS)); JMenuItem maxItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.MAX)); JMenuItem minItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.MIN)); JMenuItem powItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.POW)); JMenuItem sqrtItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.SQRT)); JMenuItem sinItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.SIN)); JMenuItem cosItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.COS)); JMenuItem tanItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.TAN)); JMenuItem asinItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.ASIN)); JMenuItem acosItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.ACOS)); JMenuItem atanItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.ATAN)); JMenuItem logItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.LOG)); JMenuItem expItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.EXP)); JMenuItem eItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.E)); JMenuItem piItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.PI)); JMenuItem randomItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.RANDOM)); JMenuItem toDegreesItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.TO_DEGREES)); JMenuItem toRadiansItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.TO_RADIANS)); functionMenu.add(absItem); functionMenu.add(maxItem); functionMenu.add(minItem); functionMenu.add(powItem); functionMenu.add(sqrtItem); functionMenu.add(sinItem); functionMenu.add(cosItem); functionMenu.add(tanItem); functionMenu.add(asinItem); functionMenu.add(acosItem); functionMenu.add(atanItem); functionMenu.add(logItem); functionMenu.add(expItem); functionMenu.add(eItem); functionMenu.add(piItem); functionMenu.add(randomItem); functionMenu.add(toDegreesItem); functionMenu.add(toRadiansItem); shortcuts.add(functionMenu); JMenu specialMenu = new JMenu(PixelleBundle.getString(PixelleBundle.SPECIAL)); JMenuItem pixelInRectItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.PIXEL_IN_RECT)); JMenuItem pixelInCircleItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.PIXEL_IN_CIRCLE)); JMenuItem pixelOnEdgeItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.PIXEL_ON_EDGE)); JMenuItem pixelAverageItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.PIXEL_AVERAGE)); JMenuItem inverseXItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.INVERSE_X)); JMenuItem inverseYItem = new JMenuItem(PixelleBundle.getString(PixelleBundle.INVERSE_Y)); specialMenu.add(pixelInRectItem); specialMenu.add(pixelInCircleItem); specialMenu.add(pixelOnEdgeItem); specialMenu.add(pixelAverageItem); specialMenu.add(inverseXItem); specialMenu.add(inverseYItem); shortcuts.add(specialMenu); addSimpleShortCutListener(redSpecItem, "p(0)[x,y].r"); addSimpleShortCutListener(greenSpecItem, "p(0)[x,y].g"); addSimpleShortCutListener(blueSpecItem, "p(0)[x,y].b"); addSimpleShortCutListener(blackSpecItem, "p(0)[x,y].k"); addSimpleShortCutListener(transparentSpecItem, "p(0)[x,y].t"); addSimpleShortCutListener(selectionSpecItem, "p(0)[x,y].s"); addSimpleShortCutListener(leftItem, "0"); addSimpleShortCutListener(topItem, "0"); addSimpleShortCutListener(rightItem, "width"); addSimpleShortCutListener(bottomItem, "height"); addSimpleShortCutListener(centerXItem, "(width/2)"); addSimpleShortCutListener(centerYItem, "(height/2)"); addSimpleShortCutListener(andItem, " && "); addSimpleShortCutListener(orItem, " || "); addSimpleShortCutListener(trinaryItem, " ? "); addSimpleShortCutListener(equalsItem, " == "); addSimpleShortCutListener(notEqualsItem, " != "); addSimpleShortCutListener(lessThanOrEqualsItem, " <= "); addSimpleShortCutListener(greaterThanOrEqualsItem, " >= "); addSimpleShortCutListener(lessThanItem, " < "); addSimpleShortCutListener(greaterThanItem, " > "); addSimpleShortCutListener(multiplyItem, " * "); addSimpleShortCutListener(divideItem, " / "); addSimpleShortCutListener(addItem, " + "); addSimpleShortCutListener(subtractItem, " - "); addSimpleShortCutListener(notItem, " !"); addSimpleShortCutListener(absItem, "abs(x)"); addSimpleShortCutListener(maxItem, "max(x,y)"); addSimpleShortCutListener(minItem, "min(x,y)"); addSimpleShortCutListener(powItem, "pow(x,y)"); addSimpleShortCutListener(sqrtItem, "sqrt(x)"); addSimpleShortCutListener(sinItem, "sin(x)"); addSimpleShortCutListener(cosItem, "cos(x)"); addSimpleShortCutListener(tanItem, "tan(x)"); addSimpleShortCutListener(asinItem, "asin(x)"); addSimpleShortCutListener(acosItem, "acos(x)"); addSimpleShortCutListener(atanItem, "atan(x)"); addSimpleShortCutListener(logItem, "log(x)"); addSimpleShortCutListener(expItem, "exp(x)"); addSimpleShortCutListener(eItem, "e()"); addSimpleShortCutListener(piItem, "pi()"); addSimpleShortCutListener(randomItem, "random()"); addSimpleShortCutListener(toDegreesItem, "toDegrees(r)"); addSimpleShortCutListener(toRadiansItem, "toRadians(d)"); addSimpleShortCutListener(pixelInRectItem, "pixelInRect(t,l,b,r)"); addSimpleShortCutListener(pixelInCircleItem, "pixelInCircle(x,y,radius)"); addSimpleShortCutListener(pixelOnEdgeItem, "pixelOnEdge(e)"); addSimpleShortCutListener(pixelAverageItem, "pixelAverage(x, y, size, source, color)"); addSimpleShortCutListener(inverseXItem, "inverseX(source, x)"); addSimpleShortCutListener(inverseYItem, "inverseY(source, y)"); } private void addSimpleShortCutListener(JMenuItem mi, final String sc) { mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { algo.replaceSelection(sc); } }); } }
package com.ra4king.circuitsimulator.gui; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import com.ra4king.circuitsimulator.gui.ComponentManager.ComponentCreator; import com.ra4king.circuitsimulator.gui.Connection.PortConnection; import com.ra4king.circuitsimulator.gui.LinkWires.Wire; import com.ra4king.circuitsimulator.gui.Properties.Direction; import com.ra4king.circuitsimulator.gui.peers.SubcircuitPeer; import com.ra4king.circuitsimulator.gui.peers.wiring.PinPeer; import com.ra4king.circuitsimulator.simulator.Circuit; import com.ra4king.circuitsimulator.simulator.CircuitState; import com.ra4king.circuitsimulator.simulator.Port; import com.ra4king.circuitsimulator.simulator.Port.Link; import com.ra4king.circuitsimulator.simulator.Simulator; import com.ra4king.circuitsimulator.simulator.WireValue; import com.ra4king.circuitsimulator.simulator.WireValue.State; import com.ra4king.circuitsimulator.simulator.components.wiring.Pin; import javafx.geometry.Bounds; import javafx.geometry.Point2D; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.text.FontSmoothingType; import javafx.scene.text.Text; import javafx.util.Pair; /** * @author Roi Atalla */ public class CircuitManager { private enum SelectingState { IDLE, HIGHLIGHT_DRAGGED, ELEMENT_SELECTED, CONNECTION_SELECTED, ELEMENT_DRAGGED, CONNECTION_DRAGGED, PLACING_COMPONENT, } private SelectingState currentState = SelectingState.IDLE; private final CircuitSimulator simulatorWindow; private final ScrollPane canvasScrollPane; private final CircuitBoard circuitBoard; private ContextMenu menu; private Point2D lastMousePosition = new Point2D(0, 0); private Point2D lastMousePressed = new Point2D(0, 0); private GuiElement lastPressed; private LinkWires inspectLinkWires; private boolean isMouseInsideCanvas; private boolean isDraggedHorizontally; private boolean isCtrlDown; private boolean isShiftDown; private Circuit dummyCircuit = new Circuit(new Simulator()); private ComponentPeer<?> potentialComponent; private ComponentCreator componentCreator; private Properties potentialComponentProperties; private Connection startConnection, endConnection; private Map<GuiElement, Point2D> selectedElementsMap = new HashMap<>(); private Exception lastException; private long lastErrorTime; private static final long SHOW_ERROR_DURATION = 3000; private boolean needsRepaint; CircuitManager(CircuitSimulator simulatorWindow, ScrollPane canvasScrollPane, Simulator simulator) { this.simulatorWindow = simulatorWindow; this.canvasScrollPane = canvasScrollPane; circuitBoard = new CircuitBoard(this, simulator, simulatorWindow.getEditHistory()); getCanvas().setOnContextMenuRequested(event -> { menu = new ContextMenu(); MenuItem delete = new MenuItem("Delete"); delete.setOnAction(event1 -> { mayThrow(() -> circuitBoard.removeElements(selectedElementsMap.keySet())); setSelectedElements(Collections.emptySet()); reset(); }); if(selectedElementsMap.size() == 0) { Optional<ComponentPeer<?>> any = circuitBoard.getComponents().stream().filter( component -> component.containsScreenCoord((int)event.getX(), (int)event.getY())).findAny(); if(any.isPresent()) { menu.getItems().add(delete); menu.getItems().addAll(any.get().getContextMenuItems(this)); } } else if(selectedElementsMap.size() == 1) { menu.getItems().add(delete); menu.getItems().addAll(selectedElementsMap.keySet().iterator().next().getContextMenuItems(this)); } else { menu.getItems().add(delete); } if(menu.getItems().size() > 0) { menu.show(getCanvas(), event.getScreenX(), event.getScreenY()); } }); } private void reset() { currentState = SelectingState.IDLE; setSelectedElements(Collections.emptySet()); simulatorWindow.clearSelection(); dummyCircuit.clearComponents(); potentialComponent = null; isDraggedHorizontally = false; startConnection = null; endConnection = null; inspectLinkWires = null; needsRepaint = true; } public void destroy() { circuitBoard.destroy(); } public CircuitSimulator getSimulatorWindow() { return simulatorWindow; } public ScrollPane getCanvasScrollPane() { return canvasScrollPane; } public Canvas getCanvas() { return (Canvas)canvasScrollPane.getContent(); } public Circuit getCircuit() { return circuitBoard.getCircuit(); } public CircuitBoard getCircuitBoard() { return circuitBoard; } Exception getCurrentError() { if(lastException != null && SHOW_ERROR_DURATION < System.currentTimeMillis() - lastErrorTime) { lastException = null; } return lastException == null ? circuitBoard.getLastException() : lastException; } public Point2D getLastMousePosition() { return lastMousePosition; } public void setLastMousePosition(Point2D lastMousePosition) { this.lastMousePosition = lastMousePosition; } public Set<GuiElement> getSelectedElements() { return selectedElementsMap.keySet(); } public void setSelectedElements(Set<GuiElement> elements) { mayThrow(circuitBoard::finalizeMove); selectedElementsMap = elements.stream().collect( Collectors.toMap(peer -> peer, peer -> new Point2D(peer.getX(), peer.getY()))); updateSelectedProperties(); } public boolean needsRepaint() { return needsRepaint; } private Properties getCommonSelectedProperties() { return selectedElementsMap.keySet().stream() .filter(element -> element instanceof ComponentPeer<?>) .map(element -> ((ComponentPeer<?>)element).getProperties()) .reduce(Properties::intersect).orElse(new Properties()); } private void updateSelectedProperties() { long componentCount = selectedElementsMap.keySet().stream() .filter(element -> element instanceof ComponentPeer<?>) .count(); if(componentCount == 1) { Optional<? extends ComponentPeer<?>> peer = selectedElementsMap .keySet().stream() .filter(element -> element instanceof ComponentPeer<?>) .map(element -> ((ComponentPeer<?>)element)) .findAny(); peer.ifPresent(simulatorWindow::setProperties); } else if(componentCount > 1) { simulatorWindow.setProperties("Multiple selections", getCommonSelectedProperties()); } else { simulatorWindow.clearProperties(); } } public void modifiedSelection(ComponentCreator componentCreator, Properties properties) { this.componentCreator = componentCreator; this.potentialComponentProperties = properties; needsRepaint = true; if(currentState != SelectingState.IDLE && currentState != SelectingState.PLACING_COMPONENT) { reset(); } if(componentCreator != null) { setSelectedElements(Collections.emptySet()); currentState = SelectingState.PLACING_COMPONENT; potentialComponent = componentCreator.createComponent(properties, GuiUtils.getCircuitCoord(lastMousePosition.getX()), GuiUtils.getCircuitCoord(lastMousePosition.getY())); mayThrow(() -> dummyCircuit.addComponent(potentialComponent.getComponent())); potentialComponent.setX(potentialComponent.getX() - potentialComponent.getWidth() / 2); potentialComponent.setY(potentialComponent.getY() - potentialComponent.getHeight() / 2); simulatorWindow.setProperties(potentialComponent); return; } if(properties != null && !properties.isEmpty() && !selectedElementsMap.isEmpty()) { Map<ComponentPeer<?>, ComponentPeer<?>> newComponents = selectedElementsMap .keySet().stream() .filter(element -> element instanceof ComponentPeer<?>) .map(element -> (ComponentPeer<?>)element) .collect(Collectors.toMap( component -> component, component -> (ComponentPeer<?>)simulatorWindow .getComponentManager() .get(component.getClass()) .creator .createComponent( component.getProperties() .mergeIfExists(properties), component.getX(), component.getY()))); simulatorWindow.getEditHistory().beginGroup(); newComponents.forEach((oldComponent, newComponent) -> mayThrow(() -> circuitBoard.updateComponent(oldComponent, newComponent))); simulatorWindow.getEditHistory().endGroup(); setSelectedElements(Stream.concat( selectedElementsMap.keySet().stream().filter(element -> !(element instanceof ComponentPeer<?>)), newComponents.values().stream()) .collect(Collectors.toSet())); return; } currentState = SelectingState.IDLE; setSelectedElements(Collections.emptySet()); dummyCircuit.clearComponents(); potentialComponent = null; isDraggedHorizontally = false; startConnection = null; endConnection = null; needsRepaint = true; } public void paint() { needsRepaint = false; GraphicsContext graphics = getCanvas().getGraphicsContext2D(); graphics.setFont(GuiUtils.getFont(13)); graphics.setFontSmoothingType(FontSmoothingType.LCD); graphics.save(); graphics.setFill(Color.LIGHTGRAY); graphics.fillRect(0, 0, getCanvas().getWidth(), getCanvas().getHeight()); graphics.setFill(Color.BLACK); for(int i = 0; i < getCanvas().getWidth(); i += GuiUtils.BLOCK_SIZE) { for(int j = 0; j < getCanvas().getHeight(); j += GuiUtils.BLOCK_SIZE) { graphics.getPixelWriter().setColor(i, j, Color.BLACK); } } graphics.restore(); circuitBoard.paint(graphics); for(GuiElement selectedElement : selectedElementsMap.keySet()) { graphics.setStroke(Color.RED); if(selectedElement instanceof Wire) { graphics.strokeRect(selectedElement.getScreenX() - 1, selectedElement.getScreenY() - 1, selectedElement.getScreenWidth() + 2, selectedElement.getScreenHeight() + 2); } else { GuiUtils.drawShape(graphics::strokeRect, selectedElement); } } if(!simulatorWindow.isSimulationEnabled()) { graphics.save(); graphics.setStroke(Color.RED); for(Pair<CircuitState, Link> linkToUpdate : simulatorWindow.getSimulator().getLinksToUpdate()) { for(Port port : linkToUpdate.getValue().getParticipants()) { Optional<PortConnection> connection = circuitBoard.getComponents().stream() .flatMap(c -> c.getConnections().stream()) .filter(p -> p.getPort() == port).findFirst(); if(connection.isPresent()) { PortConnection portConn = connection.get(); graphics.strokeOval(portConn.getScreenX() - 2, portConn.getScreenY() - 2, 10, 10); } } } graphics.restore(); } if(inspectLinkWires != null && inspectLinkWires.getLink() != null && inspectLinkWires.isLinkValid()) { String value; try { value = circuitBoard.getCurrentState().getMergedValue(inspectLinkWires.getLink()).toString(); } catch(Exception exc) { value = "Error"; } Text text = new Text(value); text.setFont(graphics.getFont()); Bounds bounds = text.getLayoutBounds(); double x = lastMousePressed.getX() - bounds.getWidth() / 2 - 3; double y = lastMousePressed.getY() + 30; double width = bounds.getWidth() + 6; double height = bounds.getHeight() + 3; graphics.setLineWidth(1); graphics.setStroke(Color.BLACK); graphics.setFill(Color.ORANGE.brighter()); graphics.fillRect(x, y, width, height); graphics.strokeRect(x, y, width, height); graphics.setFill(Color.BLACK); graphics.fillText(value, x + 3, y + height - 5); } switch(currentState) { case IDLE: case CONNECTION_SELECTED: if(startConnection != null) { graphics.save(); graphics.setLineWidth(2); graphics.setStroke(Color.GREEN); graphics.strokeOval(startConnection.getScreenX() - 2, startConnection.getScreenY() - 2, 10, 10); if(endConnection != null) { graphics.strokeOval(endConnection.getScreenX() - 2, endConnection.getScreenY() - 2, 10, 10); } if(startConnection instanceof PortConnection) { PortConnection portConnection = (PortConnection)startConnection; String name = portConnection.getName(); if(!name.isEmpty()) { Text text = new Text(name); text.setFont(graphics.getFont()); Bounds bounds = text.getLayoutBounds(); double x = startConnection.getScreenX() - bounds.getWidth() / 2 - 3; double y = startConnection.getScreenY() + 30; double width = bounds.getWidth() + 6; double height = bounds.getHeight() + 3; graphics.setLineWidth(1); graphics.setStroke(Color.BLACK); graphics.setFill(Color.ORANGE.brighter()); graphics.fillRect(x, y, width, height); graphics.strokeRect(x, y, width, height); graphics.setFill(Color.BLACK); graphics.fillText(name, x + 3, y + height - 5); } } graphics.restore(); } break; case CONNECTION_DRAGGED: { graphics.save(); graphics.setLineWidth(2); graphics.setStroke(Color.GREEN); graphics.strokeOval(startConnection.getScreenX() - 2, startConnection.getScreenY() - 2, 10, 10); if(endConnection != null) { graphics.strokeOval(endConnection.getScreenX() - 2, endConnection.getScreenY() - 2, 10, 10); } int startX = startConnection.getScreenX() + startConnection.getScreenWidth() / 2; int startY = startConnection.getScreenY() + startConnection.getScreenHeight() / 2; int pointX = GuiUtils.getScreenCircuitCoord(lastMousePosition.getX()); int pointY = GuiUtils.getScreenCircuitCoord(lastMousePosition.getY()); graphics.setStroke(isShiftDown ? Color.RED : Color.BLACK); if(isDraggedHorizontally) { graphics.strokeLine(startX, startY, pointX, startY); graphics.strokeLine(pointX, startY, pointX, pointY); } else { graphics.strokeLine(startX, startY, startX, pointY); graphics.strokeLine(startX, pointY, pointX, pointY); } graphics.restore(); break; } case PLACING_COMPONENT: { if(potentialComponent != null && isMouseInsideCanvas) { graphics.save(); potentialComponent.paint(graphics, dummyCircuit.getTopLevelState()); graphics.restore(); for(Connection connection : potentialComponent.getConnections()) { graphics.save(); connection.paint(graphics, dummyCircuit.getTopLevelState()); graphics.restore(); } } break; } case HIGHLIGHT_DRAGGED: { double startX = lastMousePressed.getX() < lastMousePosition.getX() ? lastMousePressed.getX() : lastMousePosition.getX(); double startY = lastMousePressed.getY() < lastMousePosition.getY() ? lastMousePressed.getY() : lastMousePosition.getY(); double width = Math.abs(lastMousePosition.getX() - lastMousePressed.getX()); double height = Math.abs(lastMousePosition.getY() - lastMousePressed.getY()); graphics.setStroke(Color.GREEN.darker()); graphics.strokeRect(startX, startY, width, height); break; } } } interface ThrowableRunnable { void run() throws Exception; } boolean mayThrow(ThrowableRunnable runnable) { try { runnable.run(); if(lastException != null && SHOW_ERROR_DURATION < System.currentTimeMillis() - lastErrorTime) { lastException = null; } return false; } catch(Exception exc) { exc.printStackTrace(); lastException = exc; lastErrorTime = System.currentTimeMillis(); return true; } } public void keyPressed(KeyEvent e) { needsRepaint = true; switch(e.getCode()) { case RIGHT: { e.consume(); Properties props = currentState == SelectingState.PLACING_COMPONENT ? this.potentialComponentProperties : getCommonSelectedProperties(); props.setValue(Properties.DIRECTION, Direction.EAST); modifiedSelection(componentCreator, props); break; } case LEFT: { e.consume(); Properties props = currentState == SelectingState.PLACING_COMPONENT ? this.potentialComponentProperties : getCommonSelectedProperties(); props.setValue(Properties.DIRECTION, Direction.WEST); modifiedSelection(componentCreator, props); break; } case UP: { e.consume(); Properties props = currentState == SelectingState.PLACING_COMPONENT ? this.potentialComponentProperties : getCommonSelectedProperties(); props.setValue(Properties.DIRECTION, Direction.NORTH); modifiedSelection(componentCreator, props); break; } case DOWN: { e.consume(); Properties props = currentState == SelectingState.PLACING_COMPONENT ? this.potentialComponentProperties : getCommonSelectedProperties(); props.setValue(Properties.DIRECTION, Direction.SOUTH); modifiedSelection(componentCreator, props); break; } case CONTROL: isCtrlDown = true; break; case SHIFT: if(currentState != SelectingState.CONNECTION_SELECTED && currentState != SelectingState.CONNECTION_DRAGGED) { simulatorWindow.setClickMode(true); } isShiftDown = true; break; case NUMPAD0: case NUMPAD1: case DIGIT0: case DIGIT1: int value = e.getText().charAt(0) - '0'; GuiElement selectedElem; if(selectedElementsMap.size() == 1 && (selectedElem = selectedElementsMap.keySet().iterator().next()) instanceof PinPeer && ((PinPeer)selectedElem).isInput()) { PinPeer selectedPin = (PinPeer)selectedElem; WireValue currentValue = new WireValue(circuitBoard.getCurrentState() .getLastPushedValue( selectedPin.getComponent().getPort(Pin.PORT))); for(int i = currentValue.getBitSize() - 1; i > 0; i currentValue.setBit(i, currentValue.getBit(i - 1)); } currentValue.setBit(0, value == 1 ? State.ONE : State.ZERO); selectedPin.getComponent().setValue(circuitBoard.getCurrentState(), currentValue); simulatorWindow.runSim(); needsRepaint = true; } break; case BACK_SPACE: case DELETE: mayThrow(() -> circuitBoard.removeElements(selectedElementsMap.keySet())); case ESCAPE: if(currentState == SelectingState.ELEMENT_DRAGGED) { mayThrow(() -> circuitBoard.moveElements(0, 0)); } reset(); break; } } public void keyReleased(KeyEvent e) { needsRepaint = true; switch(e.getCode()) { case CONTROL: isCtrlDown = false; break; case SHIFT: simulatorWindow.setClickMode(false); isShiftDown = false; break; } } private void addCurrentWire() { int endMidX = endConnection == null ? GuiUtils.getCircuitCoord(lastMousePosition.getX()) : endConnection.getX(); int endMidY = endConnection == null ? GuiUtils.getCircuitCoord(lastMousePosition.getY()) : endConnection.getY(); Set<Wire> wires = new HashSet<>(); if(endMidX - startConnection.getX() != 0 && endMidY - startConnection.getY() != 0) { simulatorWindow.getEditHistory().beginGroup(); if(isDraggedHorizontally) { wires.add(new Wire(null, startConnection.getX(), startConnection.getY(), endMidX - startConnection.getX(), true)); wires.add(new Wire(null, endMidX, startConnection.getY(), endMidY - startConnection.getY(), false)); } else { wires.add(new Wire(null, startConnection.getX(), startConnection.getY(), endMidY - startConnection.getY(), false)); wires.add(new Wire(null, startConnection.getX(), endMidY, endMidX - startConnection.getX(), true)); } simulatorWindow.getEditHistory().endGroup(); } else if(endMidX - startConnection.getX() != 0) { wires.add(new Wire(null, startConnection.getX(), startConnection.getY(), endMidX - startConnection.getX(), true)); } else if(endMidY - startConnection.getY() != 0) { wires.add(new Wire(null, endMidX, startConnection.getY(), endMidY - startConnection.getY(), false)); } else { Set<Connection> connections = circuitBoard.getConnections(startConnection.getX(), startConnection.getY()); setSelectedElements(Stream.concat(isCtrlDown ? getSelectedElements().stream() : Stream.empty(), connections.stream().map(Connection::getParent)) .collect(Collectors.toSet())); } if(isShiftDown) { mayThrow(() -> circuitBoard.removeElements(wires)); } else { for(Wire w : wires) { mayThrow(() -> circuitBoard.addWire(w.getX(), w.getY(), w.getLength(), w.isHorizontal())); } } } private void checkStartConnection() { if(currentState != SelectingState.CONNECTION_DRAGGED) { Set<Connection> selectedConns = circuitBoard.getConnections( GuiUtils.getCircuitCoord(lastMousePosition.getX()), GuiUtils.getCircuitCoord(lastMousePosition.getY())); Connection selected = null; for(Connection connection : selectedConns) { if(connection instanceof PortConnection) { selected = connection; break; } } if(selected == null && !selectedConns.isEmpty()) { selected = selectedConns.iterator().next(); } startConnection = selected; needsRepaint = true; } } private void checkEndConnection(Point2D prevMousePosition) { if(currentState == SelectingState.CONNECTION_DRAGGED) { int currDiffX = GuiUtils.getCircuitCoord(lastMousePosition.getX()) - startConnection.getX(); int prevDiffX = GuiUtils.getCircuitCoord(prevMousePosition.getX()) - startConnection.getX(); int currDiffY = GuiUtils.getCircuitCoord(lastMousePosition.getY()) - startConnection.getY(); int prevDiffY = GuiUtils.getCircuitCoord(prevMousePosition.getY()) - startConnection.getY(); if(currDiffX == 0 || prevDiffX == 0 || currDiffX / Math.abs(currDiffX) != prevDiffX / Math.abs(prevDiffX)) { isDraggedHorizontally = false; } if(currDiffY == 0 || prevDiffY == 0 || currDiffY / Math.abs(currDiffY) != prevDiffY / Math.abs(prevDiffY)) { isDraggedHorizontally = true; } endConnection = circuitBoard.findConnection(GuiUtils.getCircuitCoord(lastMousePosition.getX()), GuiUtils.getCircuitCoord(lastMousePosition.getY())); needsRepaint = true; } } public void mousePressed(MouseEvent e) { if(menu != null) { menu.hide(); } if(e.getButton() != MouseButton.PRIMARY) { return; } lastMousePosition = new Point2D(e.getX(), e.getY()); lastMousePressed = new Point2D(e.getX(), e.getY()); switch(currentState) { case ELEMENT_DRAGGED: case CONNECTION_SELECTED: case HIGHLIGHT_DRAGGED: throw new IllegalStateException("How?!"); case IDLE: case ELEMENT_SELECTED: if(startConnection != null) { if(simulatorWindow.isClickMode()) { inspectLinkWires = startConnection.getLinkWires(); currentState = SelectingState.IDLE; } else { if(isCtrlDown) { currentState = SelectingState.CONNECTION_DRAGGED; } else { currentState = SelectingState.CONNECTION_SELECTED; } } } else { inspectLinkWires = null; Optional<GuiElement> clickedComponent = Stream.concat(getSelectedElements().stream(), circuitBoard.getComponents().stream()) .filter(peer -> peer.containsScreenCoord((int)e.getX(), (int)e.getY())) .findFirst(); if(clickedComponent.isPresent()) { GuiElement selectedElement = clickedComponent.get(); if(simulatorWindow.isClickMode()) { lastPressed = selectedElement; selectedElement.mousePressed(circuitBoard.getCurrentState(), lastMousePosition.getX() - selectedElement.getScreenX(), lastMousePosition.getY() - selectedElement.getScreenY()); simulatorWindow.runSim(); needsRepaint = true; } else if(e.getClickCount() == 2 && selectedElement instanceof SubcircuitPeer) { reset(); ((SubcircuitPeer)selectedElement).switchToSubcircuit(this); } else if(isCtrlDown) { Set<GuiElement> elements = new HashSet<>(getSelectedElements()); elements.add(selectedElement); setSelectedElements(elements); } else if(!getSelectedElements().contains(selectedElement)) { setSelectedElements(Collections.singleton(selectedElement)); } if(currentState == SelectingState.IDLE) { currentState = SelectingState.ELEMENT_SELECTED; } } else if(!isCtrlDown) { reset(); } } break; case CONNECTION_DRAGGED: addCurrentWire(); if(isCtrlDown) { Set<Connection> selectedConns = circuitBoard.getConnections(GuiUtils.getCircuitCoord(e.getX()), GuiUtils.getCircuitCoord(e.getY())); if(!selectedConns.isEmpty()) { startConnection = selectedConns.iterator().next(); } } else { currentState = SelectingState.IDLE; startConnection = null; endConnection = null; } break; case PLACING_COMPONENT: ComponentPeer<?> newComponent = componentCreator.createComponent(potentialComponentProperties, potentialComponent.getX(), potentialComponent.getY()); mayThrow(() -> circuitBoard.addComponent(newComponent)); reset(); if(circuitBoard.getComponents().contains(newComponent)) { setSelectedElements(Collections.singleton(newComponent)); } currentState = SelectingState.PLACING_COMPONENT; break; } needsRepaint = true; } public void mouseReleased(MouseEvent e) { if(e.getButton() != MouseButton.PRIMARY) { return; } lastMousePosition = new Point2D(e.getX(), e.getY()); switch(currentState) { case IDLE: case ELEMENT_SELECTED: case ELEMENT_DRAGGED: if(lastPressed != null) { lastPressed.mouseReleased(circuitBoard.getCurrentState(), lastMousePosition.getX() - lastPressed.getScreenX(), lastMousePosition.getY() - lastPressed.getScreenY()); lastPressed = null; simulatorWindow.runSim(); needsRepaint = true; } mayThrow(circuitBoard::finalizeMove); currentState = SelectingState.IDLE; break; case CONNECTION_SELECTED: { Set<Connection> connections = circuitBoard.getConnections(startConnection.getX(), startConnection.getY()); setSelectedElements(Stream.concat(isCtrlDown ? getSelectedElements().stream() : Stream.empty(), connections.stream().map(Connection::getParent)) .collect(Collectors.toSet())); currentState = SelectingState.IDLE; break; } case CONNECTION_DRAGGED: { if(!isCtrlDown) { addCurrentWire(); currentState = SelectingState.IDLE; startConnection = null; endConnection = null; } break; } case HIGHLIGHT_DRAGGED: case PLACING_COMPONENT: currentState = SelectingState.IDLE; break; } checkStartConnection(); needsRepaint = true; } public void mouseDragged(MouseEvent e) { if(e.getButton() != MouseButton.PRIMARY) { return; } Point2D prevMousePosition = lastMousePosition; lastMousePosition = new Point2D(e.getX(), e.getY()); switch(currentState) { case IDLE: case HIGHLIGHT_DRAGGED: currentState = SelectingState.HIGHLIGHT_DRAGGED; int startX = (int)(lastMousePressed.getX() < lastMousePosition.getX() ? lastMousePressed.getX() : lastMousePosition.getX()); int startY = (int)(lastMousePressed.getY() < lastMousePosition.getY() ? lastMousePressed.getY() : lastMousePosition.getY()); int width = (int)Math.abs(lastMousePosition.getX() - lastMousePressed.getX()); int height = (int)Math.abs(lastMousePosition.getY() - lastMousePressed.getY()); if(!isCtrlDown) { selectedElementsMap.clear(); } setSelectedElements(Stream.concat( getSelectedElements().stream(), Stream.concat(circuitBoard.getComponents().stream(), circuitBoard.getLinks().stream() .flatMap(link -> link.getWires().stream())) .filter(peer -> peer.isWithinScreenCoord(startX, startY, width, height))) .collect(Collectors.toSet())); break; case ELEMENT_SELECTED: case ELEMENT_DRAGGED: case PLACING_COMPONENT: int dx = GuiUtils.getCircuitCoord(lastMousePosition.getX() - lastMousePressed.getX()); int dy = GuiUtils.getCircuitCoord(lastMousePosition.getY() - lastMousePressed.getY()); if(dx != 0 || dy != 0 || currentState == SelectingState.ELEMENT_DRAGGED) { currentState = SelectingState.ELEMENT_DRAGGED; if(!circuitBoard.isMoving()) { mayThrow(() -> circuitBoard.initMove(getSelectedElements())); } mayThrow(() -> circuitBoard.moveElements(dx, dy)); } break; case CONNECTION_SELECTED: case CONNECTION_DRAGGED: currentState = SelectingState.CONNECTION_DRAGGED; checkEndConnection(prevMousePosition); break; } checkStartConnection(); needsRepaint = true; } public void mouseMoved(MouseEvent e) { Point2D prevMousePosition = lastMousePosition; lastMousePosition = new Point2D(e.getX(), e.getY()); if(potentialComponent != null) { potentialComponent.setX(GuiUtils.getCircuitCoord(e.getX()) - potentialComponent.getWidth() / 2); potentialComponent.setY(GuiUtils.getCircuitCoord(e.getY()) - potentialComponent.getHeight() / 2); } checkStartConnection(); checkEndConnection(prevMousePosition); needsRepaint = true; } public void mouseEntered(MouseEvent e) { isMouseInsideCanvas = true; } public void mouseExited(MouseEvent e) { isMouseInsideCanvas = false; isCtrlDown = false; isShiftDown = false; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan.indexer; import fan.sys.MapType; import fan.sys.Type; import java.lang.reflect.Member; import java.util.List; import net.colar.netbeans.fan.FanParserResult; import net.colar.netbeans.fan.FanUtilities; import net.colar.netbeans.fan.antlr.FanParser; import net.colar.netbeans.fan.ast.FanAstScope; import net.colar.netbeans.fan.ast.FanLexAstUtils; import net.colar.netbeans.fan.ast.FanRootScope; import net.colar.netbeans.fan.indexer.model.FanSlot; import net.colar.netbeans.fan.indexer.model.FanType; import org.antlr.runtime.tree.CommonTree; /** * Resolved type * @author tcolar */ public class FanResolvedType { private final String qualifiedType; private final FanType dbType; // whether it's used in a nullable context : ex: Str? vs Str // TODO not being set private boolean nullableContext = false; // whether it's used in a static context: ex Str. vs str. private boolean staticContext = false; public FanResolvedType(String qualifiedType) { this.qualifiedType = qualifiedType; if (qualifiedType != null && !qualifiedType.equals(FanIndexer.UNRESOLVED_TYPE)) { dbType = FanType.findByQualifiedName(qualifiedType); } else { dbType = null; } } public boolean isResolved() { return dbType != null; } public FanType getDbType() { return dbType; } public String getQualifiedType() { return qualifiedType; } @Override public String toString() { StringBuilder sb = new StringBuilder(qualifiedType).append(" resolved:").append(isResolved()); return sb.toString(); } public static FanResolvedType makeUnresolved() { return new FanResolvedType(FanIndexer.UNRESOLVED_TYPE); } public static FanResolvedType makeFromSimpleTypeWithWarning(FanAstScope scope, CommonTree node) { FanResolvedType result = makeFromSimpleType(scope, node); if (!result.isResolved()) { String type = FanLexAstUtils.getNodeContent(scope.getRoot().getParserResult(), node); //TODO: Propose to auto-add using statements (Hints) scope.getRoot().addError("Unresolved type: " + type, node); } return result; } public static FanResolvedType makeFromSimpleType(FanAstScope scope, CommonTree node) { if (node == null) { return makeUnresolved(); } //TODO: formals, functiontype, assignedType FanRootScope root = scope.getRoot(); String type = FanLexAstUtils.getNodeContent(root.getParserResult(), node).trim(); boolean nullable = true; boolean list = false; if (type.endsWith("?")) { type = type.substring(0, type.length() - 1); } else { nullable = false; } if (type.endsWith("[]")) { list = true; type = type.substring(0, type.length() - 2); } CommonTree map = (CommonTree) node.getFirstChildWithType(FanParser.AST_MAP); FanResolvedType resolved = makeUnresolved(); // TODO Deal with maps if (map != null) { CommonTree keyNode = (CommonTree) map.getChild(0); CommonTree valueNode = (CommonTree) map.getChild(1); if (keyNode != null && valueNode != null) { // Find key / value type FanResolvedType keyType = makeFromSimpleType(scope, keyNode); FanResolvedType valueType = makeFromSimpleType(scope, valueNode); if (keyType.isResolved() && valueType.isResolved()) { MapType mapType = new MapType(Type.find(keyType.getQualifiedType()), Type.find(valueType.getQualifiedType())); resolved = new FanResolvedType(mapType.qname()); } } } else { // "regular" type resolved = root.lookupUsing(type); } // TODO: list if (list) { if (resolved.isResolved()) { resolved = new FanResolvedType(Type.find(resolved.getQualifiedType()).toListOf().qname()); } } resolved.setNullableContext(nullable); //System.out.println("Type: " + type + " resolved to: " + resolved); return resolved; } public static FanResolvedType makeFromExpr(FanRootScope rootScope, FanParserResult result, CommonTree exprNode, int lastGoodTokenIndex) { FanAstScope scope = rootScope.findClosestScope(exprNode); FanUtilities.GENERIC_LOGGER.debug("** scope: " + scope); FanResolvedType type = resolveExpr(result, scope, null, exprNode, lastGoodTokenIndex); if (type == null) { type = makeUnresolved(); } FanUtilities.GENERIC_LOGGER.debug("** resolvedType: " + type); return type; } /** * recursive * @param result * @param scope * @param baseType * @param node * @param index * @return */ private static FanResolvedType resolveExpr(FanParserResult result, FanAstScope scope, FanResolvedType baseType, CommonTree node, int index) { // if unresolveable no point searching further if (baseType != null && !baseType.isResolved()) { return baseType; } //System.out.println("Node type: " + node.getType()); String t = FanLexAstUtils.getNodeContent(result, node); FanUtilities.GENERIC_LOGGER.debug("** type: " + t + " " + node.toStringTree() + " " + baseType); //System.out.println("Index: " + FanLexAstUtils.getTokenStart(node) + " VS " + index); // Skip the imcomplete part past what we care about if (!isValidTokenStart(node, index)) { return baseType; } List<CommonTree> children = node.getChildren(); System.out.println("Node type: "+t+" -> "+node.getText()+"("+node.getType()+")"); switch (node.getType()) { case FanParser.AST_TERM_EXPR: CommonTree termBase = children.get(0); CommonTree termChain = children.get(1); baseType = resolveExpr(result, scope, null, termBase, index); baseType = resolveExpr(result, scope, baseType, termChain, index); break; case FanParser.AST_STATIC_CALL: CommonTree type = children.get(0); CommonTree idExpr = children.get(1); baseType = resolveExpr(result, scope, null, type, index); baseType = resolveExpr(result, scope, baseType, idExpr, index); break; case FanParser.AST_STR: baseType = new FanResolvedType("sys::Str"); break; case FanParser.KW_TRUE: case FanParser.KW_FALSE: baseType = new FanResolvedType("sys::Bool"); break; case FanParser.NUMBER: String ftype = parseNumberType(node.getText()); baseType = new FanResolvedType(ftype); break; case FanParser.URI: // TODO: parse for Int, Float, Long, Duration etc... baseType = new FanResolvedType("sys::Uri"); break; //TODO: named super / this, it //case FanParser.KW_IT: //case FanParser.KW_THIS: //case FanParser.KW_SUPER: //scope.getParentType(); // Do nothing //break; //TODO: list, map, range, symbol, slot, type case FanParser.AST_ID: if (baseType == null) { baseType = scope.resolveVar(t); if (!baseType.isResolved()) { // Try a static type (ex: Str.) baseType = makeFromSimpleType(scope, node); baseType.setStaticContext(true); } } else { if (baseType.isResolved() && baseType.getDbType().isJava()) { // java slots List<Member> members = FanIndexerFactory.getJavaIndexer().findTypeSlots(baseType.getQualifiedType()); boolean found = false; // Returrning the first match .. because java has overloading this could be wrong // However i assume overloaded methods return the same type (If it doesn't too bad, it's ugly coe anyway :) ) for (Member member : members) { if (member.getName().equalsIgnoreCase(t)) { baseType = new FanResolvedType(FanIndexerFactory.getJavaIndexer().getReturnType(member)); found = true; break; } } if (!found) { baseType = makeUnresolved(); } } else { // Fan slots FanSlot slot = FanSlot.findByTypeAndName(baseType.getQualifiedType(), t); if (slot != null) { baseType = new FanResolvedType(slot.returnedType); } else { baseType = makeUnresolved(); } } } break; // TODO case itBlock : skip; default: // "Meaningless" nodes (interm of expression resolving) if (node.getChildCount() > 0) { baseType = resolveExpr(result, scope, baseType, (CommonTree) node.getChild(0), index); } else { FanUtilities.GENERIC_LOGGER.info("Don't know how to resolve: " + t + " " + node.toStringTree()); //baseType = makeUnresolved(); } break; } //System.out.println("** End type: " + baseType); return baseType; } private static boolean isValidTokenStart(CommonTree node, int maxIndex) { int index = FanLexAstUtils.getTokenStart(node); // will be -1 for a Nill node return index >= 0 && index <= maxIndex; } public boolean isStaticContext() { return staticContext; } public void setNullableContext(boolean nullable) { nullableContext = nullable; } public boolean isNullable() { return nullableContext; } public void setStaticContext(boolean b) { staticContext = b; } private static String parseNumberType(String text) { // TODO: parse for Int, Float, Long, Duration etc... return "sys::Int"; } }
package net.xisberto.work_schedule; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import net.xisberto.work_schedule.database.Database; import net.xisberto.work_schedule.database.Period; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.NavUtils; import android.support.v4.view.ViewPager; import android.util.Log; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.doomonafireball.betterpickers.calendardatepicker.CalendarDatePickerDialog; import com.doomonafireball.betterpickers.calendardatepicker.CalendarDatePickerDialog.OnDateSetListener; import com.viewpagerindicator.TabPageIndicator; public class ViewHistoryActivity extends SherlockFragmentActivity implements OnDateSetListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_history); getSupportActionBar().setDisplayHomeAsUpEnabled(true); ViewPager view_pager = (ViewPager) findViewById(R.id.pager); TabPageIndicator pager_indicator = (TabPageIndicator) findViewById(R.id.pager_indicator); HistoryPagerAdapter pager_adapter = new HistoryPagerAdapter( getSupportFragmentManager()); view_pager.setAdapter(pager_adapter); pager_indicator.setViewPager(view_pager); view_pager.setCurrentItem(HistoryPagerAdapter.SIZE); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_history, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (!BuildConfig.DEBUG) { menu.findItem(R.id.menu_fake_data).setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); return true; } ViewPager view_pager = (ViewPager) findViewById(R.id.pager); HistoryPagerAdapter adapter = (HistoryPagerAdapter) view_pager .getAdapter(); Calendar selected_day = adapter.getSelectedDay(view_pager .getCurrentItem()); CalendarDatePickerDialog dialog; switch (item.getItemId()) { case R.id.menu_go_today: view_pager = (ViewPager) findViewById(R.id.pager); view_pager.setCurrentItem(HistoryPagerAdapter.SIZE); break; case R.id.menu_share: dialog = CalendarDatePickerDialog.newInstance(this, selected_day.get(Calendar.YEAR), selected_day.get(Calendar.MONTH), selected_day.get(Calendar.DAY_OF_MONTH)); dialog.show(getSupportFragmentManager(), "date_picker"); break; case R.id.menu_fake_data: dialog = CalendarDatePickerDialog.newInstance( new OnDateSetListener() { @Override public void onDateSet(CalendarDatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) { Calendar date = Calendar.getInstance(); date.set(Calendar.YEAR, year); date.set(Calendar.MONTH, monthOfYear); date.set(Calendar.DAY_OF_MONTH, dayOfMonth); while (date.before(Calendar.getInstance())) { if ((date.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) && (date.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)) { for (int id : Period.ids) { Period period = new Period(id, date); period.persist(ViewHistoryActivity.this); } } date.add(Calendar.DAY_OF_MONTH, 1); } } }, selected_day.get(Calendar.YEAR), selected_day .get(Calendar.MONTH), selected_day .get(Calendar.DAY_OF_MONTH)); dialog.show(getSupportFragmentManager(), "date_picker"); break; default: return super.onOptionsItemSelected(item); } return true; } @Override public void onDateSet(CalendarDatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) { Log.d("History", "onDateSelected"); Calendar startDate = Calendar.getInstance(); startDate.set(Calendar.YEAR, year); startDate.set(Calendar.MONTH, monthOfYear); startDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); CSVExporter exporter = new CSVExporter(ViewHistoryActivity.this); exporter.execute(startDate); } public void shareUri(Uri uri) { Log.d("History", "shareURI"); Intent intentShare = new Intent(Intent.ACTION_SEND); intentShare.setType("text/csv"); intentShare.putExtra(Intent.EXTRA_STREAM, uri); startActivity(Intent.createChooser(intentShare, getResources() .getString(R.string.menu_share))); } public static class CSVExporter extends AsyncTask<Calendar, Void, Uri> { private ViewHistoryActivity activity; public CSVExporter(ViewHistoryActivity context) { super(); this.activity = context; } /* Checks if external storage is available for read and write */ public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } @Override protected Uri doInBackground(Calendar... params) { Database database = Database.getInstance(activity); Calendar startDate = Calendar.getInstance(), endDate = Calendar .getInstance(); if (params[0] != null) { startDate = params[0]; } if (params.length > 1 && params[1] != null) { endDate = params[1]; } String content = database.exportCSV(startDate, endDate); if (isExternalStorageWritable()) { SimpleDateFormat dateFormat = new SimpleDateFormat( Database.DATE_FORMAT, Locale.getDefault()); String filename = "export_" + dateFormat.format(startDate.getTime()) + "_" + dateFormat.format(endDate.getTime()) + ".csv"; File file; File dir; dir = new File(Environment.getExternalStorageDirectory(), "WorkSchedule"); if (!dir.exists()) { dir.mkdirs(); } file = new File(dir, filename); Log.d("CVSExporter", "saving file on " + file.getAbsolutePath()); FileOutputStream outputStream; try { outputStream = new FileOutputStream(file); outputStream.write(content.getBytes()); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } return Uri.fromFile(file); } return null; } @Override protected void onPostExecute(Uri result) { activity.shareUri(result); } } }
package org.opentdc.events.file; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.opentdc.file.AbstractFileServiceProvider; import org.opentdc.events.EventModel; import org.opentdc.events.InvitationState; import org.opentdc.events.ServiceProvider; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.InternalServerErrorException; import org.opentdc.service.exception.NotFoundException; import org.opentdc.service.exception.ValidationException; // import org.opentdc.util.EmailSender; // import org.opentdc.util.FreeMarkerConfig; import org.opentdc.util.PrettyPrinter; // import freemarker.template.Template; /** * A file-based or transient implementation of the Events service. * @author Bruno Kaiser * */ public class FileServiceProvider extends AbstractFileServiceProvider<EventModel> implements ServiceProvider { private static Map<String, EventModel> index = null; private static final Logger logger = Logger.getLogger(FileServiceProvider.class.getName()); // private EmailSender emailSender = null; // private static final String SUBJECT = "Einladung zum Arbalo Launch Event"; /** * Constructor. * @param context the servlet context. * @param prefix the simple class name of the service provider * @throws IOException */ public FileServiceProvider( ServletContext context, String prefix ) throws IOException { super(context, prefix); if (index == null) { index = new HashMap<String, EventModel>(); List<EventModel> _events = importJson(); for (EventModel _event : _events) { index.put(_event.getId(), _event); } // new FreeMarkerConfig(context); // emailSender = new EmailSender(context); logger.info(_events.size() + " Events imported."); } } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#list(java.lang.String, java.lang.String, long, long) */ @Override public ArrayList<EventModel> list( String queryType, String query, int position, int size ) { logger.warning("EventsService.list() should not be called; returning empty list"); return new ArrayList<EventModel>(); /* ArrayList<EventModel> _events = new ArrayList<EventModel>(index.values()); Collections.sort(_events, EventModel.EventComparator); ArrayList<EventModel> _selection = new ArrayList<EventModel>(); for (int i = 0; i < _events.size(); i++) { if (i >= position && i < (position + size)) { _selection.add(_events.get(i)); } } logger.info("list(<" + query + ">, <" + queryType + ">, <" + position + ">, <" + size + ">) -> " + _selection.size() + " events."); return _selection; */ } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#create(org.opentdc.events.EventsModel) */ @Override public EventModel create( EventModel event) throws DuplicateException, ValidationException { logger.warning("EventsService.create() should not be called; returning the same EventModel"); logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")"); return event; /* logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")"); String _id = event.getId(); if (_id == null || _id == "") { _id = UUID.randomUUID().toString(); } else { if (index.get(_id) != null) { // object with same ID exists already throw new DuplicateException("event <" + _id + "> exists already."); } else { // a new ID was set on the client; we do not allow this throw new ValidationException("event <" + _id + "> contains an ID generated on the client. This is not allowed."); } } // enforce mandatory fields if (event.getFirstName() == null || event.getFirstName().length() == 0) { throw new ValidationException("event <" + _id + "> must contain a valid firstName."); } if (event.getLastName() == null || event.getLastName().length() == 0) { throw new ValidationException("event <" + _id + "> must contain a valid lastName."); } if (event.getEmail() == null || event.getEmail().length() == 0) { throw new ValidationException("event <" + _id + "> must contain a valid email address."); } if (event.getInvitationState() == null) { event.setInvitationState(InvitationState.INITIAL); } if (event.getSalutation() == null) { event.setSalutation(SalutationType.DU_M); } event.setId(_id); Date _date = new Date(); event.setCreatedAt(_date); event.setCreatedBy(getPrincipal()); event.setModifiedAt(_date); event.setModifiedBy(getPrincipal()); index.put(_id, event); logger.info("create(" + PrettyPrinter.prettyPrintAsJSON(event) + ")"); if (isPersistent) { exportJson(index.values()); } return event; */ } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#read(java.lang.String) */ @Override public EventModel read( String id) throws NotFoundException { EventModel _event = index.get(id); if (_event == null) { throw new NotFoundException("no event with ID <" + id + "> was found."); } logger.info("read(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event)); return _event; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#update(java.lang.String, org.opentdc.events.EventsModel) */ @Override public EventModel update( HttpServletRequest request, String id, EventModel event ) throws NotFoundException, ValidationException { EventModel _event = index.get(id); /* if(_event == null) { throw new NotFoundException("no event with ID <" + id + "> was found."); } if (! _event.getCreatedAt().equals(event.getCreatedAt())) { logger.warning("event <" + id + ">: ignoring createdAt value <" + event.getCreatedAt().toString() + "> because it was set on the client."); } if (! _event.getCreatedBy().equalsIgnoreCase(event.getCreatedBy())) { logger.warning("event <" + id + ">: ignoring createdBy value <" + event.getCreatedBy() + "> because it was set on the client."); } if (event.getFirstName() == null || event.getFirstName().length() == 0) { throw new ValidationException("event <" + id + "> must contain a valid firstName."); } if (event.getLastName() == null || event.getLastName().length() == 0) { throw new ValidationException("event <" + id + "> must contain a valid lastName."); } if (event.getEmail() == null || event.getEmail().length() == 0) { throw new ValidationException("event <" + id + "> must contain a valid email address."); } */ if (event.getInvitationState() == null) { event.setInvitationState(InvitationState.INITIAL); } /* if (event.getSalutation() == null) { event.setSalutation(SalutationType.DU_M); } _event.setFirstName(event.getFirstName()); _event.setLastName(event.getLastName()); _event.setEmail(event.getEmail()); _event.setSalutation(event.getSalutation()); */ _event.setInvitationState(event.getInvitationState()); _event.setComment(event.getComment()); _event.setModifiedAt(new Date()); _event.setModifiedBy(getPrincipal()); index.put(id, _event); logger.info("update(" + id + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event)); if (isPersistent) { exportJson(index.values()); } return _event; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#delete(java.lang.String) */ @Override public void delete( String id) throws NotFoundException, InternalServerErrorException { logger.warning("EventsService.delete(" + id + ") should not be called; ignoring it"); /* EventModel _event = index.get(id); if (_event == null) { throw new NotFoundException("event <" + id + "> was not found."); } if (index.remove(id) == null) { throw new InternalServerErrorException("event <" + id + "> can not be removed, because it does not exist in the index"); } logger.info("delete(" + id + ")"); if (isPersistent) { exportJson(index.values()); } */ } /** * Retrieve the email address of the contact. * @param contactName the name of the contact * @return the corresponding email address */ /* private String getEmailAddress(String contactName) { logger.info("getEmailAddress(" + contactName + ")"); String _emailAddress = null; if (contactName == null || contactName.isEmpty()) { contactName = "arbalo"; } if (contactName.equalsIgnoreCase("bruno")) { _emailAddress = "bruno.kaiser@arbalo.ch"; } else if (contactName.equalsIgnoreCase("thomas")) { _emailAddress = "thomas.huber@arbalo.ch"; } else if (contactName.equalsIgnoreCase("peter")) { _emailAddress = "peter.windemann@arbalo.ch"; } else if (contactName.equalsIgnoreCase("marc")) { _emailAddress = "marc.hofer@arbalo.ch"; } else if (contactName.equalsIgnoreCase("werner")) { _emailAddress = "werner.froidevaux@arbalo.ch"; } else { _emailAddress = "info@arbalo.ch"; } logger.info("getEmailAddress(" + contactName + ") -> " + _emailAddress); return _emailAddress; } */ /** * @param salutation * @return */ /* private Template getTemplate( SalutationType salutation, String contactName) { String _templateName = null; if (contactName == null || contactName.isEmpty()) { contactName = "arbalo"; } switch (salutation) { case HERR: _templateName = "emailHerr_" + contactName + ".ftl"; break; case FRAU: _templateName = "emailFrau_" + contactName + ".ftl"; break; case DU_F: _templateName = "emailDuf_" + contactName + ".ftl"; break; case DU_M: _templateName = "emailDum_" + contactName + ".ftl"; break; } return FreeMarkerConfig.getTemplateByName(_templateName); } */ /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#getMessage(java.lang.String) */ @Override public String getMessage(String id) throws NotFoundException, InternalServerErrorException { String _msg = "EventsService.getMessage(" + id + ") should not be called; use InvitationsService instead"; logger.warning(_msg); /* logger.info("getMessage(" + id + ")"); EventModel _model = read(id); // create the FreeMarker data model Map<String, Object> _root = new HashMap<String, Object>(); _root.put("event", _model); // Merge data model with template String _msg = FreeMarkerConfig.getProcessedTemplate( _root, getTemplate(_model.getSalutation(), _model.getContact())); logger.info("getMessage(" + id + ") -> " + _msg); */ return _msg; } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#sendMessage(java.lang.String) */ @Override public void sendMessage(String id) throws NotFoundException, InternalServerErrorException { logger.warning("EventsService.sendMessage(" + id + ") should not be called; ignoring it"); /* logger.info("sendMessage(" + id + ")"); EventModel _model = read(id); emailSender.sendMessage( _model.getEmail(), getEmailAddress(_model.getContact()), SUBJECT, getMessage(id)); logger.info("sent email message to " + _model.getEmail()); _model.setId(null); _model.setInvitationState(InvitationState.SENT); update(id, _model); */ } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#sendAllMessages() */ @Override public void sendAllMessages() throws InternalServerErrorException { logger.warning("EventsService.sendAllMessages() should not be called; ignoring it"); /* logger.info("sendAllMessages()"); for (EventModel _model : index.values()) { emailSender.sendMessage( _model.getEmail(), getEmailAddress(_model.getContact()), SUBJECT, getMessage(_model.getId())); logger.info("sent email message to " + _model.getEmail()); _model.setId(null); _model.setInvitationState(InvitationState.SENT); update(_model.getId(), _model); try { Thread.sleep(1000); } catch (InterruptedException _ex) { _ex.printStackTrace(); throw new InternalServerErrorException(_ex.getMessage()); } } */ } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#register(java.lang.String, java.lang.String) */ @Override public void register( HttpServletRequest request, String id, String comment) throws NotFoundException, ValidationException { EventModel _event = read(id); if (_event.getInvitationState() == InvitationState.INITIAL) { throw new ValidationException("invitation <" + id + "> must be sent before being able to register"); } if (_event.getInvitationState() == InvitationState.REGISTERED) { logger.warning("invitation <" + id + "> is already registered; ignoring re-registration"); } _event.setInvitationState(InvitationState.REGISTERED); _event.setComment(comment); _event.setModifiedAt(new Date()); _event.setModifiedBy(getPrincipal()); index.put(id, _event); logger.info("register(" + id + ", " + comment + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event)); if (isPersistent) { exportJson(index.values()); } } /* (non-Javadoc) * @see org.opentdc.events.ServiceProvider#deregister(java.lang.String, java.lang.String) */ @Override public void deregister( HttpServletRequest request, String id, String comment) throws NotFoundException, ValidationException { EventModel _event = read(id); if (_event.getInvitationState() == InvitationState.INITIAL) { throw new ValidationException("invitation <" + id + "> must be sent before being able to deregister"); } if (_event.getInvitationState() == InvitationState.EXCUSED) { logger.warning("invitation <" + id + "> is already excused; ignoring deregistration"); } _event.setInvitationState(InvitationState.EXCUSED); _event.setComment(comment); _event.setModifiedAt(new Date()); _event.setModifiedBy(getPrincipal()); index.put(id, _event); logger.info("deregister(" + id + ", " + comment + ") -> " + PrettyPrinter.prettyPrintAsJSON(_event)); if (isPersistent) { exportJson(index.values()); } } }
package org.epics.graphene.rrdtool; import java.util.Arrays; import java.util.regex.Pattern; import org.epics.graphene.Point3DWithLabelDataset; import org.epics.util.time.Timestamp; import org.epics.util.time.TimestampFormat; /** * * @author carcassi */ public class GangliaRrdClusterMain { private static TimestampFormat format = new TimestampFormat("yyyyMMddHHmmss"); private static TimestampFormat readFormat = new TimestampFormat("yyyy/MM/dd HH:mm:ss"); public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: list directory (prints the machines and signals found)\n"); System.out.println("Usage: plot directory signalX signalY signalSize date outputName (creates a bubble plot)\n"); System.exit(0); } Pattern filePattern = Pattern.compile(".*\\.local", Pattern.CASE_INSENSITIVE); if ("list".equals(args[0])) { String path = args[1]; GangliaRrdCluster cluster = new GangliaRrdCluster(path); cluster.setDirPattern(filePattern); System.out.println("Machines: " + cluster.getMachines()); System.out.println("Signals: " + cluster.getSignals()); } else if ("plot".equals(args[0])) { if (args.length != 6) { System.out.println("Wrong syntax: needs 6 arguments"); } String path = args[1]; String signalX = args[2]; String signalY = args[3]; String signalZ = args[4]; String filename = args[6]; Timestamp time = format.parse(args[5]); String timeString = null; if (time != null) { timeString = readFormat.format(time); } System.out.println("Plotting from " + path + " (" + signalX + ", " + signalY + ", " + signalZ + ") at time " + timeString); GangliaRrdCluster cluster = new GangliaRrdCluster(path); cluster.setDirPattern(filePattern); Point3DWithLabelDataset dataset = cluster.dataset(Arrays.asList(signalX, signalY, signalZ), time); StringBuilder html = new StringBuilder(); BubbleUtil.createBubblePlot(filename, dataset, "http://ganglia-um.aglt2.org/ganglia/?m=load_one&r=day&s=ascending&c=UM-Worker-Nodes&h=DATASETLABEL&sh=1&hc=4&z=small", path, signalX, signalY, signalZ, time); } else { System.out.println("Command not found"); } } }
package com.upchannel.cordova.plugins; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import android.content.Context; import android.telephony.TelephonyManager; import android.accounts.Account; import android.accounts.AccountManager; import android.os.Build; public class DeviceInformation extends CordovaPlugin { private String checkValue(String str) { if ((str == null) || (str.length() == 0)) { return "\"TM.ERROR\""; } return "\"" + str + "\""; } private String getAccount(AccountManager am) { String str = ""; if (am != null) { Account[] accounts = am.getAccounts(); if (str.length() > 0) { str += ","; } str += "\"accounts\":["; for (int i = 0; i < accounts.length; i++) { if (i > 0) { str += ","; } str += "{\"email\": " + checkValue(accounts[i].name) + "," + "\"type\": " + checkValue(accounts[i].type) + "}"; } str += "]"; } return str; } private String getTelephone(TelephonyManager tm) { String str = ""; if (tm != null) { str = "\"deviceID\": " + checkValue(tm.getDeviceId()) + "," + "\"phoneNo\": " + checkValue(tm.getLine1Number()) + "," + "\"netCountry\": " + checkValue(tm.getNetworkCountryIso()) + "," + "\"netName\": " + checkValue(tm.getNetworkOperatorName()) + "," + "\"simNo\": " + checkValue(tm.getSimSerialNumber()) + "," + "\"simCountry\": " + checkValue(tm.getSimCountryIso()) + "," + "\"simName\": " + checkValue(tm.getSimOperatorName()) + "," + "\"userAgent: " + checkValue(System.getProperty("http.agent")) + "," + "\"systemBoardID: " + checkValue(BUILD.BOARD) + "," + "\"systemManufacturer: " + checkValue(BUILD.MANUFACTURER) + "," + "\"systemVersion: " + checkValue(BUILD.VERSION.RELEASE) + "," + "\"systemName: Android"; } return str; } private String getDetails(TelephonyManager tm, AccountManager am) { String acc = getAccount(am); String tel = getTelephone(tm); String str = ""; if ((acc.length() != 0) || (tel.length() != 0)) { str += "{" + acc; if (str.length() > 1) { str += ","; } str += tel + "}"; } return str; } public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { try { if (action.equals("get")) { TelephonyManager tm = (TelephonyManager) this.cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE); AccountManager am = AccountManager.get(this.cordova.getActivity()); String result = getDetails(tm,am); if (result != null) { callbackContext.success(result); return true; } } callbackContext.error("Invalid action"); return false; } catch (Exception e) { String s = "Exception: " + e.getMessage(); System.err.println(s); callbackContext.error(s); return false; } } }
package org.xblackcat.sjpu.settings.util; import javassist.*; import javassist.Modifier; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xblackcat.sjpu.builder.BuilderUtils; import org.xblackcat.sjpu.settings.NoPropertyException; import org.xblackcat.sjpu.settings.NotImplementedException; import org.xblackcat.sjpu.settings.SettingsException; import org.xblackcat.sjpu.settings.ann.*; import org.xblackcat.sjpu.settings.ann.Optional; import org.xblackcat.sjpu.settings.converter.IParser; import java.lang.reflect.*; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; /** * 12.02.13 16:40 * * @author xBlackCat */ public class ClassUtils { private static final Log log = LogFactory.getLog(ClassUtils.class); private static final String DEFAULT_DELIMITER = ","; private static final String DEFAULT_SPLITTER = ":"; public static String buildPropertyName(String prefixName, Method m) { StringBuilder propertyNameBuilder = new StringBuilder(); if (StringUtils.isNotBlank(prefixName)) { propertyNameBuilder.append(prefixName); propertyNameBuilder.append('.'); } final PropertyName field = m.getAnnotation(PropertyName.class); if (field != null && StringUtils.isNotBlank(field.value())) { propertyNameBuilder.append(field.value()); } else { final String fieldName = BuilderUtils.makeFieldName(m.getName()); boolean onHump = true; // Generate a property name from field name for (char c : fieldName.toCharArray()) { if (Character.isUpperCase(c)) { if (!onHump) { propertyNameBuilder.append('.'); onHump = true; } } else { onHump = false; } propertyNameBuilder.append(Character.toLowerCase(c)); } } return propertyNameBuilder.toString(); } public static <T> List<Object> buildConstructorParameters( ClassPool pool, Class<T> clazz, IValueGetter properties, String prefixName ) throws SettingsException { List<Object> values = new ArrayList<>(); for (Method method : clazz.getMethods()) { if (ignoreMethod(method)) { continue; } final GroupField groupField = method.getAnnotation(GroupField.class); try { final Object value; if (groupField != null) { value = getGroupFieldValue(pool, groupField.value(), properties, prefixName, method); } else { final Class<?> returnType = method.getReturnType(); final String delimiter; delimiter = getDelimiter(method); final IParser<?> parser = getCustomConverter(method); if (parser != null && returnType.isAssignableFrom(parser.getReturnType())) { String valueStr = getStringValue(properties, prefixName, method); if (valueStr != null) { try { value = parser.apply(valueStr); } catch (RuntimeException e) { throw new SettingsException("Can't parse value " + valueStr + " to type " + returnType.getName(), e); } } else { value = null; } } else if (returnType.isArray()) { value = getArrayFieldValue(properties, prefixName, method, delimiter, parser); } else if (Collection.class.isAssignableFrom(returnType)) { value = getCollectionFieldValue(properties, prefixName, method, delimiter, parser); } else if (Map.class.isAssignableFrom(returnType)) { value = getMapFieldValue(properties, prefixName, method, delimiter); } else if (returnType.isInterface()) { final String propertyName = buildPropertyName(prefixName, method); @SuppressWarnings("unchecked") final Constructor<?> c = getSettingsConstructor(returnType, pool); value = initialize(c, buildConstructorParameters(pool, returnType, properties, propertyName)); } else { String valueStr = getStringValue(properties, prefixName, method); if (valueStr != null) { try { value = ParserUtils.getToObjectConverter(returnType).apply(valueStr); } catch (RuntimeException e) { throw new SettingsException("Can't parse value " + valueStr + " to type " + returnType.getName(), e); } } else { value = null; } } } values.add(value); } catch (NoPropertyException e) { if (method.getReturnType().isPrimitive() || method.getAnnotation(org.xblackcat.sjpu.settings.ann.Optional.class) == null) { throw e; } // Optional values could be omitted values.add(null); } } return values; } public static IParser<?> getCustomConverter(Method method) throws SettingsException { final ParseWith parseWith = method.getAnnotation(ParseWith.class); if (parseWith == null) { return null; } final IParser<?> parser; final Class<? extends IParser<?>> aClass = parseWith.value(); try { // Check for default constructor aClass.getConstructor(); parser = aClass.newInstance(); } catch (InstantiationException e) { throw new SettingsException("Failed to instantiate converter class " + aClass, e); } catch (IllegalAccessException e) { throw new SettingsException("Failed to initialize converter class " + aClass, e); } catch (NoSuchMethodException e) { throw new SettingsException("Converter class " + aClass + " should have default public constructor", e); } return parser; } public static String getDelimiter(Method method) { Delimiter delimiterAnn = method.getAnnotation(Delimiter.class); if (delimiterAnn == null) { return DEFAULT_DELIMITER; } else { return delimiterAnn.value(); } } public static String getSplitter(Method method) { Splitter splitterAnn = method.getAnnotation(Splitter.class); if (splitterAnn == null) { return DEFAULT_SPLITTER; } else { return splitterAnn.value(); } } public static synchronized <T> Constructor<T> getSettingsConstructor(Class<T> clazz, ClassPool pool) throws SettingsException { final String implName = clazz.getName() + "$Impl"; Class<?> aClass; try { aClass = Class.forName(implName, true, pool.getClassLoader()); } catch (ClassNotFoundException e) { try { CtClass settingsClass = buildSettingsClass(clazz, pool); aClass = settingsClass.toClass(); settingsClass.detach(); } catch (CannotCompileException ee) { throw new SettingsException("Can't initialize a constructor for generated class " + clazz.getName(), ee); } } // A class with a single constructor has been generated @SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"}) final Constructor<T> constructor = (Constructor<T>) aClass.getConstructors()[0]; return constructor; } private static <T> CtClass buildSettingsClass(Class<T> clazz, ClassPool pool) throws SettingsException { if (!clazz.isInterface()) { throw new SettingsException("Only annotated interfaces are supported. " + clazz.getName() + " is a class."); } final CtClass settingsClass; try { final CtClass settingsInterface = pool.get(clazz.getName()); settingsClass = settingsInterface.makeNestedClass("Impl", true); settingsClass.addInterface(settingsInterface); } catch (NotFoundException e) { throw new SettingsException("Can't generate class for settings", e); } List<String> fieldNames = new ArrayList<>(); StringBuilder toStringBody = new StringBuilder(); StringBuilder equalsBody = new StringBuilder(); StringBuilder constructorBody = new StringBuilder(); List<CtClass> constructorParameters = new ArrayList<>(); constructorBody.append("{\n"); toStringBody.append("{\nreturn \""); toStringBody.append(clazz.getSimpleName()); toStringBody.append(" [\""); final String className = settingsClass.getName(); equalsBody.append( "{\n" + "if (this == $1) return true;\n" + "if ($1 == null || getClass() != $1.getClass()) return false;\n" + "final " ); equalsBody.append(className); equalsBody.append(" that = ("); equalsBody.append(className); equalsBody.append(") $1;\n return true"); int idx = 1; for (Method m : clazz.getMethods()) { final String mName = m.getName(); final Class<?> returnType = m.getReturnType(); if (m.isDefault()) { if (log.isTraceEnabled()) { log.trace("Ignore default method " + m + " in interface " + clazz.getName()); } continue; } if (m.isAnnotationPresent(Ignore.class)) { final CtClass retType; try { retType = pool.get(returnType.getName()); } catch (NotFoundException e) { throw new SettingsException("Somehow a class " + returnType.getName() + " can't be found", e); } try { final CtMethod dumbMethod = CtNewMethod.make( Modifier.FINAL | Modifier.PUBLIC, retType, mName, BuilderUtils.toCtClasses(pool, m.getParameterTypes()), BuilderUtils.toCtClasses(pool, m.getExceptionTypes()), "{ throw new " + NotImplementedException.class.getName() + "(\"Method " + mName + " is excluded from generation\"); }", settingsClass ); settingsClass.addMethod(dumbMethod); } catch (NotFoundException | CannotCompileException e) { throw new SettingsException("Can't add a dumb method " + mName + " to generated class", e); } continue; } if (m.getParameterTypes().length > 0) { throw new SettingsException("Method " + m.toString() + " has parameters - can't be processed as getter"); } final String fieldName = "__" + BuilderUtils.makeFieldName(mName); if (log.isTraceEnabled()) { log.trace("Generate a field " + fieldName + " for class " + clazz.getName() + " of type " + returnType.getName()); } final CtClass retType; try { retType = pool.get(returnType.getName()); } catch (NotFoundException e) { throw new SettingsException("Somehow a class " + returnType.getName() + " can't be found", e); } final boolean returnTypeArray = returnType.isArray(); try { CtField f = new CtField(retType, fieldName, settingsClass); f.setModifiers(Modifier.FINAL | Modifier.PRIVATE); settingsClass.addField(f); final String body; if (returnTypeArray) { body = "{ return ($r) this." + fieldName + ".clone()" + "; }"; } else { body = "{ return this." + fieldName + "" + "; }"; } if (log.isTraceEnabled()) { log.trace("Implement method " + clazz.getName() + "#" + mName + "() " + body); } final CtMethod getter = CtNewMethod.make( Modifier.FINAL | Modifier.PUBLIC, retType, mName, BuilderUtils.EMPTY_LIST, BuilderUtils.EMPTY_LIST, body, settingsClass ); settingsClass.addMethod(getter); } catch (CannotCompileException e) { throw new SettingsException("Can't add a field " + fieldName + " to generated class", e); } if (returnTypeArray) { constructorBody.append("if ($"); constructorBody.append(idx); constructorBody.append(" != null) {\n"); constructorBody.append("this."); constructorBody.append(fieldName); constructorBody.append(" = ("); constructorBody.append(BuilderUtils.getName(returnType)); constructorBody.append(")$"); constructorBody.append(idx); constructorBody.append(".clone();\n"); constructorBody.append("} else {\n"); constructorBody.append("this."); constructorBody.append(fieldName); constructorBody.append(" = null;\n}\n"); } else { constructorBody.append("this."); constructorBody.append(fieldName); constructorBody.append(" = $"); constructorBody.append(idx); constructorBody.append(";\n"); } equalsBody.append(" &&\n"); if (returnTypeArray) { equalsBody.append("java.util.Arrays.equals("); equalsBody.append(fieldName); equalsBody.append(", that."); equalsBody.append(fieldName); equalsBody.append(")"); } else if (returnType.isPrimitive() || returnType.isEnum()) { equalsBody.append(fieldName); equalsBody.append(" == "); equalsBody.append(fieldName); equalsBody.append(""); } else { equalsBody.append("java.util.Objects.equals("); equalsBody.append(fieldName); equalsBody.append(", that."); equalsBody.append(fieldName); equalsBody.append(")"); } fieldNames.add("($w)" + fieldName); toStringBody.append(" + \""); toStringBody.append(fieldName); toStringBody.append(" ("); toStringBody.append(buildPropertyName(null, m)); toStringBody.append(") = \\\"\" + java.lang.String.valueOf(this."); toStringBody.append(fieldName); toStringBody.append(") + \"\\\"; \""); constructorParameters.add(retType); idx++; } if (idx == 1) { throw new SettingsException("Can't load settings to a class without properties. Class " + className); } constructorBody.append("}"); toStringBody.setLength(toStringBody.length() - 3); toStringBody.append("]\";\n}"); equalsBody.append(";\n}"); try { if (log.isTraceEnabled()) { log.trace("Generated method " + clazz.getName() + "#equals() " + equalsBody.toString()); } final CtMethod equals = CtNewMethod.make( Modifier.FINAL | Modifier.PUBLIC, pool.get(boolean.class.getName()), "equals", pool.get(new String[]{"java.lang.Object"}), BuilderUtils.EMPTY_LIST, equalsBody.toString(), settingsClass ); settingsClass.addMethod(equals); String hashCodeBody = "{\n" + "return java.util.Objects.hash(new java.lang.Object[]{\n" + String.join(",\n", fieldNames) + "\n});\n}"; if (log.isTraceEnabled()) { log.trace("Generated method " + clazz.getName() + "#hashCode() " + hashCodeBody); } final CtMethod hashCode = CtNewMethod.make( Modifier.FINAL | Modifier.PUBLIC, pool.get(int.class.getName()), "hashCode", BuilderUtils.EMPTY_LIST, BuilderUtils.EMPTY_LIST, hashCodeBody, settingsClass ); settingsClass.addMethod(hashCode); if (log.isTraceEnabled()) { log.trace("Generated method " + clazz.getName() + "#toString() " + toStringBody.toString()); } final CtMethod toString = CtNewMethod.make( Modifier.FINAL | Modifier.PUBLIC, pool.get(String.class.getName()), "toString", BuilderUtils.EMPTY_LIST, BuilderUtils.EMPTY_LIST, toStringBody.toString(), settingsClass ); settingsClass.addMethod(toString); if (log.isTraceEnabled()) { log.trace("Generated constructor " + clazz.getName() + "() " + constructorBody.toString()); } final CtConstructor constructor = CtNewConstructor.make( constructorParameters.toArray(new CtClass[constructorParameters.size()]), BuilderUtils.EMPTY_LIST, constructorBody.toString(), settingsClass ); settingsClass.addConstructor(constructor); return settingsClass; } catch (CannotCompileException e) { throw new SettingsException("Can't generate a constructor for generated class " + clazz.getName(), e); } catch (NotFoundException e) { throw new SettingsException("Can't generate toString() method for generated class " + clazz.getName(), e); } } public static String getStringValue(IValueGetter properties, String prefixName, Method m) throws SettingsException { final Class<?> returnType = m.getReturnType(); final String propertyName = buildPropertyName(prefixName, m); String valueStr = properties.get(propertyName); if (log.isTraceEnabled()) { log.trace("Property " + propertyName + " for method " + m.getName() + " is " + valueStr); } if (valueStr == null) { // Check for default value final DefaultValue field = m.getAnnotation(DefaultValue.class); final boolean optional = m.isAnnotationPresent(Optional.class); final String defValue = field == null ? null : field.value(); if (StringUtils.isEmpty(defValue)) { if (returnType.isPrimitive() || !optional && defValue == null) { throw new NoPropertyException(propertyName, m); } } else { if (log.isTraceEnabled()) { log.trace("Using default value " + defValue + " for property " + propertyName); } } valueStr = defValue; } return valueStr; } @SuppressWarnings("unchecked") private static Object getArrayFieldValue( IValueGetter properties, String prefixName, Method method, String delimiter, IParser<?> parser ) throws SettingsException { final Class<?> returnType = method.getReturnType(); Class<?> targetType = returnType.getComponentType(); if (parser != null) { if (!targetType.isAssignableFrom(parser.getReturnType())) { throw new SettingsException( "Converter return type " + parser.getReturnType().getName() + " can't be assigned to array component type" + returnType.getName() ); } } String arrayString = getStringValue(properties, prefixName, method); if (targetType == null) { throw new IllegalStateException("Array component type is null? " + returnType.getName()); } String[] values = StringUtils.splitByWholeSeparator(arrayString, delimiter); final int arrayLength; if (values != null) { arrayLength = values.length; } else { arrayLength = 0; } Object o = Array.newInstance(targetType, arrayLength); if (arrayLength == 0) { return o; } final ParserUtils.ArraySetter setter; if (parser == null) { setter = ParserUtils.getArraySetter(targetType); } else { setter = ParserUtils.getArraySetter(parser); } int i = 0; while (i < arrayLength) { String valueStr = values[i]; try { if (valueStr == null) { Array.set(o, i, null); } else { setter.set(o, i, valueStr); } } catch (RuntimeException e) { throw new SettingsException("Can't parse value " + valueStr + " to type " + targetType.getName(), e); } i++; } return o; } @SuppressWarnings("unchecked") private static Object getCollectionFieldValue( IValueGetter properties, String prefixName, Method method, String delimiter, IParser<?> parser ) throws SettingsException { String arrayString = getStringValue(properties, prefixName, method); if (arrayString == null) { return null; } final Class<?> returnRawType; final Class<?> proposalReturnClass; if (method.getGenericReturnType() instanceof ParameterizedType) { final ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType(); if (!(returnType.getRawType() instanceof Class)) { throw new SettingsException("Raw type is not a class " + returnType + " in method " + method.toString()); } returnRawType = (Class) returnType.getRawType(); proposalReturnClass = BuilderUtils.detectTypeArgClass(returnType); } else { returnRawType = (Class<?>) method.getGenericReturnType(); proposalReturnClass = null; } final Class<?> targetType; CollectionOf collectionOf = method.getAnnotation(CollectionOf.class); if (collectionOf != null) { targetType = collectionOf.value(); } else { targetType = proposalReturnClass; } if (proposalReturnClass != null) { if (!targetType.isAssignableFrom(proposalReturnClass)) { throw new SettingsException( "Specified return object " + targetType.getName() + " cannot be casted to " + proposalReturnClass.getName() ); } } if (targetType == null) { throw new SettingsException( "Cannot detect component type of list. Please, use @CollectionOf annotation for method " + method.toString() ); } if (parser != null) { if (!targetType.isAssignableFrom(parser.getReturnType())) { throw new SettingsException( "Converter return type " + parser.getReturnType().getName() + " can't be assigned to array component type" + targetType.getName() + " for method " + method.getName() ); } } String[] values = StringUtils.splitByWholeSeparator(arrayString, delimiter); final Collection collection; final boolean isList; if (returnRawType.equals(Set.class)) { if (values == null || values.length == 0) { return Collections.emptySet(); } isList = false; if (Enum.class.isAssignableFrom(targetType)) { collection = EnumSet.noneOf((Class<Enum>) targetType); } else { collection = new LinkedHashSet<>(values.length); } } else if (returnRawType.equals(List.class) || returnRawType.equals(List.class)) { if (values == null || values.length == 0) { return Collections.emptyList(); } isList = true; collection = new ArrayList<>(values.length); } else { throw new SettingsException( "Please, specify container by interface " + Collection.class.getName() + ", " + List.class.getName() + " or " + Set.class.getName() + " as return type for collections." ); } if (targetType.isInterface() || java.lang.reflect.Modifier.isAbstract(targetType.getModifiers())) { throw new SettingsException("Only non-abstract classes could be specified as collection elements"); } final Function<String, ?> converter; if (parser == null) { converter = ParserUtils.getToObjectConverter(targetType); } else { converter = parser; } for (String valueStr : values) { try { if (valueStr == null) { collection.add(null); } else { collection.add(converter.apply(valueStr)); } } catch (RuntimeException e) { throw new SettingsException("Can't parse value " + valueStr + " to type " + targetType.getName(), e); } } if (isList) { return Collections.unmodifiableList((List<?>) collection); } else { return Collections.unmodifiableSet((Set<?>) collection); } } @SuppressWarnings("unchecked") private static Map getMapFieldValue( IValueGetter properties, String prefixName, Method method, String delimiter ) throws SettingsException { String arrayString = getStringValue(properties, prefixName, method); if (arrayString == null) { return null; } final Class<?> returnRawType; final Class<?> proposalKeyClass; final Class<?> proposalValueClass; if (method.getGenericReturnType() instanceof ParameterizedType) { final ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType(); if (!(returnType.getRawType() instanceof Class)) { throw new SettingsException("Raw type is not a class " + returnType + " in method " + method.toString()); } returnRawType = (Class) returnType.getRawType(); Class<?>[] detectTypeArgsClass = BuilderUtils.detectTypeArgsClass(returnType, 2); proposalKeyClass = detectTypeArgsClass[0]; proposalValueClass = detectTypeArgsClass[1]; } else { returnRawType = (Class<?>) method.getGenericReturnType(); proposalKeyClass = null; proposalValueClass = null; } if (!Map.class.equals(returnRawType)) { throw new SettingsException("Please, specify general interface for maps as return type for method " + method.toString()); } final Class<?> targetKeyType; MapKey mapKey = method.getAnnotation(MapKey.class); if (mapKey != null) { targetKeyType = mapKey.value(); } else { targetKeyType = proposalKeyClass; } if (proposalKeyClass != null) { if (!targetKeyType.isAssignableFrom(proposalKeyClass)) { throw new SettingsException( "Specified return object " + targetKeyType.getName() + " cannot be casted to " + proposalKeyClass.getName() ); } } if (targetKeyType == null) { throw new SettingsException( "Cannot detect key component type of map. Please, use @MapKey annotation for method " + method.toString() ); } final Class<?> targetValueType; MapValue collectionOf = method.getAnnotation(MapValue.class); if (collectionOf != null) { targetValueType = collectionOf.value(); } else { targetValueType = proposalValueClass; } if (proposalValueClass != null) { if (!targetValueType.isAssignableFrom(proposalValueClass)) { throw new SettingsException( "Specified return object " + targetValueType.getName() + " cannot be casted to " + proposalValueClass.getName() ); } } if (targetValueType == null) { throw new SettingsException( "Cannot detect value component type of map. Please, use @MapValue annotation for method " + method.toString() ); } String[] values = StringUtils.splitByWholeSeparator(arrayString, delimiter); if (values == null || values.length == 0) { return Collections.emptyMap(); } final Map map; if (Enum.class.isAssignableFrom(targetKeyType)) { map = new EnumMap(targetKeyType); } else { map = new LinkedHashMap(values.length); } Function<String, ?> keyParser = ParserUtils.getToObjectConverter(targetKeyType); Function<String, ?> valueParser = ParserUtils.getToObjectConverter(targetValueType); final String splitter = getSplitter(method); for (String part : values) { String[] parts = StringUtils.splitByWholeSeparator(part, splitter, 2); final String keyString; final String valueString; if (parts.length < 2) { keyString = parts[0]; valueString = null; } else { keyString = parts[0]; valueString = parts[1]; } try { Object key = keyParser.apply(keyString); if (valueString == null) { map.put(key, null); } else { map.put(key, valueParser.apply(valueString)); } } catch (RuntimeException e) { throw new SettingsException("Can't parse value " + valueString + " to type " + targetKeyType.getName(), e); } } return Collections.unmodifiableMap(map); } private static <T> Map<String, T> getGroupFieldValue( ClassPool pool, Class<T> clazz, IValueGetter properties, String prefixName, Method method ) throws SettingsException { final Class<?> returnType = method.getReturnType(); if (!Map.class.equals(returnType)) { throw new SettingsException("Group field should have java.util.Map return type only"); } @SuppressWarnings("unchecked") final Constructor<T> c = getSettingsConstructor(clazz, pool); final String propertyName = buildPropertyName(prefixName, method); final String propertyNameDot = propertyName + "."; Set<String> propertyNames = properties.keySet().stream().filter(name -> name.startsWith(propertyNameDot)).collect(Collectors.toSet()); // Search for possible prefixes Set<String> prefixes = new HashSet<>(); for (Method mm : clazz.getMethods()) { if (ignoreMethod(mm)) { continue; } final String suffix = "." + buildPropertyName(null, mm); for (String name : propertyNames) { if (name.endsWith(suffix)) { final String prefix; final int prefixLen = propertyNameDot.length(); final int cutLen = name.length() - suffix.length(); if (prefixLen >= cutLen) { prefix = ""; } else { prefix = name.substring(prefixLen, cutLen); } prefixes.add(prefix); } } } boolean required = method.getAnnotation(org.xblackcat.sjpu.settings.ann.Optional.class) == null; if (required && !prefixes.contains("")) { throw new SettingsException("A default group set is required for method " + method.getName()); } Map<String, T> result = new HashMap<>(); for (String p : prefixes) { final String realPrefix; if (StringUtils.isNotBlank(p)) { realPrefix = propertyNameDot + p; } else { realPrefix = propertyName; } result.put(p, initialize(c, buildConstructorParameters(pool, clazz, properties, realPrefix))); } return Collections.unmodifiableMap(result); } public static <T> T initialize(Constructor<T> c, List<Object> values) throws SettingsException { try { final Object[] array = values.toArray(new Object[values.size()]); return c.newInstance(array); } catch (InstantiationException e) { throw new SettingsException("Can't make a new instance of my own class :(", e); } catch (IllegalAccessException e) { throw new SettingsException("Can't get access to my own class :(", e); } catch (InvocationTargetException e) { throw new SettingsException("My class produces an exception :(", e); } } public static <T> boolean allMethodsHaveDefaults(Class<T> clazz) { for (Method m : clazz.getDeclaredMethods()) { if (ignoreMethod(m)) { continue; } if (!m.isAnnotationPresent(DefaultValue.class) && !m.isAnnotationPresent(Optional.class)) { return false; } } return true; } static boolean ignoreMethod(Method method) { return method.isDefault() || method.isAnnotationPresent(Ignore.class); } }
package org.jetel.component; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.formatter.DelimitedDataFormatterNIO; import org.jetel.data.formatter.FixLenDataFormatter; import org.jetel.data.formatter.Formatter; import org.jetel.data.parser.DelimitedDataParserNIO; import org.jetel.data.parser.FixLenDataParser; import org.jetel.data.parser.Parser; import org.jetel.exception.ComponentNotReadyException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.OutputPort; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.ComponentXMLAttributes; import org.jetel.util.SynchronizeUtils; import org.w3c.dom.Element; /** * <h3>System Execute Component</h3> * <!-- This component executes system command.--> * * <table border="1"> * * <th> * Component: * </th> * <tr><td> * <h4><i>Name:</i> </h4></td><td>SystemExecute</td> * </tr> * <tr><td><h4><i>Category:</i> </h4></td><td></td> * </tr> * <tr><td><h4><i>Description:</i> </h4></td> * <td> * This component executes system command.<br> * </td> * </tr> * <tr><td><h4><i>Inputs:</i> </h4></td> * <td> * [0]- input records for system command<br> * </td></tr> * <tr><td> <h4><i>Outputs:</i> </h4> * </td> * <td> * [0] - output stream from system command * </td></tr> * <tr><td><h4><i>Comment:</i> </h4> * </td> * <td></td> * </tr> * </table> * <br> * <table border="1"> * <th>XML attributes:</th> * <tr><td><b>type</b></td><td>SYS_EXECUTE</td></tr> * <tr><td><b>command</b></td><td> command to be execute by system</td></tr> * <tr><td><b>errorLinesNumber</b></td><td> number of lines that are print * out if command finishes with errors</td></tr> * </table> * <h4>Example:</h4> <pre>&lt;Node id="SYS_EXECUTE0" type="SYS_EXECUTE"&gt; * &lt;attr name="errorLinesNumber"&gt;3&lt;/attr&gt; * &lt;attr name="command"&gt;rm test.txt &lt;/attr&gt; * &lt;/Node&gt;</pre> * * @author avackova * */ public class SystemExecute extends Node{ private static final String XML_COMMAND_ATTRIBUTE = "command"; private static final String XML_ERROR_LINES_ATTRIBUTE = "errorLinesNumber"; public final static String COMPONENT_TYPE = "SYS_EXECUTE"; private final static int INPUT_PORT = 0; private final static int OUTPUT_PORT = 0; private final static int ERROR_LINES=2; private String command; private int errorLinesNumber; private int exitValue; private Parser parser; private Formatter formatter; static Log logger = LogFactory.getLog(SystemExecute.class); public SystemExecute(String id,String command) { super(id); this.command=command; errorLinesNumber=2; } public SystemExecute(String id,String command,int errorLinesNumber) { super(id); this.command=command; this.errorLinesNumber=errorLinesNumber; } public void run() { resultCode = Node.RESULT_OK; //Creating and initializing record from input port DataRecord in_record=null; InputPort inPort = getInputPort(INPUT_PORT); //If there is input port read metadadata and initialize in_record if (inPort!=null) { DataRecordMetadata meta=inPort.getMetadata(); in_record = new DataRecord(meta); in_record.init(); if (meta.getRecType()==DataRecordMetadata.DELIMITED_RECORD) { formatter=new DelimitedDataFormatterNIO(); }else { formatter=new FixLenDataFormatter(); } }else{ formatter=null; } //Creating and initializing record to otput port DataRecord out_record=null; OutputPort outPort=getOutputPort(OUTPUT_PORT); //If there is output port read metadadata and initialize in_record if (outPort!=null) { DataRecordMetadata meta=outPort.getMetadata(); out_record= new DataRecord(meta); out_record.init(); if (meta.getRecType()==DataRecordMetadata.DELIMITED_RECORD) { parser=new DelimitedDataParserNIO(); }else { parser=new FixLenDataParser(); } }else{ parser=null; } Runtime r=Runtime.getRuntime(); try{ Process process=r.exec(command); OutputStream process_in=process.getOutputStream(); InputStream process_out=process.getInputStream(); InputStream process_err=process.getErrorStream(); // If there is input port read records and write them to input stream of the process GetData getData=null; if (inPort!=null) { formatter.open(process_in,getInputPort(INPUT_PORT).getMetadata()); getData=new GetData(inPort, in_record, formatter); getData.start(); } //If there is output port read output from process and send it to output ports SendData sendData=null; if (outPort!=null){ parser.open(process_out, getOutputPort(OUTPUT_PORT).getMetadata()); sendData=new SendData(outPort,out_record,parser); //send all out_records to output ports sendData.start(); } BufferedReader err=new BufferedReader(new InputStreamReader(process_err)); String line; StringBuffer errmes=new StringBuffer(); int i=0; while (((line=err.readLine())!=null)&&i++<Math.max(errorLinesNumber,ERROR_LINES)){ if (i<=errorLinesNumber) logger.debug(line); if (i<=ERROR_LINES) errmes.append(line+"\n"); } if (ERROR_LINES<i) errmes.append(".......\n"); err.close(); process_err.close(); resultMsg=errmes.toString(); exitValue=process.waitFor(); if (getData!=null || sendData!=null){ boolean stoped=false; if (getData!=null && getData.getResultCode()==Node.RESULT_RUNNING) { getData.stop_it(); stoped=true; } if (sendData!=null && sendData.getResultCode()==Node.RESULT_RUNNING) { sendData.stop_it(); stoped=true; } if (stoped) Thread.sleep(10000); if (getData!=null && getData.getResultCode()==Node.RESULT_RUNNING) getData.interrupt(); if (sendData!=null && sendData.getResultCode()==Node.RESULT_RUNNING) sendData.interrupt(); if (getData!=null && getData.getResultCode()!=Node.RESULT_OK) { resultMsg = resultMsg + "\n" + getData.getResultMsg(); resultCode = Node.RESULT_ERROR; } if (sendData!=null && sendData.getResultCode()!=Node.RESULT_OK) { resultMsg = resultMsg + "\n" + sendData.getResultMsg(); resultCode = Node.RESULT_ERROR; } } }catch(IOException ex){ ex.printStackTrace(); resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; }catch(Exception ex){ ex.printStackTrace(); resultMsg = ex.getClass().getName()+" : "+ ex.getMessage(); resultCode = Node.RESULT_FATAL_ERROR; return; } broadcastEOF(); if (!runIt) { resultMsg = resultMsg + "\n" + "STOPPED"; resultCode=Node.RESULT_ERROR; } if (exitValue!=0){ resultCode = Node.RESULT_ERROR; } if (resultCode==Node.RESULT_OK){ resultMsg = "OK"; } } public void init() throws ComponentNotReadyException { if (getInPorts().size()>1) throw new ComponentNotReadyException(getId() + ": too many input ports"); if (getOutPorts().size()>1) throw new ComponentNotReadyException(getId() + ": too many otput ports"); } public String getType(){ return COMPONENT_TYPE; } public boolean checkConfig() { return true; } public static Node fromXML(TransformationGraph graph, org.w3c.dom.Node nodeXML) { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); try { return new SystemExecute(xattribs.getString(Node.XML_ID_ATTRIBUTE),xattribs.getString(XML_COMMAND_ATTRIBUTE),xattribs.getInteger(XML_ERROR_LINES_ATTRIBUTE,2)); } catch (Exception ex) { System.err.println(COMPONENT_TYPE + ":" + ((xattribs.exists(XML_ID_ATTRIBUTE)) ? xattribs.getString(Node.XML_ID_ATTRIBUTE) : " unknown ID ") + ":" + ex.getMessage()); return null; } } public void toXML(Element xmlElement) { super.toXML(xmlElement); xmlElement.setAttribute(XML_COMMAND_ATTRIBUTE,command); xmlElement.setAttribute(XML_ERROR_LINES_ATTRIBUTE,String.valueOf(errorLinesNumber)); } private static class GetData extends Thread { InputPort inPort; DataRecord in_record; Formatter formatter; String resultMsg=null; int resultCode=Node.RESULT_OK; volatile boolean runIt; GetData(InputPort inPort,DataRecord in_record,Formatter formatter){ super(); this.in_record=in_record; this.inPort=inPort; this.formatter=formatter; runIt=true; } public void stop_it(){ runIt=false; } public void run() { resultCode=Node.RESULT_RUNNING; try{ while ((( in_record=inPort.readRecord(in_record))!= null ) && runIt) { formatter.write(in_record); SynchronizeUtils.cloverYield(); } formatter.close(); }catch(IOException ex){ resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; }catch(InterruptedException ex){ resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; } resultCode=Node.RESULT_OK; } public int getResultCode() { return resultCode; } public String getResultMsg() { return resultMsg; } } private static class SendData extends Thread { DataRecord out_record; OutputPort outPort; Parser parser; String resultMsg=null; int resultCode=Node.RESULT_OK; volatile boolean runIt; SendData(OutputPort outPort,DataRecord out_record,Parser parser){ super(); this.out_record=out_record; this.outPort=outPort; this.parser=parser; this.runIt=true; } public void stop_it(){ runIt=false; } public void run() { resultCode=Node.RESULT_RUNNING; try{ while (((out_record = parser.getNext(out_record)) != null) && runIt) { //broadcast the record to all connected Edges outPort.writeRecord(out_record); SynchronizeUtils.cloverYield(); } }catch(IOException ex){ resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; }catch(Exception ex){ resultMsg = ex.getMessage(); resultCode = Node.RESULT_ERROR; } resultCode=Node.RESULT_OK; } /** * @return Returns the resultCode. */ public int getResultCode() { return resultCode; } public String getResultMsg() { return resultMsg; } } }
package com.codeforces.commons.xml; import com.codeforces.commons.io.FileUtil; import com.codeforces.commons.io.IoUtil; import com.codeforces.commons.process.ThreadUtil; import org.junit.Assert; import org.junit.Test; import org.w3c.dom.NodeList; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.*; public class XmlUtilTest { @Test public void testExtractFromXml() throws IOException { File tempDir = null; try { tempDir = FileUtil.createTemporaryDirectory("test-xml"); File testFile = new File(tempDir, "test.xml"); FileUtil.writeFile(testFile, getBytes("test.xml")); Assert.assertEquals( "Failed XmlUtil.extractFromXml for XPath '/a/bs/b[1]/@attr1'.", "attr1v1", XmlUtil.extractFromXml(testFile, "/a/bs/b[1]/@attr1", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml for XPath '/a/bs/b[2]/@attr1'.", "attr1v2", XmlUtil.extractFromXml(testFile, "/a/bs/b[2]/@attr1", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml for XPath '/a/bs/b[@attr1='attr1v1']/@attr2'.", "attr2v1", XmlUtil.extractFromXml(testFile, "/a/bs/b[@attr1='attr1v1']/@attr2", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml for XPath '/a/bs/b[@attr1='attr1v1']/@attr3'.", Integer.valueOf(1), XmlUtil.extractFromXml(testFile, "/a/bs/b[@attr1='attr1v1']/@attr3", Integer.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml for XPath '/a/d/@attr6'.", "attr6v", XmlUtil.extractFromXml(testFile, "/a/d/@attr6", String.class) ); } finally { FileUtil.deleteTotallyAsync(tempDir); } } @Test public void testUpdateXml() throws IOException { File tempDir = null; try { tempDir = FileUtil.createTemporaryDirectory("test-xml"); File testFile = new File(tempDir, "test.xml"); FileUtil.writeFile(testFile, getBytes("test.xml")); XmlUtil.updateXml(testFile, "/a/c/@intAttr", "7"); XmlUtil.updateXml(testFile, "/a/c/@strAttr", "cabaca"); XmlUtil.updateXml(testFile, "/a/c/@boolAttr", "true"); XmlUtil.updateXml(testFile, "/a/d/@attr5", "newValue"); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.updateXml for XPath '/a/c/@intAttr'.", Integer.valueOf(7), XmlUtil.extractFromXml(testFile, "/a/c/@intAttr", Integer.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.updateXml for XPath '/a/c/@strAttr'.", "cabaca", XmlUtil.extractFromXml(testFile, "/a/c/@strAttr", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.updateXml for XPath '/a/c/@boolAttr'.", Boolean.TRUE, XmlUtil.extractFromXml(testFile, "/a/c/@boolAttr", Boolean.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.updateXml for XPath '/a/c/@notExistingAttr'.", Boolean.FALSE, XmlUtil.extractFromXml(testFile, "/a/c/@notExistingAttr", Boolean.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.updateXml for XPath '/a/d/@attr5'.", "newValue", XmlUtil.extractFromXml(testFile, "/a/d/@attr5", String.class) ); } finally { FileUtil.deleteTotallyAsync(tempDir); } } @Test public void testEnsureXmlElementExist() throws IOException { File tempDir = null; try { tempDir = FileUtil.createTemporaryDirectory("test-xml"); File testFile = new File(tempDir, "test.xml"); FileUtil.writeFile(testFile, getBytes("test.xml")); Map<String, String> filterAttributes = new HashMap<>(); filterAttributes.put("foo", "fooValue"); filterAttributes.put("bar", "barValue"); XmlUtil.ensureXmlElementExists(testFile, "/a", "e", filterAttributes, filterAttributes, null); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e'.", 1, XmlUtil.extractFromXml(testFile, "/a/e", NodeList.class).getLength() ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e/@foo'.", "fooValue", XmlUtil.extractFromXml(testFile, "/a/e/@foo", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e/@bar'.", "barValue", XmlUtil.extractFromXml(testFile, "/a/e/@bar", String.class) ); Map<String, String> newAttributes = new HashMap<>(filterAttributes); newAttributes.put("baz", "bazValue"); XmlUtil.ensureXmlElementExists(testFile, "/a", "e", filterAttributes, newAttributes, null); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e'.", 1, XmlUtil.extractFromXml(testFile, "/a/e", NodeList.class).getLength() ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e/@foo'.", "fooValue", XmlUtil.extractFromXml(testFile, "/a/e/@foo", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e/@bar'.", "barValue", XmlUtil.extractFromXml(testFile, "/a/e/@bar", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e/@baz'.", "bazValue", XmlUtil.extractFromXml(testFile, "/a/e/@baz", String.class) ); filterAttributes.put("foo", "newFooValue"); newAttributes.put("foo", "newFooValue"); XmlUtil.ensureXmlElementExists(testFile, "/a", "e", filterAttributes, newAttributes, null); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e'.", 2, XmlUtil.extractFromXml(testFile, "/a/e", NodeList.class).getLength() ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e[2]/@foo'.", "newFooValue", XmlUtil.extractFromXml(testFile, "/a/e[2]/@foo", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e[2]/@bar'.", "barValue", XmlUtil.extractFromXml(testFile, "/a/e[2]/@bar", String.class) ); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.ensureXmlElementExists for XPath '/a/e[2]/@baz'.", "bazValue", XmlUtil.extractFromXml(testFile, "/a/e[2]/@baz", String.class) ); } finally { FileUtil.deleteTotallyAsync(tempDir); } } @SuppressWarnings("MessageMissingOnJUnitAssertion") @Test public void testEnsureXmlElementExistDoesntRewriteFileIfNoChanges() throws IOException { File tempDir = null; try { tempDir = FileUtil.createTemporaryDirectory("test-xml-ext"); File testFile = new File(tempDir, "test-ext.xml"); FileUtil.writeFile(testFile, getBytes("test-ext.xml")); long lastModified = testFile.lastModified(); Map<String, String> filterAttributes = new HashMap<>(); filterAttributes.put("boolAttr", "false"); filterAttributes.put("strAttr", ""); ThreadUtil.sleep(100); XmlUtil.ensureXmlElementExists(testFile, "/a", "c", filterAttributes, null, null); Assert.assertEquals(lastModified, testFile.lastModified()); ThreadUtil.sleep(100); XmlUtil.ensureXmlElementExists(testFile, "/a", "c", filterAttributes, filterAttributes, null); Assert.assertEquals(lastModified, testFile.lastModified()); ThreadUtil.sleep(100); XmlUtil.ensureXmlElementExists(testFile, "/a", "c", filterAttributes, null, new TreeSet<>(Collections.singletonList("c"))); Assert.assertEquals(lastModified, testFile.lastModified()); ThreadUtil.sleep(100); XmlUtil.ensureXmlElementExists(testFile, "/a", "c", filterAttributes, null, new TreeSet<>(Collections.singletonList("intAttr"))); Assert.assertNotEquals(lastModified, testFile.lastModified()); lastModified = testFile.lastModified(); Map<String, String> expectedAttributes = new HashMap<>(); expectedAttributes.put("x", ""); expectedAttributes.put("notBoolAttr", "false"); ThreadUtil.sleep(1); XmlUtil.ensureXmlElementExists(testFile, "/a", "c", filterAttributes, expectedAttributes, null); Assert.assertNotEquals(lastModified, testFile.lastModified()); lastModified = testFile.lastModified(); ThreadUtil.sleep(1); XmlUtil.ensureXmlElementExists(testFile, "/a", "c", expectedAttributes, null, null); Assert.assertEquals(lastModified, testFile.lastModified()); } finally { FileUtil.deleteTotallyAsync(tempDir); } } @Test public void testRemoveElementsIfExists() throws IOException { File tempDir = null; try { tempDir = FileUtil.createTemporaryDirectory("test-xml"); File testFile = new File(tempDir, "test.xml"); FileUtil.writeFile(testFile, getBytes("test.xml")); XmlUtil.removeElementsIfExists(testFile, "/a/bs/b"); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.removeElementsIfExists for XPath '/a/bs/b'.", 0, XmlUtil.extractFromXml(testFile, "/a/bs/b", NodeList.class).getLength() ); Map<String, String> newAttributes = new HashMap<>(); newAttributes.put("value", "123"); XmlUtil.ensureXmlElementExists(testFile, "/a", "e", new HashMap<>(), newAttributes, null); newAttributes.put("value2", "1234"); XmlUtil.ensureXmlElementExists(testFile, "/a", "e", new HashMap<>(), newAttributes, null); XmlUtil.removeElementsIfExists(testFile, "/a/e"); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.removeElementsIfExists for XPath '/a/e'.", 0, XmlUtil.extractFromXml(testFile, "/a/e", NodeList.class).getLength() ); XmlUtil.removeElementsIfExists(testFile, "/a/e"); Assert.assertEquals( "Failed XmlUtil.extractFromXml after XmlUtil.removeElementsIfExists for XPath '/a/e'.", 0, XmlUtil.extractFromXml(testFile, "/a/e", NodeList.class).getLength() ); } finally { FileUtil.deleteTotallyAsync(tempDir); } } @SuppressWarnings("MessageMissingOnJUnitAssertion") @Test public void testConcurrentExtractFromXml() throws Exception { File tempDir = null; try { tempDir = FileUtil.createTemporaryDirectory("test-xml"); File testFile = new File(tempDir, "test.xml"); FileUtil.writeFile(testFile, getBytes("test.xml")); int concurrency = 4 * Runtime.getRuntime().availableProcessors(); List<Thread> threads = new ArrayList<>(); for (int i = 0; i < concurrency; i++) { threads.add(new Thread(() -> { for (int i1 = 0; i1 < 100; i1++) { try { Assert.assertEquals("false", XmlUtil.extractFromXml(testFile, "/a/c/@boolAttr", String.class)); } catch (IOException e) { throw new RuntimeException(e); } } })); } threads.forEach(Thread::start); for (Thread thread : threads) { thread.join(); } } finally { FileUtil.deleteTotallyAsync(tempDir); } } private static byte[] getBytes(String resourceName) throws IOException { InputStream resourceStream = XmlUtilTest.class.getResourceAsStream( "/com/codeforces/commons/xml/" + resourceName ); try { return IoUtil.toByteArray(resourceStream); } finally { IoUtil.closeQuietly(resourceStream); } } }
package com.ForgeEssentials.core; import java.io.File; import com.ForgeEssentials.client.network.HandlerClient; import com.ForgeEssentials.core.config.FEConfig; import com.ForgeEssentials.network.HandlerServer; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.Init; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.PostInit; import cpw.mods.fml.common.Mod.PreInit; import cpw.mods.fml.common.Mod.ServerStarting; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkMod.SidedPacketHandler; import cpw.mods.fml.common.registry.GameRegistry; /** * Main mod class */ @NetworkMod(clientSideRequired = false, serverSideRequired = false, clientPacketHandlerSpec = @SidedPacketHandler(channels = { "ForgeEssentials" }, packetHandler = HandlerClient.class), serverPacketHandlerSpec = @SidedPacketHandler(channels = { "ForgeEssentials" }, packetHandler = HandlerServer.class)) @Mod(modid = "ForgeEssentials", name = "Forge Essentials", version = "0.0.1") public class ForgeEssentials { @SidedProxy(clientSide = "com.ForgeEssentials.client.core.ProxyClient", serverSide = "com.ForgeEssentials.core.ProxyCommon") public static ProxyCommon proxy; @Instance(value = "ForgeEssentials") public static ForgeEssentials instance; public static FEConfig config; public ModuleLauncher mdlaunch; public static boolean verCheck = true; //public LibraryDetector libdetect; public static final File FEDIR = new File("./ForgeEssentials/"); @PreInit public void preInit(FMLPreInitializationEvent e) { // check directory constants and create... if (!FEDIR.exists() || !FEDIR.isDirectory()) FEDIR.mkdir(); if (!PlayerInfo.FESAVES.exists() || !PlayerInfo.FESAVES.isDirectory()) PlayerInfo.FESAVES.mkdir(); config = new FEConfig(); if (verCheck) Version.checkVersion(); mdlaunch = new ModuleLauncher(); mdlaunch.preLoad(e); } @Init public void load(FMLInitializationEvent e) { proxy.load(e); mdlaunch.load(e); GameRegistry.registerPlayerTracker(new PlayerTracker()); } @PostInit public void postLoad (FMLPostInitializationEvent e){ //needs some work done //libdetect = new LibraryDetector(); //libdetect.detect(); } @ServerStarting public void serverStarting(FMLServerStartingEvent e) { mdlaunch.serverStarting(e); } }
package nl.mpi.arbil.FieldEditors; import java.awt.BorderLayout; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameEvent; import nl.mpi.arbil.ImdiField; import nl.mpi.arbil.ImdiTable; import nl.mpi.arbil.ImdiVocabularies; import nl.mpi.arbil.LinorgWindowManager; import nl.mpi.arbil.data.ImdiTreeObject; public class ArbilLongFieldEditor { ImdiTable parentTable = null; int selectedField = -1; Object[] cellValue; JTextField keyEditorFields[] = null; JTextArea fieldEditors[] = null; JComboBox fieldLanguageBoxs[] = null; public ArbilLongFieldEditor(ImdiTable parentTableLocal) { parentTable = parentTableLocal; } public void showEditor(Object[] cellValueLocal, String currentEditorText) { cellValue = cellValueLocal; int titleCount = 1; JTextArea focusedTabTextArea = null; JTabbedPane tabPane = new JTabbedPane(); fieldEditors = new JTextArea[cellValue.length]; keyEditorFields = new JTextField[cellValue.length]; fieldLanguageBoxs = new JComboBox[cellValue.length]; String parentNodeName = "unknown"; String fieldName = "unknown"; if (cellValue[0] instanceof ImdiField) { ((ImdiField) cellValue[0]).parentImdi.registerContainer(this); parentNodeName = ((ImdiField) cellValue[0]).parentImdi.toString(); fieldName = ((ImdiField[]) cellValue)[0].getTranslateFieldName(); } for (int cellFieldCounter = 0; cellFieldCounter < cellValue.length; cellFieldCounter++) { final int cellFieldIndex = cellFieldCounter; // ImdiField cellField = ((ImdiField) cellValue[cellFieldIndex]); // final ImdiField sourceField = cellValueItem; fieldEditors[cellFieldIndex] = new JTextArea(); if (focusedTabTextArea == null || selectedField == cellFieldCounter) { // set the selected field as the first one or in the case of a single node being selected tab to its pane focusedTabTextArea = fieldEditors[cellFieldIndex]; } fieldEditors[cellFieldIndex].setEditable(((ImdiField) cellValue[cellFieldIndex]).parentImdi.getParentDomNode().isLocal()); FocusListener editorFocusListener = new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { ImdiField cellField = (ImdiField) cellValue[cellFieldIndex]; if (cellField.parentImdi.getParentDomNode().isLocal()) { cellField.setFieldValue(fieldEditors[cellFieldIndex].getText(), true, false); if (keyEditorFields[cellFieldIndex] != null) { cellField.setKeyName(keyEditorFields[cellFieldIndex].getText(), true, false); } } } }; fieldEditors[cellFieldIndex].addFocusListener(editorFocusListener); // insert the last key for only the selected field if (selectedField == cellFieldIndex || (selectedField == -1 && cellFieldIndex == 0)) { fieldEditors[cellFieldIndex].setText(currentEditorText); } else { fieldEditors[cellFieldIndex].setText(((ImdiField) cellValue[cellFieldIndex]).getFieldValue()); } fieldEditors[cellFieldIndex].setLineWrap(true); fieldEditors[cellFieldIndex].setWrapStyleWord(true); JPanel tabPanel = new JPanel(); JPanel tabTitlePanel = new JPanel(); tabPanel.setLayout(new BorderLayout()); tabTitlePanel.setLayout(new BoxLayout(tabTitlePanel, BoxLayout.PAGE_AXIS)); fieldLanguageBoxs[cellFieldIndex] = null; if (cellValue[cellFieldIndex] instanceof ImdiField) { if (((ImdiField) cellValue[cellFieldIndex]).getLanguageId() != null) { fieldLanguageBoxs[cellFieldIndex] = new LanguageIdBox((ImdiField) cellValue[cellFieldIndex], null); JPanel languagePanel = new JPanel(new BorderLayout()); languagePanel.add(new JLabel("Language:"), BorderLayout.LINE_START); languagePanel.add(fieldLanguageBoxs[cellFieldIndex], BorderLayout.CENTER); tabTitlePanel.add(languagePanel); } } String keyName = ((ImdiField) cellValue[cellFieldIndex]).getKeyName(); if (keyName != null) { // if this is a key type field then show the editing options JPanel keyNamePanel = new JPanel(new BorderLayout()); keyEditorFields[cellFieldIndex] = new JTextField(((ImdiField[]) cellValue)[cellFieldCounter].getKeyName()); keyEditorFields[cellFieldIndex].addFocusListener(editorFocusListener); keyEditorFields[cellFieldIndex].setEditable(((ImdiField) cellValue[cellFieldIndex]).parentImdi.getParentDomNode().isLocal()); keyNamePanel.add(new JLabel("Key Name:"), BorderLayout.LINE_START); keyNamePanel.add(keyEditorFields[cellFieldIndex], BorderLayout.CENTER); tabTitlePanel.add(keyNamePanel); } // tabTitlePanel.add(new JLabel("Field Value")); // int layoutRowCount = tabTitlePanel.getComponentCount() / 2; // tabTitlePanel.setLayout(new GridLayout(layoutRowCount, 2)); tabPanel.add(tabTitlePanel, BorderLayout.PAGE_START); tabPanel.add(new JScrollPane(fieldEditors[cellFieldIndex]), BorderLayout.CENTER); tabPane.add(fieldName + " " + titleCount++, tabPanel); } JInternalFrame editorFrame = LinorgWindowManager.getSingleInstance().createWindow(fieldName + " in " + parentNodeName, tabPane); editorFrame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { // deregister component from imditreenode if (cellValue[0] instanceof ImdiField) { ((ImdiField) cellValue[0]).parentImdi.removeContainer(this); } super.internalFrameClosed(e); parentTable.requestFocusInWindow(); } }); if (selectedField != -1) { tabPane.setSelectedIndex(selectedField); } else { tabPane.setSelectedIndex(0); } focusedTabTextArea.requestFocusInWindow(); } public void updateEditor(ImdiTreeObject parentImdiObject) { // this will only be called when the long field editor is shown // when an imdi node is edited or saved or reloaded this will be called to update the displayed values if (cellValue instanceof ImdiField[]) { String fieldName = ((ImdiField[]) cellValue)[0].getTranslateFieldName(); cellValue = parentImdiObject.getFields().get(fieldName); for (int cellFieldCounter = 0; cellFieldCounter < cellValue.length; cellFieldCounter++) { fieldEditors[cellFieldCounter].setText(((ImdiField[]) cellValue)[cellFieldCounter].getFieldValue()); if (fieldLanguageBoxs[cellFieldCounter] != null) { // set the language id selection in the dropdown boolean selectedValueFound = false; for (int itemCounter = 0; itemCounter < fieldLanguageBoxs[cellFieldCounter].getItemCount(); itemCounter++) { Object currentObject = fieldLanguageBoxs[cellFieldCounter].getItemAt(itemCounter); if (currentObject instanceof ImdiVocabularies.VocabularyItem) { ImdiVocabularies.VocabularyItem currentItem = (ImdiVocabularies.VocabularyItem) currentObject; // System.out.println(((ImdiField[]) cellValue)[cellFieldCounter].getLanguageId()); System.out.println(currentItem.languageCode); if (currentItem.languageCode.equals(((ImdiField[]) cellValue)[cellFieldCounter].getLanguageId())) { // System.out.println("setting as current"); fieldLanguageBoxs[cellFieldCounter].setSelectedIndex(itemCounter); selectedValueFound = true; } } } if (selectedValueFound == false) { fieldLanguageBoxs[cellFieldCounter].addItem(LanguageIdBox.defaultLanguageDropDownValue); fieldLanguageBoxs[cellFieldCounter].setSelectedItem(LanguageIdBox.defaultLanguageDropDownValue); } // System.out.println("field language: " + ((ImdiField[]) cellValue)[cellFieldCounter].getLanguageId()); } if (keyEditorFields[cellFieldCounter] != null) { keyEditorFields[cellFieldCounter].setText(((ImdiField[]) cellValue)[cellFieldCounter].getKeyName()); } } } } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import org.apache.commons.logging.impl.LogFactoryImpl; import org.apache.commons.logging.impl.NoOpLog; import cc.arduino.packages.DiscoveryManager; import processing.app.debug.TargetBoard; import processing.app.debug.TargetPackage; import processing.app.debug.TargetPlatform; import processing.app.debug.TargetPlatformException; import processing.app.helpers.FileUtils; import processing.app.helpers.PreferencesMap; import processing.app.helpers.filefilters.OnlyDirs; import processing.app.helpers.filefilters.OnlyFilesWithExtension; import processing.app.javax.swing.filechooser.FileNameExtensionFilter; import processing.app.packages.Library; import processing.app.packages.LibraryList; import processing.app.tools.MenuScroller; import processing.app.tools.ZipDeflater; import processing.core.*; import static processing.app.I18n._; /** * The base class for the main processing application. * Primary role of this class is for platform identification and * general interaction with the system (launching URLs, loading * files and images, etc) that comes from that. */ public class Base { public static final int REVISION = 157; /** This might be replaced by main() if there's a lib/version.txt file. */ static String VERSION_NAME = "0157"; /** Set true if this a proper release rather than a numbered revision. */ static public boolean RELEASE = false; static Map<Integer, String> platformNames = new HashMap<Integer, String>(); static { platformNames.put(PConstants.WINDOWS, "windows"); platformNames.put(PConstants.MACOSX, "macosx"); platformNames.put(PConstants.LINUX, "linux"); } static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>(); static { platformIndices.put("windows", PConstants.WINDOWS); platformIndices.put("macosx", PConstants.MACOSX); platformIndices.put("linux", PConstants.LINUX); } static Platform platform; private static DiscoveryManager discoveryManager = new DiscoveryManager(); static private boolean commandLine; // A single instance of the preferences window Preferences preferencesFrame; // set to true after the first time the menu is built. // so that the errors while building don't show up again. boolean builtOnce; static File buildFolder; // these are static because they're used by Sketch static private File examplesFolder; static private File toolsFolder; static private List<File> librariesFolders; // maps library name to their library folder static private LibraryList libraries; // maps #included files to their library folder static Map<String, Library> importToLibraryTable; // classpath for all known libraries for p5 // (both those in the p5/libs folder and those with lib subfolders // found in the sketchbook) static public String librariesClassPath; static public Map<String, TargetPackage> packages; // Location for untitled items static File untitledFolder; // p5 icon for the window // static Image icon; // int editorCount; List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>()); Editor activeEditor; private final Map<String, Map<String, Object>> boardsViaNetwork; static File portableFolder = null; static final String portableSketchbookFolder = "sketchbook"; static public void main(String args[]) throws Exception { System.setProperty(LogFactoryImpl.LOG_PROPERTY, NoOpLog.class.getCanonicalName()); Logger.getLogger("javax.jmdns").setLevel(Level.OFF); initPlatform(); // Portable folder portableFolder = getContentFile("portable"); if (!portableFolder.exists()) portableFolder = null; // run static initialization that grabs all the prefs Preferences.init(args); try { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { String version = PApplet.loadStrings(versionFile)[0]; if (!version.equals(VERSION_NAME) && !version.equals("${version}")) { VERSION_NAME = version; RELEASE = true; } } } catch (Exception e) { e.printStackTrace(); } // help 3rd party installers find the correct hardware path Preferences.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath()); Preferences.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000); // if (System.getProperty("mrj.version") != null) { // //String jv = System.getProperty("java.version"); // String ov = System.getProperty("os.version"); // if (ov.startsWith("10.5")) { // System.setProperty("apple.laf.useScreenMenuBar", "true"); /* commandLine = false; if (args.length >= 2) { if (args[0].startsWith("--")) { commandLine = true; } } if (PApplet.javaVersion < 1.5f) { //System.err.println("no way man"); Base.showError("Need to install Java 1.5", "This version of Processing requires \n" + "Java 1.5 or later to run properly.\n" + "Please visit java.com to upgrade.", null); } */ // // Set the look and feel before opening the window // try { // platform.setLookAndFeel(); // } catch (Exception e) { // System.err.println("Non-fatal error while setting the Look & Feel."); // System.err.println("The error message follows, however Processing should run fine."); // System.err.println(e.getMessage()); // //e.printStackTrace(); // Use native popups so they don't look so crappy on osx JPopupMenu.setDefaultLightWeightPopupEnabled(false); // Don't put anything above this line that might make GUI, // because the platform has to be inited properly first. // Make sure a full JDK is installed //initRequirements(); // setup the theme coloring fun Theme.init(); // Set the look and feel before opening the window try { platform.setLookAndFeel(); } catch (Exception e) { String mess = e.getMessage(); if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) { System.err.println(_("Non-fatal error while setting the Look & Feel.")); System.err.println(_("The error message follows, however Arduino should run fine.")); System.err.println(mess); } } // Create a location for untitled sketches untitledFolder = createTempFolder("untitled"); untitledFolder.deleteOnExit(); new Base(args); } static protected void setCommandLine() { commandLine = true; } static protected boolean isCommandLine() { return commandLine; } static protected void initPlatform() { try { Class<?> platformClass = Class.forName("processing.app.Platform"); if (Base.isMacOS()) { platformClass = Class.forName("processing.app.macosx.Platform"); } else if (Base.isWindows()) { platformClass = Class.forName("processing.app.windows.Platform"); } else if (Base.isLinux()) { platformClass = Class.forName("processing.app.linux.Platform"); } platform = (Platform) platformClass.newInstance(); } catch (Exception e) { Base.showError(_("Problem Setting the Platform"), _("An unknown error occurred while trying to load\n" + "platform-specific code for your machine."), e); } } static protected void initRequirements() { try { Class.forName("com.sun.jdi.VirtualMachine"); } catch (ClassNotFoundException cnfe) { Base.showPlatforms(); Base.showError(_("Please install JDK 1.5 or later"), _("Arduino requires a full JDK (not just a JRE)\n" + "to run. Please install JDK 1.5 or later.\n" + "More information can be found in the reference."), cnfe); } } protected static enum ACTION { GUI, VERIFY, UPLOAD }; public Base(String[] args) throws Exception { platform.init(this); this.boardsViaNetwork = new ConcurrentHashMap<String, Map<String, Object>>(); // Get the sketchbook path, and make sure it's set properly String sketchbookPath = Preferences.get("sketchbook.path"); // If a value is at least set, first check to see if the folder exists. // If it doesn't, warn the user that the sketchbook folder is being reset. if (sketchbookPath != null) { File sketchbookFolder; if (portableFolder != null) sketchbookFolder = new File(portableFolder, sketchbookPath); else sketchbookFolder = new File(sketchbookPath); if (!sketchbookFolder.exists()) { Base.showWarning(_("Sketchbook folder disappeared"), _("The sketchbook folder no longer exists.\n" + "Arduino will switch to the default sketchbook\n" + "location, and create a new sketchbook folder if\n" + "necessary. Arduino will then stop talking about\n" + "himself in the third person."), null); sketchbookPath = null; } } // If no path is set, get the default sketchbook folder for this platform if (sketchbookPath == null) { File defaultFolder = getDefaultSketchbookFolder(); if (portableFolder != null) Preferences.set("sketchbook.path", portableSketchbookFolder); else Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath()); if (!defaultFolder.exists()) { defaultFolder.mkdirs(); } } packages = new HashMap<String, TargetPackage>(); loadHardware(getHardwareFolder()); loadHardware(getSketchbookHardwareFolder()); if (packages.size() == 0) { System.out.println(_("No valid configured cores found! Exiting...")); System.exit(3); } // Setup board-dependent variables. onBoardOrPortChange(); ACTION action = ACTION.GUI; boolean doVerboseBuild = false; boolean doVerboseUpload = false;; String selectBoard = null; String selectPort = null; String currentDirectory = System.getProperty("user.dir"); List<String> filenames = new LinkedList<String>(); // Map of possible actions and corresponding options final Map<String, ACTION> actions = new HashMap<String, ACTION>(); actions.put("--verify", ACTION.VERIFY); actions.put("--upload", ACTION.UPLOAD); // Check if any files were passed in on the command line for (int i = 0; i < args.length; i++) { ACTION a = actions.get(args[i]); if (a != null) { if (action != ACTION.GUI) { String[] valid = actions.keySet().toArray(new String[0]); String mess = I18n.format(_("Can only pass one of: {0}"), PApplet.join(valid, ", ")); showError(null, mess, 3); } action = a; continue; } if (args[i].equals("--verbose") || args[i].equals("-v")) { doVerboseBuild = true; doVerboseUpload = true; continue; } if (args[i].equals("--verbose-build")) { doVerboseBuild = true; continue; } if (args[i].equals("--verbose-upload")) { doVerboseUpload = true; continue; } if (args[i].equals("--board")) { i++; if (i >= args.length) showError(null, _("Argument required for --board"), 3); processBoardArgument(args[i]); continue; } if (args[i].equals("--port")) { i++; if (i >= args.length) showError(null, _("Argument required for --port"), 3); Base.selectSerialPort(args[i]); continue; } if (args[i].equals("--curdir")) { i++; if (i >= args.length) showError(null, _("Argument required for --curdir"), 3); currentDirectory = args[i]; continue; } if (args[i].equals("--pref")) { i++; if (i >= args.length) showError(null, _("Argument required for --pref"), 3); processPrefArgument(args[i]); continue; } if (args[i].equals("--no-save-prefs")) { Preferences.setDoSave(false); continue; } if (args[i].equals("--preferences-file")) { i++; if (i >= args.length) showError(null, _("Argument required for --preferences-file"), 3); // Argument should be already processed by Preferences.init(...) continue; } if (args[i].startsWith(" showError(null, I18n.format(_("unknown option: {0}"), args[i]), 3); filenames.add(args[i]); } if ((action == ACTION.UPLOAD || action == ACTION.VERIFY) && filenames.size() != 1) showError(null, _("Must specify exactly one sketch file"), 3); if ((action != ACTION.UPLOAD && action != ACTION.VERIFY) && (doVerboseBuild || doVerboseUpload)) showError(null, _("--verbose, --verbose-upload and --verbose-build can only be used together with --verify or --upload"), 3); for (String path: filenames) { // Fix a problem with systems that use a non-ASCII languages. Paths are // being passed in with 8.3 syntax, which makes the sketch loader code // unhappy, since the sketch folder naming doesn't match up correctly. if (isWindows()) { try { File file = new File(path); path = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } if (!new File(path).isAbsolute()) { path = new File(currentDirectory, path).getAbsolutePath(); } boolean showEditor = (action == ACTION.GUI); if (handleOpen(path, nextEditorLocation(), showEditor) == null) { String mess = I18n.format(_("Failed to open sketch: \"{0}\""), path); // Open failure is fatal in upload/verify mode if (action == ACTION.VERIFY || action == ACTION.UPLOAD) showError(null, mess, 2); else showWarning(null, mess, null); } } // Save the preferences. For GUI mode, this happens in the quit // handler, but for other modes we should also make sure to save // them. Preferences.save(); switch (action) { case VERIFY: case UPLOAD: // Set verbosity for command line build Preferences.set("build.verbose", "" + doVerboseBuild); Preferences.set("upload.verbose", "" + doVerboseUpload); // Make sure these verbosity preferences are only for the // current session Preferences.setDoSave(false); Editor editor = editors.get(0); if (action == ACTION.UPLOAD) { // Build and upload editor.exportHandler.run(); } else { // Build only editor.runHandler.run(); } // Error during build or upload int res = editor.status.mode; if (res == EditorStatus.ERR) System.exit(1); // No errors exit gracefully System.exit(0); break; case GUI: // Check if there were previously opened sketches to be restored restoreSketches(); // Create a new empty window (will be replaced with any files to be opened) if (editors.isEmpty()) { handleNew(); } // Check for updates if (Preferences.getBoolean("update.check")) { new UpdateCheck(this); } break; } } protected void processBoardArgument(String selectBoard) { // No board selected? Nothing to do if (selectBoard == null) return; String[] split = selectBoard.split(":", 4); if (split.length < 3) { showError(null, I18n.format(_("{0}: Invalid board name, it should be of the form \"package:arch:board\" or \"package:arch:board:options\""), selectBoard), 3); } TargetPackage targetPackage = getTargetPackage(split[0]); if (targetPackage == null) { showError(null, I18n.format(_("{0}: Unknown package"), split[0]), 3); } TargetPlatform targetPlatform = targetPackage.get(split[1]); if (targetPlatform == null) { showError(null, I18n.format(_("{0}: Unknown architecture"), split[1]), 3); } TargetBoard targetBoard = targetPlatform.getBoard(split[2]); if (targetBoard == null) { showError(null, I18n.format(_("{0}: Unknown board"), split[2]), 3); } selectBoard(targetBoard); if (split.length > 3) { String[] options = split[3].split(","); for (String option : options) { String[] keyValue = option.split("=", 2); if (keyValue.length != 2) showError(null, I18n.format(_("{0}: Invalid option, should be of the form \"name=value\""), option, targetBoard.getId()), 3); String key = keyValue[0].trim(); String value = keyValue[1].trim(); if (!targetBoard.hasMenu(key)) showError(null, I18n.format(_("{0}: Invalid option for board \"{1}\""), key, targetBoard.getId()), 3); if (targetBoard.getMenuLabel(key, value) == null) showError(null, I18n.format(_("{0}: Invalid option for \"{1}\" option for board \"{2}\""), value, key, targetBoard.getId()), 3); Preferences.set("custom_" + key, targetBoard.getId() + "_" + value); } } } protected void processPrefArgument(String arg) { String[] split = arg.split("=", 2); if (split.length != 2 || split[0].isEmpty()) showError(null, I18n.format(_("{0}: Invalid argument to --pref, should be of the form \"pref=value\""), arg), 3); Preferences.set(split[0], split[1]); } public Map<String, Map<String, Object>> getBoardsViaNetwork() { return new HashMap<String, Map<String, Object>>(boardsViaNetwork); } /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. * @throws Exception */ protected boolean restoreSketches() throws Exception { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } /* int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } */ } else { windowPositionValid = false; } // Iterate through all sketches that were open last time p5 was running. // If !windowPositionValid, then ignore the coordinates found for each. // Save the sketch path and window placement for each open sketch int count = Preferences.getInteger("last.sketch.count"); int opened = 0; for (int i = 0; i < count; i++) { String path = Preferences.get("last.sketch" + i + ".path"); if (portableFolder != null) { File absolute = new File(portableFolder, path); try { path = absolute.getCanonicalPath(); } catch (IOException e) { // path unchanged. } } int[] location; if (windowPositionValid) { String locationStr = Preferences.get("last.sketch" + i + ".location"); location = PApplet.parseInt(PApplet.split(locationStr, ',')); } else { location = nextEditorLocation(); } // If file did not exist, null will be returned for the Editor if (handleOpen(path, location, true) != null) { opened++; } } return (opened > 0); } /** * Store list of sketches that are currently open. * Called when the application is quitting and documents are still open. */ protected void storeSketches() { // Save the width and height of the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); String untitledPath = untitledFolder.getAbsolutePath(); // Save the sketch path and window placement for each open sketch int index = 0; for (Editor editor : editors) { String path = editor.getSketch().getMainFilePath(); // In case of a crash, save untitled sketches if they contain changes. // (Added this for release 0158, may not be a good idea.) if (path.startsWith(untitledPath) && !editor.getSketch().isModified()) { continue; } if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) continue; } Preferences.set("last.sketch" + index + ".path", path); int[] location = editor.getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); Preferences.set("last.sketch" + index + ".location", locationStr); index++; } Preferences.setInteger("last.sketch.count", index); } // If a sketch is untitled on quit, may need to store the new name // rather than the location from the temp folder. protected void storeSketchPath(Editor editor, int index) { String path = editor.getSketch().getMainFilePath(); String untitledPath = untitledFolder.getAbsolutePath(); if (path.startsWith(untitledPath)) { path = ""; } else if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) path = ""; } Preferences.set("last.sketch" + index + ".path", path); } /* public void storeSketch(Editor editor) { int index = -1; for (int i = 0; i < editorCount; i++) { if (editors[i] == editor) { index = i; break; } } if (index == -1) { System.err.println("Problem storing sketch " + editor.sketch.name); } else { String path = editor.sketch.getMainFilePath(); Preferences.set("last.sketch" + index + ".path", path); } } */ // Because of variations in native windowing systems, no guarantees about // changes to the focused and active Windows can be made. Developers must // never assume that this Window is the focused or active Window until this // Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event. protected void handleActivated(Editor whichEditor) { activeEditor = whichEditor; // set the current window to be the console that's getting output EditorConsole.setEditor(activeEditor); } protected int[] nextEditorLocation() { int defaultWidth = Preferences.getInteger("editor.window.width.default"); int defaultHeight = Preferences.getInteger("editor.window.height.default"); if (activeEditor == null) { Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds(); // If no current active editor, use default placement return new int[] { (screen.width - defaultWidth) / 2, (screen.height - defaultHeight) / 2, defaultWidth, defaultHeight, 0 }; } else { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // With a currently active editor, open the new window // using the same dimensions, but offset slightly. synchronized (editors) { final int OVER = 50; // In release 0160, don't //location = activeEditor.getPlacement(); Editor lastOpened = activeEditor; int[] location = lastOpened.getPlacement(); // Just in case the bounds for that window are bad location[0] += OVER; location[1] += OVER; if (location[0] == OVER || location[2] == OVER || location[0] + location[2] > screen.width || location[1] + location[3] > screen.height) { // Warp the next window to a randomish location on screen. return new int[] { (int) (Math.random() * (screen.width - defaultWidth)), (int) (Math.random() * (screen.height - defaultHeight)), defaultWidth, defaultHeight, 0 }; } return location; } } } boolean breakTime = false; String[] months = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; /** * Handle creating a sketch folder, return its base .pde file * or null if the operation was canceled. * @param shift whether shift is pressed, which will invert prompt setting * @param noPrompt disable prompt, no matter the setting */ protected String createNewUntitled() throws IOException { File newbieDir = null; String newbieName = null; // In 0126, untitled sketches will begin in the temp folder, // and then moved to a new location because Save will default to Save As. File sketchbookDir = getSketchbookFolder(); File newbieParentDir = untitledFolder; // Use a generic name like sketch_031008a, the date plus a char int index = 0; //SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); //SimpleDateFormat formatter = new SimpleDateFormat("MMMdd"); //String purty = formatter.format(new Date()).toLowerCase(); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31 int month = cal.get(Calendar.MONTH); // 0..11 String purty = months[month] + PApplet.nf(day, 2); do { if (index == 26) { // In 0159, avoid running past z by sending people outdoors. if (!breakTime) { Base.showWarning(_("Time for a Break"), _("You've reached the limit for auto naming of new sketches\n" + "for the day. How about going for a walk instead?"), null); breakTime = true; } else { Base.showWarning(_("Sunshine"), _("No really, time for some fresh air for you."), null); } return null; } newbieName = "sketch_" + purty + ((char) ('a' + index)); newbieDir = new File(newbieParentDir, newbieName); index++; // Make sure it's not in the temp folder *and* it's not in the sketchbook } while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists()); // Make the directory for the new sketch newbieDir.mkdirs(); // Make an empty pde file File newbieFile = new File(newbieDir, newbieName + ".ino"); if (!newbieFile.createNewFile()) { throw new IOException(); } FileUtils.copyFile(new File(getContentFile("examples"), "01.Basics" + File.separator + "BareMinimum" + File.separator + "BareMinimum.ino"), newbieFile); return newbieFile.getAbsolutePath(); } /** * Create a new untitled document in a new sketch window. * @throws Exception */ public void handleNew() throws Exception { try { String path = createNewUntitled(); if (path != null) { Editor editor = handleOpen(path); editor.untitled = true; } } catch (IOException e) { if (activeEditor != null) { activeEditor.statusError(e); } } } /** * Replace the sketch in the current window with a new untitled document. */ public void handleNewReplace() { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); // Actually replace things handleNewReplaceImpl(); } protected void handleNewReplaceImpl() { try { String path = createNewUntitled(); if (path != null) { activeEditor.handleOpenInternal(path); activeEditor.untitled = true; } // return true; } catch (IOException e) { activeEditor.statusError(e); // return false; } } /** * Open a sketch, replacing the sketch in the current window. * @param path Location of the primary pde file for the sketch. */ public void handleOpenReplace(String path) { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); boolean loaded = activeEditor.handleOpenInternal(path); if (!loaded) { // replace the document without checking if that's ok handleNewReplaceImpl(); } } /** * Prompt for a sketch to open, and open it in a new window. * @throws Exception */ public void handleOpenPrompt() throws Exception { // get the frontmost window frame for placing file dialog JFileChooser fd = new JFileChooser(Preferences.get("last.folder", Base.getSketchbookFolder().getAbsolutePath())); fd.setDialogTitle(_("Open an Arduino sketch...")); fd.setFileSelectionMode(JFileChooser.FILES_ONLY); fd.setFileFilter(new FileNameExtensionFilter(_("Sketches (*.ino, *.pde)"), "ino", "pde")); Dimension preferredSize = fd.getPreferredSize(); fd.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fd.showOpenDialog(activeEditor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File inputFile = fd.getSelectedFile(); Preferences.set("last.folder", inputFile.getAbsolutePath()); handleOpen(inputFile.getAbsolutePath()); } /** * Open a sketch in a new window. * @param path Path to the pde file for the sketch in question * @return the Editor object, so that properties (like 'untitled') * can be set by the caller * @throws Exception */ public Editor handleOpen(String path) throws Exception { return handleOpen(path, nextEditorLocation(), true); } protected Editor handleOpen(String path, int[] location, boolean showEditor) throws Exception { // System.err.println("entering handleOpen " + path); File file = new File(path); if (!file.exists()) return null; // System.err.println(" editors: " + editors); // Cycle through open windows to make sure that it's not already open. for (Editor editor : editors) { if (editor.getSketch().getMainFilePath().equals(path)) { editor.toFront(); // System.err.println(" handleOpen: already opened"); return editor; } } // If the active editor window is an untitled, and un-modified document, // just replace it with the file that's being opened. // if (activeEditor != null) { // Sketch activeSketch = activeEditor.sketch; // if (activeSketch.isUntitled() && !activeSketch.isModified()) { // // if it's an untitled, unmodified document, it can be replaced. // // except in cases where a second blank window is being opened. // if (!path.startsWith(untitledFolder.getAbsolutePath())) { // activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0); // return activeEditor; // System.err.println(" creating new editor"); Editor editor = new Editor(this, path, location); // Editor editor = null; // try { // editor = new Editor(this, path, location); // } catch (Exception e) { // e.printStackTrace(); // System.err.flush(); // System.out.flush(); // System.exit(1); // System.err.println(" done creating new editor"); // EditorConsole.systemErr.println(" done creating new editor"); // Make sure that the sketch actually loaded if (editor.getSketch() == null) { // System.err.println("sketch was null, getting out of handleOpen"); return null; // Just walk away quietly } // if (editors == null) { // editors = new Editor[5]; // if (editorCount == editors.length) { // editors = (Editor[]) PApplet.expand(editors); // editors[editorCount++] = editor; editors.add(editor); // if (markedForClose != null) { // Point p = markedForClose.getLocation(); // handleClose(markedForClose, false); // // open the new window in // editor.setLocation(p); // now that we're ready, show the window // (don't do earlier, cuz we might move it based on a window being closed) if (showEditor) editor.setVisible(true); // System.err.println("exiting handleOpen"); return editor; } /** * Close a sketch as specified by its editor window. * @param editor Editor object of the sketch to be closed. * @return true if succeeded in closing, false if canceled. */ public boolean handleClose(Editor editor) { // Check if modified // boolean immediate = editors.size() == 1; if (!editor.checkModified()) { return false; } // Close the running window, avoid window boogers with multiple sketches editor.internalCloseRunner(); if (editors.size() == 1) { // For 0158, when closing the last window /and/ it was already an // untitled sketch, just give up and let the user quit. // if (Preferences.getBoolean("sketchbook.closing_last_window_quits") || // (editor.untitled && !editor.getSketch().isModified())) { if (Base.isMacOS()) { Object[] options = { "OK", "Cancel" }; String prompt = _("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Are you sure you want to Quit?</b>" + "<p>Closing the last open sketch will quit Arduino."); int result = JOptionPane.showOptionDialog(editor, prompt, _("Quit"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) { return false; } } // This will store the sketch count as zero editors.remove(editor); try { Editor.serialMonitor.close(); } catch (Exception e) { //ignore } storeSketches(); // Save out the current prefs state Preferences.save(); // Since this wasn't an actual Quit event, call System.exit() System.exit(0); } else { // More than one editor window open, // proceed with closing the current window. editor.setVisible(false); editor.dispose(); // for (int i = 0; i < editorCount; i++) { // if (editor == editors[i]) { // for (int j = i; j < editorCount-1; j++) { // editors[j] = editors[j+1]; // editorCount--; // // Set to null so that garbage collection occurs // editors[editorCount] = null; editors.remove(editor); } return true; } /** * Handler for File &rarr; Quit. * @return false if canceled, true otherwise. */ public boolean handleQuit() { // If quit is canceled, this will be replaced anyway // by a later handleQuit() that is not canceled. storeSketches(); try { Editor.serialMonitor.close(); } catch (Exception e) { // ignore } if (handleQuitEach()) { // make sure running sketches close before quitting for (Editor editor : editors) { editor.internalCloseRunner(); } // Save out the current prefs state Preferences.save(); if (!Base.isMacOS()) { // If this was fired from the menu or an AppleEvent (the Finder), // then Mac OS X will send the terminate signal itself. System.exit(0); } return true; } return false; } /** * Attempt to close each open sketch in preparation for quitting. * @return false if canceled along the way */ protected boolean handleQuitEach() { int index = 0; for (Editor editor : editors) { if (editor.checkModified()) { // Update to the new/final sketch path for this fella storeSketchPath(editor, index); index++; } else { return false; } } return true; } /** * Asynchronous version of menu rebuild to be used on save and rename * to prevent the interface from locking up until the menus are done. */ protected void rebuildSketchbookMenus() { //System.out.println("async enter"); //new Exception().printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { //System.out.println("starting rebuild"); rebuildSketchbookMenu(Editor.sketchbookMenu); rebuildToolbarMenu(Editor.toolbarMenu); //System.out.println("done with rebuild"); } }); //System.out.println("async exit"); } protected void rebuildToolbarMenu(JMenu menu) { JMenuItem item; menu.removeAll(); // Add the single "Open" item item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { handleOpenPrompt(); } catch (Exception e1) { e1.printStackTrace(); } } }); menu.add(item); menu.addSeparator(); // Add a list of all sketches and subfolders try { boolean sketches = addSketches(menu, getSketchbookFolder(), true); if (sketches) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } // Add each of the subfolders of examples directly to the menu try { boolean found = addSketches(menu, examplesFolder, true); if (found) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } } protected void rebuildSketchbookMenu(JMenu menu) { //System.out.println("rebuilding sketchbook menu"); //new Exception().printStackTrace(); try { menu.removeAll(); addSketches(menu, getSketchbookFolder(), false); //addSketches(menu, getSketchbookFolder()); } catch (IOException e) { e.printStackTrace(); } } public LibraryList getIDELibs() { if (libraries == null) return new LibraryList(); LibraryList res = new LibraryList(libraries); res.removeAll(getUserLibs()); return res; } public LibraryList getUserLibs() { if (libraries == null) return new LibraryList(); return libraries.filterLibrariesInSubfolder(getSketchbookFolder()); } public void rebuildImportMenu(JMenu importMenu) { importMenu.removeAll(); JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library...")); addLibraryMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.this.handleAddLibrary(); Base.this.onBoardOrPortChange(); Base.this.rebuildImportMenu(Editor.importMenu); Base.this.rebuildExamplesMenu(Editor.examplesMenu); } }); importMenu.add(addLibraryMenuItem); importMenu.addSeparator(); // Split between user supplied libraries and IDE libraries TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform != null) { LibraryList ideLibs = getIDELibs(); LibraryList userLibs = getUserLibs(); try { // Find the current target. Get the platform, and then select the // correct name and core path. PreferencesMap prefs = targetPlatform.getPreferences(); if (prefs != null) { String platformName = prefs.get("name"); if (platformName != null) { JMenuItem platformItem = new JMenuItem(_(platformName)); platformItem.setEnabled(false); importMenu.add(platformItem); } } if (ideLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, ideLibs); } if (userLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, userLibs); } } catch (IOException e) { e.printStackTrace(); } } } public void rebuildExamplesMenu(JMenu menu) { try { menu.removeAll(); // Add examples from distribution "example" folder boolean found = addSketches(menu, examplesFolder, false); if (found) menu.addSeparator(); // Add examples from libraries LibraryList ideLibs = getIDELibs(); ideLibs.sort(); for (Library lib : ideLibs) addSketchesSubmenu(menu, lib, false); LibraryList userLibs = getUserLibs(); if (userLibs.size()>0) { menu.addSeparator(); userLibs.sort(); for (Library lib : userLibs) addSketchesSubmenu(menu, lib, false); } } catch (IOException e) { e.printStackTrace(); } } public LibraryList scanLibraries(List<File> folders) throws IOException { LibraryList res = new LibraryList(); for (File folder : folders) res.addOrReplaceAll(scanLibraries(folder)); return res; } public LibraryList scanLibraries(File folder) throws IOException { LibraryList res = new LibraryList(); String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return res; for (String libName : list) { File subfolder = new File(folder, libName); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); Base.showMessage(_("Ignoring bad library name"), mess); continue; } try { Library lib = Library.create(subfolder); // (also replace previously found libs with the same name) if (lib != null) res.addOrReplace(lib); } catch (IOException e) { System.out.println(I18n.format(_("Invalid library found in {0}: {1}"), subfolder, e.getMessage())); } } return res; } public void onBoardOrPortChange() { TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform == null) return; // Calculate paths for libraries and examples examplesFolder = getContentFile("examples"); toolsFolder = getContentFile("tools"); File platformFolder = targetPlatform.getFolder(); librariesFolders = new ArrayList<File>(); librariesFolders.add(getContentFile("libraries")); String core = getBoardPreferences().get("build.core"); if (core.contains(":")) { String referencedCore = core.split(":")[0]; TargetPlatform referencedPlatform = Base.getTargetPlatform(referencedCore, targetPlatform.getId()); if (referencedPlatform != null) { File referencedPlatformFolder = referencedPlatform.getFolder(); librariesFolders.add(new File(referencedPlatformFolder, "libraries")); } } librariesFolders.add(new File(platformFolder, "libraries")); librariesFolders.add(getSketchbookLibrariesFolder()); // Scan for libraries in each library folder. // Libraries located in the latest folders on the list can override // other libraries with the same name. try { libraries = scanLibraries(librariesFolders); } catch (IOException e) { showWarning(_("Error"), _("Error loading libraries"), e); } // Populate importToLibraryTable importToLibraryTable = new HashMap<String, Library>(); for (Library lib : libraries) { try { String headers[] = headerListFromIncludePath(lib.getSrcFolder()); for (String header : headers) { Library old = importToLibraryTable.get(header); if (old != null) { // If a library was already found with this header, keep // it if the library's name matches the header name. String name = header.substring(0, header.length() - 2); if (old.getFolder().getPath().endsWith(name)) continue; } importToLibraryTable.put(header, lib); } } catch (IOException e) { showWarning(_("Error"), I18n .format("Unable to list header files in {0}", lib.getSrcFolder()), e); } } // Update editors status bar for (Editor editor : editors) editor.onBoardOrPortChange(); } public void rebuildBoardsMenu(JMenu toolsMenu, Editor editor) throws Exception { JMenu boardsMenu = getBoardCustomMenu(); boolean first = true; List<JMenuItem> menuItemsToClickAfterStartup = new LinkedList<JMenuItem>(); ButtonGroup boardsButtonGroup = new ButtonGroup(); Map<String, ButtonGroup> buttonGroupsMap = new HashMap<String, ButtonGroup>(); // Generate custom menus for all platforms Set<String> titles = new HashSet<String>(); for (TargetPackage targetPackage : packages.values()) { for (TargetPlatform targetPlatform : targetPackage.platforms()) titles.addAll(targetPlatform.getCustomMenus().values()); } for (String title : titles) makeBoardCustomMenu(toolsMenu, _(title)); // Cycle through all packages for (TargetPackage targetPackage : packages.values()) { // For every package cycle through all platform for (TargetPlatform targetPlatform : targetPackage.platforms()) { // Add a separator from the previous platform if (!first) boardsMenu.add(new JSeparator()); first = false; // Add a title for each platform String platformLabel = targetPlatform.getPreferences().get("name"); if (platformLabel != null && !targetPlatform.getBoards().isEmpty()) { JMenuItem menuLabel = new JMenuItem(_(platformLabel)); menuLabel.setEnabled(false); boardsMenu.add(menuLabel); } // Cycle through all boards of this platform for (TargetBoard board : targetPlatform.getBoards().values()) { JMenuItem item = createBoardMenusAndCustomMenus(menuItemsToClickAfterStartup, buttonGroupsMap, board, targetPlatform, targetPackage); boardsMenu.add(item); boardsButtonGroup.add(item); } } } if (menuItemsToClickAfterStartup.isEmpty()) { menuItemsToClickAfterStartup.add(selectFirstEnabledMenuItem(boardsMenu)); } for (JMenuItem menuItemToClick : menuItemsToClickAfterStartup) { menuItemToClick.setSelected(true); menuItemToClick.getAction().actionPerformed(new ActionEvent(this, -1, "")); } } private JRadioButtonMenuItem createBoardMenusAndCustomMenus( List<JMenuItem> menuItemsToClickAfterStartup, Map<String, ButtonGroup> buttonGroupsMap, TargetBoard board, TargetPlatform targetPlatform, TargetPackage targetPackage) throws Exception { String selPackage = Preferences.get("target_package"); String selPlatform = Preferences.get("target_platform"); String selBoard = Preferences.get("board"); String boardId = board.getId(); String packageName = targetPackage.getId(); String platformName = targetPlatform.getId(); // Setup a menu item for the current board @SuppressWarnings("serial") Action action = new AbstractAction(board.getName()) { public void actionPerformed(ActionEvent actionevent) { selectBoard((TargetBoard)getValue("b")); filterVisibilityOfSubsequentBoardMenus((TargetBoard)getValue("b"), 1); onBoardOrPortChange(); rebuildImportMenu(Editor.importMenu); rebuildExamplesMenu(Editor.examplesMenu); } }; action.putValue("b", board); JRadioButtonMenuItem item = new JRadioButtonMenuItem(action); if (selBoard.equals(boardId) && selPackage.equals(packageName) && selPlatform.equals(platformName)) { menuItemsToClickAfterStartup.add(item); } PreferencesMap customMenus = targetPlatform.getCustomMenus(); for (final String menuId : customMenus.keySet()) { String title = customMenus.get(menuId); JMenu menu = getBoardCustomMenu(_(title)); if (board.hasMenu(menuId)) { PreferencesMap boardCustomMenu = board.getMenuLabels(menuId); for (String customMenuOption : boardCustomMenu.keySet()) { @SuppressWarnings("serial") Action subAction = new AbstractAction(_(boardCustomMenu.get(customMenuOption))) { public void actionPerformed(ActionEvent e) { Preferences.set("custom_" + menuId, ((TargetBoard)getValue("board")).getId() + "_" + getValue("custom_menu_option")); } }; subAction.putValue("board", board); subAction.putValue("custom_menu_option", customMenuOption); if (!buttonGroupsMap.containsKey(menuId)) { buttonGroupsMap.put(menuId, new ButtonGroup()); } JRadioButtonMenuItem subItem = new JRadioButtonMenuItem(subAction); menu.add(subItem); buttonGroupsMap.get(menuId).add(subItem); String selectedCustomMenuEntry = Preferences.get("custom_" + menuId); if (selBoard.equals(boardId) && (boardId + "_" + customMenuOption).equals(selectedCustomMenuEntry)) { menuItemsToClickAfterStartup.add(subItem); } } } } return item; } private static void filterVisibilityOfSubsequentBoardMenus(TargetBoard board, int fromIndex) { for (int i = fromIndex; i < Editor.boardsMenus.size(); i++) { JMenu menu = Editor.boardsMenus.get(i); for (int m = 0; m < menu.getItemCount(); m++) { JMenuItem menuItem = menu.getItem(m); menuItem.setVisible(menuItem.getAction().getValue("board").equals(board)); } menu.setVisible(ifThereAreVisibleItemsOn(menu)); if (menu.isVisible()) { JMenuItem visibleSelectedOrFirstMenuItem = selectVisibleSelectedOrFirstMenuItem(menu); if (!visibleSelectedOrFirstMenuItem.isSelected()) { visibleSelectedOrFirstMenuItem.setSelected(true); visibleSelectedOrFirstMenuItem.getAction().actionPerformed(null); } } } } private static boolean ifThereAreVisibleItemsOn(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { if (menu.getItem(i).isVisible()) { return true; } } return false; } private JMenu makeBoardCustomMenu(JMenu toolsMenu, String label) { JMenu menu = new JMenu(label); Editor.boardsMenus.add(menu); toolsMenu.add(menu); return menu; } private JMenu getBoardCustomMenu() throws Exception { return getBoardCustomMenu(_("Board")); } private JMenu getBoardCustomMenu(String label) throws Exception { for (JMenu menu : Editor.boardsMenus) if (label.equals(menu.getText())) return menu; throw new Exception("Custom menu not found!"); } private static JMenuItem selectVisibleSelectedOrFirstMenuItem(JMenu menu) { JMenuItem firstVisible = null; for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isVisible()) { if (item.isSelected()) { return item; } if (firstVisible == null) { firstVisible = item; } } } if (firstVisible != null) { return firstVisible; } throw new IllegalStateException("Menu has no enabled items"); } private static JMenuItem selectFirstEnabledMenuItem(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isEnabled()) { return item; } } throw new IllegalStateException("Menu has no enabled items"); } private void selectBoard(TargetBoard targetBoard) { TargetPlatform targetPlatform = targetBoard.getContainerPlatform(); TargetPackage targetPackage = targetPlatform.getContainerPackage(); Preferences.set("target_package", targetPackage.getId()); Preferences.set("target_platform", targetPlatform.getId()); Preferences.set("board", targetBoard.getId()); File platformFolder = targetPlatform.getFolder(); Preferences.set("runtime.platform.path", platformFolder.getAbsolutePath()); Preferences.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath()); } public static void selectSerialPort(String port) { Preferences.set("serial.port", port); if (port.startsWith("/dev/")) Preferences.set("serial.port.file", port.substring(5)); else Preferences.set("serial.port.file", port); } public void rebuildProgrammerMenu(JMenu menu) { menu.removeAll(); ButtonGroup group = new ButtonGroup(); for (TargetPackage targetPackage : packages.values()) { for (TargetPlatform targetPlatform : targetPackage.platforms()) { for (String programmer : targetPlatform.getProgrammers().keySet()) { String id = targetPackage.getId() + ":" + programmer; @SuppressWarnings("serial") AbstractAction action = new AbstractAction(targetPlatform .getProgrammer(programmer).get("name")) { public void actionPerformed(ActionEvent actionevent) { Preferences.set("programmer", "" + getValue("id")); } }; action.putValue("id", id); JMenuItem item = new JRadioButtonMenuItem(action); if (Preferences.get("programmer").equals(id)) item.setSelected(true); group.add(item); menu.add(item); } } } } /** * Scan a folder recursively, and add any sketches found to the menu * specified. Set the openReplaces parameter to true when opening the sketch * should replace the sketch in the current window, or false when the * sketch should open in a new window. */ protected boolean addSketches(JMenu menu, File folder, final boolean replaceExisting) throws IOException { if (folder == null) return false; if (!folder.isDirectory()) return false; File[] files = folder.listFiles(); // If a bad folder or unreadable or whatever, this will come back null if (files == null) return false; // Alphabetize files, since it's not always alpha order Arrays.sort(files, new Comparator<File>() { @Override public int compare(File file, File file2) { return file.getName().compareToIgnoreCase(file2.getName()); } }); boolean ifound = false; for (File subfolder : files) { if (FileUtils.isSCCSOrHiddenFile(subfolder)) { continue; } if (!subfolder.isDirectory()) continue; if (addSketchesSubmenu(menu, subfolder.getName(), subfolder, replaceExisting)) { ifound = true; } } return ifound; } private boolean addSketchesSubmenu(JMenu menu, Library lib, boolean replaceExisting) throws IOException { return addSketchesSubmenu(menu, lib.getName(), lib.getFolder(), replaceExisting); } private boolean addSketchesSubmenu(JMenu menu, String name, File folder, final boolean replaceExisting) throws IOException { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String path = e.getActionCommand(); if (new File(path).exists()) { boolean replace = replaceExisting; if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { replace = !replace; } if (replace) { handleOpenReplace(path); } else { try { handleOpen(path); } catch (Exception e1) { e1.printStackTrace(); } } } else { showWarning(_("Sketch Does Not Exist"), _("The selected sketch no longer exists.\n" + "You may need to restart Arduino to update\n" + "the sketchbook menu."), null); } } }; File entry = new File(folder, name + ".ino"); if (!entry.exists() && (new File(folder, name + ".pde")).exists()) entry = new File(folder, name + ".pde"); // if a .pde file of the same prefix as the folder exists.. if (entry.exists()) { if (!Sketch.isSanitaryName(name)) { if (!builtOnce) { String complaining = I18n .format( _("The sketch \"{0}\" cannot be used.\n" + "Sketch names must contain only basic letters and numbers\n" + "(ASCII-only with no spaces, " + "and it cannot start with a number).\n" + "To get rid of this message, remove the sketch from\n" + "{1}"), name, entry.getAbsolutePath()); Base.showMessage(_("Ignoring sketch with bad name"), complaining); } return false; } JMenuItem item = new JMenuItem(name); item.addActionListener(listener); item.setActionCommand(entry.getAbsolutePath()); menu.add(item); return true; } // don't create an extra menu level for a folder named "examples" if (folder.getName().equals("examples")) return addSketches(menu, folder, replaceExisting); // not a sketch folder, but maybe a subfolder containing sketches JMenu submenu = new JMenu(name); boolean found = addSketches(submenu, folder, replaceExisting); if (found) { menu.add(submenu); MenuScroller.setScrollerFor(submenu); } return found; } protected void addLibraries(JMenu menu, LibraryList libs) throws IOException { LibraryList list = new LibraryList(libs); list.sort(); for (Library lib : list) { @SuppressWarnings("serial") AbstractAction action = new AbstractAction(lib.getName()) { public void actionPerformed(ActionEvent event) { Library l = (Library) getValue("library"); try { activeEditor.getSketch().importLibrary(l); } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", l.getSrcFolder()), e); } } }; action.putValue("library", lib); // Add new element at the bottom JMenuItem item = new JMenuItem(action); item.putClientProperty("library", lib); menu.add(item); // XXX: DAM: should recurse here so that library folders can be nested } } /** * Given a folder, return a list of the header files in that folder (but not * the header files in its sub-folders, as those should be included from * within the header files at the top-level). */ static public String[] headerListFromIncludePath(File path) throws IOException { String[] list = path.list(new OnlyFilesWithExtension(".h")); if (list == null) { throw new IOException(); } return list; } protected void loadHardware(File folder) { if (!folder.isDirectory()) return; String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return; // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); for (String target : list) { // Skip reserved 'tools' folder. if (target.equals("tools")) continue; File subfolder = new File(folder, target); try { packages.put(target, new TargetPackage(target, subfolder)); } catch (TargetPlatformException e) { System.out.println("WARNING: Error loading hardware folder " + target); System.out.println(" " + e.getMessage()); } } } /** * Show the About box. */ @SuppressWarnings("serial") public void handleAbout() { final Image image = Base.getLibImage("about.jpg", activeEditor); final Window window = new Window(activeEditor) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); int w = image.getWidth(activeEditor); int h = image.getHeight(activeEditor); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.setVisible(true); } /** * Show the Preferences window. */ public void handlePrefs() { if (preferencesFrame == null) preferencesFrame = new Preferences(); preferencesFrame.showFrame(activeEditor); } /** * Get list of platform constants. */ // static public int[] getPlatforms() { // return platforms; // static public int getPlatform() { // String osname = System.getProperty("os.name"); // if (osname.indexOf("Mac") != -1) { // return PConstants.MACOSX; // } else if (osname.indexOf("Windows") != -1) { // return PConstants.WINDOWS; // } else if (osname.equals("Linux")) { // true for the ibm vm // return PConstants.LINUX; // } else { // return PConstants.OTHER; static public Platform getPlatform() { return platform; } static public String getPlatformName() { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { return "macosx"; } else if (osname.indexOf("Windows") != -1) { return "windows"; } else if (osname.equals("Linux")) { // true for the ibm vm return "linux"; } else { return "other"; } } /** * Map a platform constant to its name. * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX * @return one of "windows", "macosx", or "linux" */ static public String getPlatformName(int which) { return platformNames.get(which); } static public int getPlatformIndex(String what) { Integer entry = platformIndices.get(what); return (entry == null) ? -1 : entry.intValue(); } // These were changed to no longer rely on PApplet and PConstants because // of conflicts that could happen with older versions of core.jar, where // the MACOSX constant would instead read as the LINUX constant. /** * returns true if Processing is running on a Mac OS X machine. */ static public boolean isMacOS() { //return PApplet.platform == PConstants.MACOSX; return System.getProperty("os.name").indexOf("Mac") != -1; } /** * returns true if running on windows. */ static public boolean isWindows() { //return PApplet.platform == PConstants.WINDOWS; return System.getProperty("os.name").indexOf("Windows") != -1; } /** * true if running on linux. */ static public boolean isLinux() { //return PApplet.platform == PConstants.LINUX; return System.getProperty("os.name").indexOf("Linux") != -1; } static public File getSettingsFolder() { if (portableFolder != null) return portableFolder; File settingsFolder = null; String preferencesPath = Preferences.get("settings.path"); if (preferencesPath != null) { settingsFolder = new File(preferencesPath); } else { try { settingsFolder = platform.getSettingsFolder(); } catch (Exception e) { showError(_("Problem getting data folder"), _("Error getting the Arduino data folder."), e); } } // create the folder if it doesn't exist already if (!settingsFolder.exists()) { if (!settingsFolder.mkdirs()) { showError(_("Settings issues"), _("Arduino cannot run because it could not\n" + "create a folder to store your settings."), null); } } return settingsFolder; } /** * Convenience method to get a File object for the specified filename inside * the settings folder. * For now, only used by Preferences to get the preferences.txt file. * @param filename A file inside the settings folder. * @return filename wrapped as a File object inside the settings folder */ static public File getSettingsFile(String filename) { return new File(getSettingsFolder(), filename); } static public File getBuildFolder() { if (buildFolder == null) { String buildPath = Preferences.get("build.path"); if (buildPath != null) { buildFolder = new File(buildPath); } else { //File folder = new File(getTempFolder(), "build"); //if (!folder.exists()) folder.mkdirs(); buildFolder = createTempFolder("build"); buildFolder.deleteOnExit(); } } return buildFolder; } /** * Get the path to the platform's temporary folder, by creating * a temporary temporary file and getting its parent folder. * <br/> * Modified for revision 0094 to actually make the folder randomized * to avoid conflicts in multi-user environments. (Bug 177) */ static public File createTempFolder(String name) { try { File folder = File.createTempFile(name, null); //String tempPath = ignored.getParent(); //return new File(tempPath); folder.delete(); folder.mkdirs(); return folder; } catch (Exception e) { e.printStackTrace(); } return null; } static public LibraryList getLibraries() { return libraries; } static public String getExamplesPath() { return examplesFolder.getAbsolutePath(); } static public List<File> getLibrariesPath() { return librariesFolders; } static public File getToolsFolder() { return toolsFolder; } static public String getToolsPath() { return toolsFolder.getAbsolutePath(); } static public File getHardwareFolder() { // calculate on the fly because it's needed by Preferences.init() to find // the boards.txt and programmers.txt preferences files (which happens // before the other folders / paths get cached). return getContentFile("hardware"); } //Get the core libraries static public File getCoreLibraries(String path) { return getContentFile(path); } static public String getHardwarePath() { return getHardwareFolder().getAbsolutePath(); } static public String getAvrBasePath() { String path = getHardwarePath() + File.separator + "tools" + File.separator + "avr" + File.separator + "bin" + File.separator; if (Base.isLinux() && !(new File(path)).exists()) { return ""; // use distribution provided avr tools if bundled tools missing } return path; } /** * Returns a specific TargetPackage * * @param packageName * @return */ static public TargetPackage getTargetPackage(String packageName) { return packages.get(packageName); } /** * Returns the currently selected TargetPlatform. * * @return */ static public TargetPlatform getTargetPlatform() { String packageName = Preferences.get("target_package"); String platformName = Preferences.get("target_platform"); return getTargetPlatform(packageName, platformName); } /** * Returns a specific TargetPlatform searching Package/Platform * * @param packageName * @param platformName * @return */ static public TargetPlatform getTargetPlatform(String packageName, String platformName) { TargetPackage p = packages.get(packageName); if (p == null) return null; return p.get(platformName); } static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) { return getTargetPlatform(pack, Preferences.get("target_platform")); } static public PreferencesMap getBoardPreferences() { TargetBoard board = getTargetBoard(); PreferencesMap prefs = new PreferencesMap(board.getPreferences()); for (String menuId : board.getMenuIds()) { String entry = Preferences.get("custom_" + menuId); if (board.hasMenu(menuId) && entry != null && entry.startsWith(board.getId())) { String selectionId = entry.substring(entry.indexOf("_") + 1); prefs.putAll(board.getMenuPreferences(menuId, selectionId)); prefs.put("name", prefs.get("name") + ", " + board.getMenuLabel(menuId, selectionId)); } } return prefs; } public static TargetBoard getTargetBoard() { String boardId = Preferences.get("board"); return getTargetPlatform().getBoard(boardId); } static public File getPortableFolder() { return portableFolder; } static public String getPortableSketchbookFolder() { return portableSketchbookFolder; } static public File getSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, Preferences.get("sketchbook.path")); return new File(Preferences.get("sketchbook.path")); } static public File getSketchbookLibrariesFolder() { File libdir = new File(getSketchbookFolder(), "libraries"); if (!libdir.exists()) { try { libdir.mkdirs(); File readme = new File(libdir, "readme.txt"); FileWriter freadme = new FileWriter(readme); freadme.write(_("For information on installing libraries, see: " + "http://arduino.cc/en/Guide/Libraries\n")); freadme.close(); } catch (Exception e) { } } return libdir; } static public String getSketchbookLibrariesPath() { return getSketchbookLibrariesFolder().getAbsolutePath(); } static public File getSketchbookHardwareFolder() { return new File(getSketchbookFolder(), "hardware"); } protected File getDefaultSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, portableSketchbookFolder); File sketchbookFolder = null; try { sketchbookFolder = platform.getDefaultSketchbookFolder(); } catch (Exception e) { } if (sketchbookFolder == null) { sketchbookFolder = promptSketchbookLocation(); } // create the folder if it doesn't exist already boolean result = true; if (!sketchbookFolder.exists()) { result = sketchbookFolder.mkdirs(); } if (!result) { showError(_("You forgot your sketchbook"), _("Arduino cannot run because it could not\n" + "create a folder to store your sketchbook."), null); } return sketchbookFolder; } /** * Check for a new sketchbook location. */ static protected File promptSketchbookLocation() { File folder = null; folder = new File(System.getProperty("user.home"), "sketchbook"); if (!folder.exists()) { folder.mkdirs(); return folder; } String prompt = _("Select (or create new) folder for sketches..."); folder = Base.selectFolder(prompt, null, null); if (folder == null) { System.exit(0); } return folder; } /** * Implements the cross-platform headache of opening URLs * TODO This code should be replaced by PApplet.link(), * however that's not a static method (because it requires * an AppletContext when used as an applet), so it's mildly * trickier than just removing this method. */ static public void openURL(String url) { try { platform.openURL(url); } catch (Exception e) { showWarning(_("Problem Opening URL"), I18n.format(_("Could not open the URL\n{0}"), url), e); } } /** * Used to determine whether to disable the "Show Sketch Folder" option. * @return true If a means of opening a folder is known to be available. */ static protected boolean openFolderAvailable() { return platform.openFolderAvailable(); } /** * Implements the other cross-platform headache of opening * a folder in the machine's native file browser. */ static public void openFolder(File file) { try { platform.openFolder(file); } catch (Exception e) { showWarning(_("Problem Opening Folder"), I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e); } } static public File selectFolder(String prompt, File folder, Frame frame) { JFileChooser fc = new JFileChooser(); fc.setDialogTitle(prompt); if (folder != null) { fc.setSelectedFile(folder); } fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returned = fc.showOpenDialog(new JDialog()); if (returned == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile(); } return null; } /** * Give this Frame a Processing icon. */ static public void setIcon(Frame frame) { // don't use the low-res icon on Mac OS X; the window should // already have the right icon from the .app file. if (Base.isMacOS()) return; Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE); frame.setIconImage(image); } // someone needs to be slapped //static KeyStroke closeWindowKeyStroke; /** * Return true if the key event was a Ctrl-W or an ESC, * both indicators to close the window. * Use as part of a keyPressed() event handler for frames. */ /* static public boolean isCloseWindowEvent(KeyEvent e) { if (closeWindowKeyStroke == null) { int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers); } return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) || KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke)); } */ /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); stroke = KeyStroke.getKeyStroke('W', modifiers); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); } static public void showReference(String filename) { File referenceFolder = Base.getContentFile("reference"); File referenceFile = new File(referenceFolder, filename); openURL(referenceFile.getAbsolutePath()); } static public void showGettingStarted() { if (Base.isMacOS()) { Base.showReference(_("Guide_MacOSX.html")); } else if (Base.isWindows()) { Base.showReference(_("Guide_Windows.html")); } else { Base.openURL(_("http: } } static public void showReference() { showReference(_("index.html")); } static public void showEnvironment() { showReference(_("Guide_Environment.html")); } static public void showPlatforms() { showReference(_("environment") + File.separator + _("platforms.html")); } static public void showTroubleshooting() { showReference(_("Guide_Troubleshooting.html")); } static public void showFAQ() { showReference(_("FAQ.html")); } /** * "No cookie for you" type messages. Nothing fatal or all that * much of a bummer, but something to notify the user about. */ static public void showMessage(String title, String message) { if (title == null) title = _("Message"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.INFORMATION_MESSAGE); } } /** * Non-fatal error message with optional stack trace side dish. */ static public void showWarning(String title, String message, Exception e) { if (title == null) title = _("Warning"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.WARNING_MESSAGE); } if (e != null) e.printStackTrace(); } static public void showError(String title, String message, Throwable e) { showError(title, message, e, 1); } static public void showError(String title, String message, int exit_code) { showError(title, message, null, exit_code); } /** * Show an error message that's actually fatal to the program. * This is an error that can't be recovered. Use showWarning() * for errors that allow P5 to continue running. */ static public void showError(String title, String message, Throwable e, int exit_code) { if (title == null) title = _("Error"); if (commandLine) { System.err.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.ERROR_MESSAGE); } if (e != null) e.printStackTrace(); System.exit(exit_code); } // incomplete static public int showYesNoCancelQuestion(Editor editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); return result; // if (result == JOptionPane.YES_OPTION) { // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // } else { } else { // Pane formatting adapted from the Quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.CANCEL_OPTION; } else if (result == options[2]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } //if (result == JOptionPane.YES_OPTION) { // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // } else { static public int showYesNoQuestion(Frame editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { return JOptionPane.showConfirmDialog(editor, "<html><body>" + "<b>" + primary + "</b>" + "<br>" + secondary, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } else { // Pane formatting adapted from the Quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>" + primary + "</b>" + "<p>" + secondary + "</p>", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Yes", "No" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } /** * Retrieve a path to something in the Processing folder. Eventually this * may refer to the Contents subfolder of Processing.app, if we bundle things * up as a single .app file with no additional folders. */ // static public String getContentsPath(String filename) { // String basePath = System.getProperty("user.dir"); // /* // // do this later, when moving to .app package // if (PApplet.platform == PConstants.MACOSX) { // basePath = System.getProperty("processing.contents"); // } // */ // return basePath + File.separator + filename; /** * Get a path for something in the Processing lib folder. */ /* static public String getLibContentsPath(String filename) { String libPath = getContentsPath("lib/" + filename); File libDir = new File(libPath); if (libDir.exists()) { return libPath; } // was looking into making this run from Eclipse, but still too much mess // libPath = getContents("build/shared/lib/" + what); // libDir = new File(libPath); // if (libDir.exists()) { // return libPath; // } return null; } */ static public File getContentFile(String name) { String path = System.getProperty("user.dir"); // Get a path to somewhere inside the .app folder if (Base.isMacOS()) { // <key>javaroot</key> // <string>$JAVAROOT</string> String javaroot = System.getProperty("javaroot"); if (javaroot != null) { path = javaroot; } } File working = new File(path); return new File(working, name); } /** * Get an image associated with the current color theme. */ static public Image getThemeImage(String name, Component who) { return getLibImage("theme/" + name, who); } /** * Return an Image object from inside the Processing lib folder. */ static public Image getLibImage(String name, Component who) { Image image = null; Toolkit tk = Toolkit.getDefaultToolkit(); File imageLocation = new File(getContentFile("lib"), name); image = tk.getImage(imageLocation.getAbsolutePath()); MediaTracker tracker = new MediaTracker(who); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } return image; } /** * Return an InputStream for a file inside the Processing lib folder. */ static public InputStream getLibStream(String filename) throws IOException { return new FileInputStream(new File(getContentFile("lib"), filename)); } /** * Get the number of lines in a file by counting the number of newline * characters inside a String (and adding 1). */ static public int countLines(String what) { int count = 1; for (char c : what.toCharArray()) { if (c == '\n') count++; } return count; } /** * Same as PApplet.loadBytes(), however never does gzip decoding. */ static public byte[] loadBytesRaw(File file) throws IOException { int size = (int) file.length(); FileInputStream input = new FileInputStream(file); byte buffer[] = new byte[size]; int offset = 0; int bytesRead; while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) { offset += bytesRead; if (bytesRead == 0) break; } input.close(); // weren't properly being closed input = null; return buffer; } /** * Read from a file with a bunch of attribute/value pairs * that are separated by = and ignore comments with #. */ static public HashMap<String,String> readSettings(File inputFile) { HashMap<String,String> outgoing = new HashMap<String,String>(); if (!inputFile.exists()) return outgoing; // return empty hash String lines[] = PApplet.loadStrings(inputFile); for (int i = 0; i < lines.length; i++) { int hash = lines[i].indexOf(' String line = (hash == -1) ? lines[i].trim() : lines[i].substring(0, hash).trim(); if (line.length() == 0) continue; int equals = line.indexOf('='); if (equals == -1) { System.err.println("ignoring illegal line in " + inputFile); System.err.println(" " + line); continue; } String attr = line.substring(0, equals).trim(); String valu = line.substring(equals + 1).trim(); outgoing.put(attr, valu); } return outgoing; } static public void copyFile(File sourceFile, File targetFile) throws IOException { InputStream from = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream to = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[16 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) { to.write(buffer, 0, bytesRead); } to.flush(); from.close(); from = null; to.close(); to = null; targetFile.setLastModified(sourceFile.lastModified()); } /** * Grab the contents of a file as a string. */ static public String loadFile(File file) throws IOException { String[] contents = PApplet.loadStrings(file); if (contents == null) return null; return PApplet.join(contents, "\n"); } /** * Spew the contents of a String object out to a file. */ static public void saveFile(String str, File file) throws IOException { File temp = File.createTempFile(file.getName(), null, file.getParentFile()); PApplet.saveStrings(temp, new String[] { str }); if (file.exists()) { boolean result = file.delete(); if (!result) { throw new IOException( I18n.format( _("Could not remove old version of {0}"), file.getAbsolutePath() ) ); } } boolean result = temp.renameTo(file); if (!result) { throw new IOException( I18n.format( _("Could not replace {0}"), file.getAbsolutePath() ) ); } } /** * Copy a folder from one place to another. This ignores all dot files and * folders found in the source directory, to avoid copying silly .DS_Store * files and potentially troublesome .svn folders. */ static public void copyDir(File sourceDir, File targetDir) throws IOException { targetDir.mkdirs(); String files[] = sourceDir.list(); for (int i = 0; i < files.length; i++) { // Ignore dot files (.DS_Store), dot folders (.svn) while copying if (files[i].charAt(0) == '.') continue; //if (files[i].equals(".") || files[i].equals("..")) continue; File source = new File(sourceDir, files[i]); File target = new File(targetDir, files[i]); if (source.isDirectory()) { //target.mkdirs(); copyDir(source, target); target.setLastModified(source.lastModified()); } else { copyFile(source, target); } } } /** * Remove all files in a directory and the directory itself. */ static public void removeDir(File dir) { if (dir.exists()) { removeDescendants(dir); if (!dir.delete()) { System.err.println(I18n.format(_("Could not delete {0}"), dir)); } } } /** * Recursively remove all files within a directory, * used with removeDir(), or when the contents of a dir * should be removed, but not the directory itself. * (i.e. when cleaning temp files from lib/build) */ static public void removeDescendants(File dir) { if (!dir.exists()) return; String files[] = dir.list(); for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || files[i].equals("..")) continue; File dead = new File(dir, files[i]); if (!dead.isDirectory()) { if (!Preferences.getBoolean("compiler.save_build_files")) { if (!dead.delete()) { // temporarily disabled System.err.println(I18n.format(_("Could not delete {0}"), dead)); } } } else { removeDir(dead); //dead.delete(); } } } /** * Calculate the size of the contents of a folder. * Used to determine whether sketches are empty or not. * Note that the function calls itself recursively. */ static public int calcFolderSize(File folder) { int size = 0; String files[] = folder.list(); // null if folder doesn't exist, happens when deleting sketch if (files == null) return -1; for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || (files[i].equals("..")) || files[i].equals(".DS_Store")) continue; File fella = new File(folder, files[i]); if (fella.isDirectory()) { size += calcFolderSize(fella); } else { size += (int) fella.length(); } } return size; } /** * Recursively creates a list of all files within the specified folder, * and returns a list of their relative paths. * Ignores any files/folders prefixed with a dot. */ static public String[] listFiles(String path, boolean relative) { return listFiles(new File(path), relative); } static public String[] listFiles(File folder, boolean relative) { String path = folder.getAbsolutePath(); Vector<String> vector = new Vector<String>(); listFiles(relative ? (path + File.separator) : "", path, vector); String outgoing[] = new String[vector.size()]; vector.copyInto(outgoing); return outgoing; } static protected void listFiles(String basePath, String path, Vector<String> vector) { File folder = new File(path); String list[] = folder.list(); if (list == null) return; for (int i = 0; i < list.length; i++) { if (list[i].charAt(0) == '.') continue; File file = new File(path, list[i]); String newPath = file.getAbsolutePath(); if (newPath.startsWith(basePath)) { newPath = newPath.substring(basePath.length()); } vector.add(newPath); if (file.isDirectory()) { listFiles(basePath, newPath, vector); } } } public void handleAddLibrary() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add")); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip")); Dimension preferredSize = fileChooser.getPreferredSize(); fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fileChooser.showOpenDialog(activeEditor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File sourceFile = fileChooser.getSelectedFile(); File tmpFolder = null; try { // unpack ZIP if (!sourceFile.isDirectory()) { try { tmpFolder = FileUtils.createTempFolder(); ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder); zipDeflater.deflate(); File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs()); if (foldersInTmpFolder.length != 1) { throw new IOException(_("Zip doesn't contain a library")); } sourceFile = foldersInTmpFolder[0]; } catch (IOException e) { activeEditor.statusError(e); return; } } // is there a valid library? File libFolder = sourceFile; String libName = libFolder.getName(); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); activeEditor.statusError(mess); return; } // copy folder File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName()); if (!destinationFolder.mkdir()) { activeEditor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName())); return; } try { FileUtils.copy(sourceFile, destinationFolder); } catch (IOException e) { activeEditor.statusError(e); return; } activeEditor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu")); } finally { // delete zip created temp folder, if exists FileUtils.recursiveDelete(tmpFolder); } } public static DiscoveryManager getDiscoveryManager() { return discoveryManager; } }
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ package processing.app; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import org.apache.commons.logging.impl.LogFactoryImpl; import org.apache.commons.logging.impl.NoOpLog; import cc.arduino.packages.DiscoveryManager; import processing.app.debug.TargetBoard; import processing.app.debug.TargetPackage; import processing.app.debug.TargetPlatform; import processing.app.debug.TargetPlatformException; import processing.app.helpers.FileUtils; import processing.app.helpers.PreferencesMap; import processing.app.helpers.filefilters.OnlyDirs; import processing.app.helpers.filefilters.OnlyFilesWithExtension; import processing.app.javax.swing.filechooser.FileNameExtensionFilter; import processing.app.packages.Library; import processing.app.packages.LibraryList; import processing.app.tools.MenuScroller; import processing.app.tools.ZipDeflater; import processing.core.*; import static processing.app.I18n._; /** * The base class for the main processing application. * Primary role of this class is for platform identification and * general interaction with the system (launching URLs, loading * files and images, etc) that comes from that. */ public class Base { public static final int REVISION = 155; /** This might be replaced by main() if there's a lib/version.txt file. */ static String VERSION_NAME = "0155"; /** Set true if this a proper release rather than a numbered revision. */ static public boolean RELEASE = false; static Map<Integer, String> platformNames = new HashMap<Integer, String>(); static { platformNames.put(PConstants.WINDOWS, "windows"); platformNames.put(PConstants.MACOSX, "macosx"); platformNames.put(PConstants.LINUX, "linux"); } static HashMap<String, Integer> platformIndices = new HashMap<String, Integer>(); static { platformIndices.put("windows", PConstants.WINDOWS); platformIndices.put("macosx", PConstants.MACOSX); platformIndices.put("linux", PConstants.LINUX); } static Platform platform; private static DiscoveryManager discoveryManager = new DiscoveryManager(); static private boolean commandLine; // A single instance of the preferences window Preferences preferencesFrame; // set to true after the first time the menu is built. // so that the errors while building don't show up again. boolean builtOnce; static File buildFolder; // these are static because they're used by Sketch static private File examplesFolder; static private File toolsFolder; static private List<File> librariesFolders; // maps library name to their library folder static private LibraryList libraries; // maps #included files to their library folder static Map<String, Library> importToLibraryTable; // classpath for all known libraries for p5 // (both those in the p5/libs folder and those with lib subfolders // found in the sketchbook) static public String librariesClassPath; static public Map<String, TargetPackage> packages; // Location for untitled items static File untitledFolder; // p5 icon for the window // static Image icon; // int editorCount; List<Editor> editors = Collections.synchronizedList(new ArrayList<Editor>()); Editor activeEditor; private final Map<String, Map<String, Object>> boardsViaNetwork; static File portableFolder = null; static final String portableSketchbookFolder = "sketchbook"; static public void main(String args[]) throws Exception { System.setProperty(LogFactoryImpl.LOG_PROPERTY, NoOpLog.class.getCanonicalName()); Logger.getLogger("javax.jmdns").setLevel(Level.OFF); initPlatform(); // Portable folder portableFolder = getContentFile("portable"); if (!portableFolder.exists()) portableFolder = null; // run static initialization that grabs all the prefs Preferences.init(args); try { File versionFile = getContentFile("lib/version.txt"); if (versionFile.exists()) { String version = PApplet.loadStrings(versionFile)[0]; if (!version.equals(VERSION_NAME) && !version.equals("${version}")) { VERSION_NAME = version; RELEASE = true; } } } catch (Exception e) { e.printStackTrace(); } // help 3rd party installers find the correct hardware path Preferences.set("last.ide." + VERSION_NAME + ".hardwarepath", getHardwarePath()); Preferences.set("last.ide." + VERSION_NAME + ".daterun", "" + (new Date()).getTime() / 1000); // if (System.getProperty("mrj.version") != null) { // //String jv = System.getProperty("java.version"); // String ov = System.getProperty("os.version"); // if (ov.startsWith("10.5")) { // System.setProperty("apple.laf.useScreenMenuBar", "true"); /* commandLine = false; if (args.length >= 2) { if (args[0].startsWith("--")) { commandLine = true; } } if (PApplet.javaVersion < 1.5f) { //System.err.println("no way man"); Base.showError("Need to install Java 1.5", "This version of Processing requires \n" + "Java 1.5 or later to run properly.\n" + "Please visit java.com to upgrade.", null); } */ // // Set the look and feel before opening the window // try { // platform.setLookAndFeel(); // } catch (Exception e) { // System.err.println("Non-fatal error while setting the Look & Feel."); // System.err.println("The error message follows, however Processing should run fine."); // System.err.println(e.getMessage()); // //e.printStackTrace(); // Use native popups so they don't look so crappy on osx JPopupMenu.setDefaultLightWeightPopupEnabled(false); // Don't put anything above this line that might make GUI, // because the platform has to be inited properly first. // Make sure a full JDK is installed //initRequirements(); // setup the theme coloring fun Theme.init(); // Set the look and feel before opening the window try { platform.setLookAndFeel(); } catch (Exception e) { String mess = e.getMessage(); if (mess.indexOf("ch.randelshofer.quaqua.QuaquaLookAndFeel") == -1) { System.err.println(_("Non-fatal error while setting the Look & Feel.")); System.err.println(_("The error message follows, however Arduino should run fine.")); System.err.println(mess); } } // Create a location for untitled sketches untitledFolder = createTempFolder("untitled"); untitledFolder.deleteOnExit(); new Base(args); } static protected void setCommandLine() { commandLine = true; } static protected boolean isCommandLine() { return commandLine; } static protected void initPlatform() { try { Class<?> platformClass = Class.forName("processing.app.Platform"); if (Base.isMacOS()) { platformClass = Class.forName("processing.app.macosx.Platform"); } else if (Base.isWindows()) { platformClass = Class.forName("processing.app.windows.Platform"); } else if (Base.isLinux()) { platformClass = Class.forName("processing.app.linux.Platform"); } platform = (Platform) platformClass.newInstance(); } catch (Exception e) { Base.showError(_("Problem Setting the Platform"), _("An unknown error occurred while trying to load\n" + "platform-specific code for your machine."), e); } } static protected void initRequirements() { try { Class.forName("com.sun.jdi.VirtualMachine"); } catch (ClassNotFoundException cnfe) { Base.showPlatforms(); Base.showError(_("Please install JDK 1.5 or later"), _("Arduino requires a full JDK (not just a JRE)\n" + "to run. Please install JDK 1.5 or later.\n" + "More information can be found in the reference."), cnfe); } } public Base(String[] args) throws Exception { platform.init(this); this.boardsViaNetwork = new ConcurrentHashMap<String, Map<String, Object>>(); // Get the sketchbook path, and make sure it's set properly String sketchbookPath = Preferences.get("sketchbook.path"); // If a value is at least set, first check to see if the folder exists. // If it doesn't, warn the user that the sketchbook folder is being reset. if (sketchbookPath != null) { File sketchbookFolder; if (portableFolder != null) sketchbookFolder = new File(portableFolder, sketchbookPath); else sketchbookFolder = new File(sketchbookPath); if (!sketchbookFolder.exists()) { Base.showWarning(_("Sketchbook folder disappeared"), _("The sketchbook folder no longer exists.\n" + "Arduino will switch to the default sketchbook\n" + "location, and create a new sketchbook folder if\n" + "necessary. Arduino will then stop talking about\n" + "himself in the third person."), null); sketchbookPath = null; } } // If no path is set, get the default sketchbook folder for this platform if (sketchbookPath == null) { File defaultFolder = getDefaultSketchbookFolder(); if (portableFolder != null) Preferences.set("sketchbook.path", portableSketchbookFolder); else Preferences.set("sketchbook.path", defaultFolder.getAbsolutePath()); if (!defaultFolder.exists()) { defaultFolder.mkdirs(); } } packages = new HashMap<String, TargetPackage>(); loadHardware(getHardwareFolder()); loadHardware(getSketchbookHardwareFolder()); if (packages.size() == 0) { System.out.println(_("No valid configured cores found! Exiting...")); System.exit(3); } // Setup board-dependent variables. onBoardOrPortChange(); boolean doUpload = false; boolean doVerify = false; boolean doVerbose = false; String selectBoard = null; String selectPort = null; String currentDirectory = System.getProperty("user.dir"); List<String> filenames = new LinkedList<String>(); // Check if any files were passed in on the command line for (int i = 0; i < args.length; i++) { if (args[i].equals("--upload")) { doUpload = true; continue; } if (args[i].equals("--verify")) { doVerify = true; continue; } if (args[i].equals("--verbose") || args[i].equals("-v")) { doVerbose = true; continue; } if (args[i].equals("--board")) { i++; if (i >= args.length) showError(null, _("Argument required for --board"), 3); selectBoard = args[i]; continue; } if (args[i].equals("--port")) { i++; if (i >= args.length) showError(null, _("Argument required for --port"), 3); selectPort = args[i]; continue; } if (args[i].equals("--curdir")) { i++; if (i >= args.length) showError(null, _("Argument required for --curdir"), 3); currentDirectory = args[i]; continue; } if (args[i].equals("--pref")) { i++; if (i >= args.length) showError(null, _("Argument required for --pref"), 3); processPrefArgument(args[i]); continue; } if (args[i].equals("--preferences-file")) { i++; if (i >= args.length) showError(null, _("Argument required for --preferences-file"), 3); // Argument should be already processed by Preferences.init(...) continue; } if (args[i].startsWith(" showError(null, I18n.format(_("unknown option: {0}"), args[i]), 3); filenames.add(args[i]); } if ((doUpload || doVerify) && filenames.size() != 1) showError(null, _("Must specify exactly one sketch file"), 3); for (String path: filenames) { // Fix a problem with systems that use a non-ASCII languages. Paths are // being passed in with 8.3 syntax, which makes the sketch loader code // unhappy, since the sketch folder naming doesn't match up correctly. if (isWindows()) { try { File file = new File(path); path = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } } if (!new File(path).isAbsolute()) { path = new File(currentDirectory, path).getAbsolutePath(); } if (handleOpen(path, nextEditorLocation(), !(doUpload || doVerify)) == null) { String mess = I18n.format(_("Failed to open sketch: \"{0}\""), path); // Open failure is fatal in upload/verify mode if (doUpload || doVerify) showError(null, mess, 2); else showWarning(null, mess, null); } } if (doUpload || doVerify) { // Set verbosity for command line build Preferences.set("build.verbose", "" + doVerbose); Preferences.set("upload.verbose", "" + doVerbose); Editor editor = editors.get(0); // Do board selection if requested processBoardArgument(selectBoard); if (doUpload) { // Build and upload if (selectPort != null) editor.selectSerialPort(selectPort); editor.exportHandler.run(); } else { // Build only editor.runHandler.run(); } // Error during build or upload int res = editor.status.mode; if (res == EditorStatus.ERR) System.exit(1); // No errors exit gracefully System.exit(0); } // Check if there were previously opened sketches to be restored restoreSketches(); // Create a new empty window (will be replaced with any files to be opened) if (editors.isEmpty()) { handleNew(); } // Check for updates if (Preferences.getBoolean("update.check")) { new UpdateCheck(this); } } protected void processBoardArgument(String selectBoard) { // No board selected? Nothing to do if (selectBoard == null) return; String[] split = selectBoard.split(":", 4); if (split.length < 3) { showError(null, I18n.format(_("{0}: Invalid board name, it should be of the form \"package:arch:board\" or \"package:arch:board:options\""), selectBoard), 3); } TargetPackage targetPackage = getTargetPackage(split[0]); if (targetPackage == null) { showError(null, I18n.format(_("{0}: Unknown package"), split[0]), 3); } TargetPlatform targetPlatform = targetPackage.get(split[1]); if (targetPlatform == null) { showError(null, I18n.format(_("{0}: Unknown architecture"), split[1]), 3); } TargetBoard targetBoard = targetPlatform.getBoard(split[2]); if (targetBoard == null) { showError(null, I18n.format(_("{0}: Unknown board"), split[2]), 3); } selectBoard(targetBoard); if (split.length > 3) { String[] options = split[3].split(","); for (String option : options) { String[] keyValue = option.split("=", 2); if (keyValue.length != 2) showError(null, I18n.format(_("{0}: Invalid option, should be of the form \"name=value\""), option, targetBoard.getId()), 3); String key = keyValue[0].trim(); String value = keyValue[1].trim(); if (!targetBoard.hasMenu(key)) showError(null, I18n.format(_("{0}: Invalid option for board \"{1}\""), key, targetBoard.getId()), 3); if (targetBoard.getMenuLabel(key, value) == null) showError(null, I18n.format(_("{0}: Invalid option for \"{1}\" option for board \"{2}\""), value, key, targetBoard.getId()), 3); Preferences.set("custom_" + key, targetBoard.getId() + "_" + value); } } } protected void processPrefArgument(String arg) { String[] split = arg.split("=", 2); if (split.length != 2 || split[0].isEmpty()) showError(null, I18n.format(_("{0}: Invalid argument to --pref, should be of the form \"pref=value\""), arg), 3); Preferences.set(split[0], split[1]); } public Map<String, Map<String, Object>> getBoardsViaNetwork() { return new HashMap<String, Map<String, Object>>(boardsViaNetwork); } /** * Post-constructor setup for the editor area. Loads the last * sketch that was used (if any), and restores other Editor settings. * The complement to "storePreferences", this is called when the * application is first launched. * @throws Exception */ protected boolean restoreSketches() throws Exception { // figure out window placement Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); boolean windowPositionValid = true; if (Preferences.get("last.screen.height") != null) { // if screen size has changed, the window coordinates no longer // make sense, so don't use them unless they're identical int screenW = Preferences.getInteger("last.screen.width"); int screenH = Preferences.getInteger("last.screen.height"); if ((screen.width != screenW) || (screen.height != screenH)) { windowPositionValid = false; } /* int windowX = Preferences.getInteger("last.window.x"); int windowY = Preferences.getInteger("last.window.y"); if ((windowX < 0) || (windowY < 0) || (windowX > screenW) || (windowY > screenH)) { windowPositionValid = false; } */ } else { windowPositionValid = false; } // Iterate through all sketches that were open last time p5 was running. // If !windowPositionValid, then ignore the coordinates found for each. // Save the sketch path and window placement for each open sketch int count = Preferences.getInteger("last.sketch.count"); int opened = 0; for (int i = 0; i < count; i++) { String path = Preferences.get("last.sketch" + i + ".path"); if (portableFolder != null) { File absolute = new File(portableFolder, path); try { path = absolute.getCanonicalPath(); } catch (IOException e) { // path unchanged. } } int[] location; if (windowPositionValid) { String locationStr = Preferences.get("last.sketch" + i + ".location"); location = PApplet.parseInt(PApplet.split(locationStr, ',')); } else { location = nextEditorLocation(); } // If file did not exist, null will be returned for the Editor if (handleOpen(path, location, true) != null) { opened++; } } return (opened > 0); } /** * Store list of sketches that are currently open. * Called when the application is quitting and documents are still open. */ protected void storeSketches() { // Save the width and height of the screen Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); Preferences.setInteger("last.screen.width", screen.width); Preferences.setInteger("last.screen.height", screen.height); String untitledPath = untitledFolder.getAbsolutePath(); // Save the sketch path and window placement for each open sketch int index = 0; for (Editor editor : editors) { String path = editor.getSketch().getMainFilePath(); // In case of a crash, save untitled sketches if they contain changes. // (Added this for release 0158, may not be a good idea.) if (path.startsWith(untitledPath) && !editor.getSketch().isModified()) { continue; } if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) continue; } Preferences.set("last.sketch" + index + ".path", path); int[] location = editor.getPlacement(); String locationStr = PApplet.join(PApplet.str(location), ","); Preferences.set("last.sketch" + index + ".location", locationStr); index++; } Preferences.setInteger("last.sketch.count", index); } // If a sketch is untitled on quit, may need to store the new name // rather than the location from the temp folder. protected void storeSketchPath(Editor editor, int index) { String path = editor.getSketch().getMainFilePath(); String untitledPath = untitledFolder.getAbsolutePath(); if (path.startsWith(untitledPath)) { path = ""; } else if (portableFolder != null) { path = FileUtils.relativePath(portableFolder.toString(), path); if (path == null) path = ""; } Preferences.set("last.sketch" + index + ".path", path); } /* public void storeSketch(Editor editor) { int index = -1; for (int i = 0; i < editorCount; i++) { if (editors[i] == editor) { index = i; break; } } if (index == -1) { System.err.println("Problem storing sketch " + editor.sketch.name); } else { String path = editor.sketch.getMainFilePath(); Preferences.set("last.sketch" + index + ".path", path); } } */ // Because of variations in native windowing systems, no guarantees about // changes to the focused and active Windows can be made. Developers must // never assume that this Window is the focused or active Window until this // Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event. protected void handleActivated(Editor whichEditor) { activeEditor = whichEditor; // set the current window to be the console that's getting output EditorConsole.setEditor(activeEditor); } protected int[] nextEditorLocation() { int defaultWidth = Preferences.getInteger("editor.window.width.default"); int defaultHeight = Preferences.getInteger("editor.window.height.default"); if (activeEditor == null) { Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds(); // If no current active editor, use default placement return new int[] { (screen.width - defaultWidth) / 2, (screen.height - defaultHeight) / 2, defaultWidth, defaultHeight, 0 }; } else { Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // With a currently active editor, open the new window // using the same dimensions, but offset slightly. synchronized (editors) { final int OVER = 50; // In release 0160, don't //location = activeEditor.getPlacement(); Editor lastOpened = activeEditor; int[] location = lastOpened.getPlacement(); // Just in case the bounds for that window are bad location[0] += OVER; location[1] += OVER; if (location[0] == OVER || location[2] == OVER || location[0] + location[2] > screen.width || location[1] + location[3] > screen.height) { // Warp the next window to a randomish location on screen. return new int[] { (int) (Math.random() * (screen.width - defaultWidth)), (int) (Math.random() * (screen.height - defaultHeight)), defaultWidth, defaultHeight, 0 }; } return location; } } } boolean breakTime = false; String[] months = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; /** * Handle creating a sketch folder, return its base .pde file * or null if the operation was canceled. * @param shift whether shift is pressed, which will invert prompt setting * @param noPrompt disable prompt, no matter the setting */ protected String createNewUntitled() throws IOException { File newbieDir = null; String newbieName = null; // In 0126, untitled sketches will begin in the temp folder, // and then moved to a new location because Save will default to Save As. File sketchbookDir = getSketchbookFolder(); File newbieParentDir = untitledFolder; // Use a generic name like sketch_031008a, the date plus a char int index = 0; //SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd"); //SimpleDateFormat formatter = new SimpleDateFormat("MMMdd"); //String purty = formatter.format(new Date()).toLowerCase(); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DAY_OF_MONTH); // 1..31 int month = cal.get(Calendar.MONTH); // 0..11 String purty = months[month] + PApplet.nf(day, 2); do { if (index == 26) { // In 0159, avoid running past z by sending people outdoors. if (!breakTime) { Base.showWarning(_("Time for a Break"), _("You've reached the limit for auto naming of new sketches\n" + "for the day. How about going for a walk instead?"), null); breakTime = true; } else { Base.showWarning(_("Sunshine"), _("No really, time for some fresh air for you."), null); } return null; } newbieName = "sketch_" + purty + ((char) ('a' + index)); newbieDir = new File(newbieParentDir, newbieName); index++; // Make sure it's not in the temp folder *and* it's not in the sketchbook } while (newbieDir.exists() || new File(sketchbookDir, newbieName).exists()); // Make the directory for the new sketch newbieDir.mkdirs(); // Make an empty pde file File newbieFile = new File(newbieDir, newbieName + ".ino"); if (!newbieFile.createNewFile()) { throw new IOException(); } FileUtils.copyFile(new File(getContentFile("examples"), "01.Basics" + File.separator + "BareMinimum" + File.separator + "BareMinimum.ino"), newbieFile); return newbieFile.getAbsolutePath(); } /** * Create a new untitled document in a new sketch window. * @throws Exception */ public void handleNew() throws Exception { try { String path = createNewUntitled(); if (path != null) { Editor editor = handleOpen(path); editor.untitled = true; } } catch (IOException e) { if (activeEditor != null) { activeEditor.statusError(e); } } } /** * Replace the sketch in the current window with a new untitled document. */ public void handleNewReplace() { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); // Actually replace things handleNewReplaceImpl(); } protected void handleNewReplaceImpl() { try { String path = createNewUntitled(); if (path != null) { activeEditor.handleOpenInternal(path); activeEditor.untitled = true; } // return true; } catch (IOException e) { activeEditor.statusError(e); // return false; } } /** * Open a sketch, replacing the sketch in the current window. * @param path Location of the primary pde file for the sketch. */ public void handleOpenReplace(String path) { if (!activeEditor.checkModified()) { return; // sketch was modified, and user canceled } // Close the running window, avoid window boogers with multiple sketches activeEditor.internalCloseRunner(); boolean loaded = activeEditor.handleOpenInternal(path); if (!loaded) { // replace the document without checking if that's ok handleNewReplaceImpl(); } } /** * Prompt for a sketch to open, and open it in a new window. * @throws Exception */ public void handleOpenPrompt() throws Exception { // get the frontmost window frame for placing file dialog JFileChooser fd = new JFileChooser(Preferences.get("last.folder", Base.getSketchbookFolder().getAbsolutePath())); fd.setDialogTitle(_("Open an Arduino sketch...")); fd.setFileSelectionMode(JFileChooser.FILES_ONLY); fd.setFileFilter(new FileNameExtensionFilter(_("Sketches (*.ino, *.pde)"), "ino", "pde")); Dimension preferredSize = fd.getPreferredSize(); fd.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fd.showOpenDialog(activeEditor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File inputFile = fd.getSelectedFile(); Preferences.set("last.folder", inputFile.getAbsolutePath()); handleOpen(inputFile.getAbsolutePath()); } /** * Open a sketch in a new window. * @param path Path to the pde file for the sketch in question * @return the Editor object, so that properties (like 'untitled') * can be set by the caller * @throws Exception */ public Editor handleOpen(String path) throws Exception { return handleOpen(path, nextEditorLocation(), true); } protected Editor handleOpen(String path, int[] location, boolean showEditor) throws Exception { // System.err.println("entering handleOpen " + path); File file = new File(path); if (!file.exists()) return null; // System.err.println(" editors: " + editors); // Cycle through open windows to make sure that it's not already open. for (Editor editor : editors) { if (editor.getSketch().getMainFilePath().equals(path)) { editor.toFront(); // System.err.println(" handleOpen: already opened"); return editor; } } // If the active editor window is an untitled, and un-modified document, // just replace it with the file that's being opened. // if (activeEditor != null) { // Sketch activeSketch = activeEditor.sketch; // if (activeSketch.isUntitled() && !activeSketch.isModified()) { // // if it's an untitled, unmodified document, it can be replaced. // // except in cases where a second blank window is being opened. // if (!path.startsWith(untitledFolder.getAbsolutePath())) { // activeEditor.handleOpenUnchecked(path, 0, 0, 0, 0); // return activeEditor; // System.err.println(" creating new editor"); Editor editor = new Editor(this, path, location); // Editor editor = null; // try { // editor = new Editor(this, path, location); // } catch (Exception e) { // e.printStackTrace(); // System.err.flush(); // System.out.flush(); // System.exit(1); // System.err.println(" done creating new editor"); // EditorConsole.systemErr.println(" done creating new editor"); // Make sure that the sketch actually loaded if (editor.getSketch() == null) { // System.err.println("sketch was null, getting out of handleOpen"); return null; // Just walk away quietly } // if (editors == null) { // editors = new Editor[5]; // if (editorCount == editors.length) { // editors = (Editor[]) PApplet.expand(editors); // editors[editorCount++] = editor; editors.add(editor); // if (markedForClose != null) { // Point p = markedForClose.getLocation(); // handleClose(markedForClose, false); // // open the new window in // editor.setLocation(p); // now that we're ready, show the window // (don't do earlier, cuz we might move it based on a window being closed) if (showEditor) editor.setVisible(true); // System.err.println("exiting handleOpen"); return editor; } /** * Close a sketch as specified by its editor window. * @param editor Editor object of the sketch to be closed. * @return true if succeeded in closing, false if canceled. */ public boolean handleClose(Editor editor) { // Check if modified // boolean immediate = editors.size() == 1; if (!editor.checkModified()) { return false; } // Close the running window, avoid window boogers with multiple sketches editor.internalCloseRunner(); if (editors.size() == 1) { // For 0158, when closing the last window /and/ it was already an // untitled sketch, just give up and let the user quit. // if (Preferences.getBoolean("sketchbook.closing_last_window_quits") || // (editor.untitled && !editor.getSketch().isModified())) { if (Base.isMacOS()) { Object[] options = { "OK", "Cancel" }; String prompt = _("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Are you sure you want to Quit?</b>" + "<p>Closing the last open sketch will quit Arduino."); int result = JOptionPane.showOptionDialog(editor, prompt, _("Quit"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) { return false; } } // This will store the sketch count as zero editors.remove(editor); try { Editor.serialMonitor.close(); } catch (Exception e) { //ignore } storeSketches(); // Save out the current prefs state Preferences.save(); // Since this wasn't an actual Quit event, call System.exit() System.exit(0); } else { // More than one editor window open, // proceed with closing the current window. editor.setVisible(false); editor.dispose(); // for (int i = 0; i < editorCount; i++) { // if (editor == editors[i]) { // for (int j = i; j < editorCount-1; j++) { // editors[j] = editors[j+1]; // editorCount--; // // Set to null so that garbage collection occurs // editors[editorCount] = null; editors.remove(editor); } return true; } /** * Handler for File &rarr; Quit. * @return false if canceled, true otherwise. */ public boolean handleQuit() { // If quit is canceled, this will be replaced anyway // by a later handleQuit() that is not canceled. storeSketches(); try { Editor.serialMonitor.close(); } catch (Exception e) { // ignore } if (handleQuitEach()) { // make sure running sketches close before quitting for (Editor editor : editors) { editor.internalCloseRunner(); } // Save out the current prefs state Preferences.save(); if (!Base.isMacOS()) { // If this was fired from the menu or an AppleEvent (the Finder), // then Mac OS X will send the terminate signal itself. System.exit(0); } return true; } return false; } /** * Attempt to close each open sketch in preparation for quitting. * @return false if canceled along the way */ protected boolean handleQuitEach() { int index = 0; for (Editor editor : editors) { if (editor.checkModified()) { // Update to the new/final sketch path for this fella storeSketchPath(editor, index); index++; } else { return false; } } return true; } /** * Asynchronous version of menu rebuild to be used on save and rename * to prevent the interface from locking up until the menus are done. */ protected void rebuildSketchbookMenus() { //System.out.println("async enter"); //new Exception().printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { //System.out.println("starting rebuild"); rebuildSketchbookMenu(Editor.sketchbookMenu); rebuildToolbarMenu(Editor.toolbarMenu); //System.out.println("done with rebuild"); } }); //System.out.println("async exit"); } protected void rebuildToolbarMenu(JMenu menu) { JMenuItem item; menu.removeAll(); // Add the single "Open" item item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { handleOpenPrompt(); } catch (Exception e1) { e1.printStackTrace(); } } }); menu.add(item); menu.addSeparator(); // Add a list of all sketches and subfolders try { boolean sketches = addSketches(menu, getSketchbookFolder(), true); if (sketches) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } // Add each of the subfolders of examples directly to the menu try { boolean found = addSketches(menu, examplesFolder, true); if (found) menu.addSeparator(); } catch (IOException e) { e.printStackTrace(); } } protected void rebuildSketchbookMenu(JMenu menu) { //System.out.println("rebuilding sketchbook menu"); //new Exception().printStackTrace(); try { menu.removeAll(); addSketches(menu, getSketchbookFolder(), false); //addSketches(menu, getSketchbookFolder()); } catch (IOException e) { e.printStackTrace(); } } public LibraryList getIDELibs() { if (libraries == null) return new LibraryList(); LibraryList res = new LibraryList(libraries); res.removeAll(getUserLibs()); return res; } public LibraryList getUserLibs() { if (libraries == null) return new LibraryList(); return libraries.filterLibrariesInSubfolder(getSketchbookFolder()); } public void rebuildImportMenu(JMenu importMenu) { importMenu.removeAll(); JMenuItem addLibraryMenuItem = new JMenuItem(_("Add Library...")); addLibraryMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.this.handleAddLibrary(); Base.this.onBoardOrPortChange(); Base.this.rebuildImportMenu(Editor.importMenu); Base.this.rebuildExamplesMenu(Editor.examplesMenu); } }); importMenu.add(addLibraryMenuItem); importMenu.addSeparator(); // Split between user supplied libraries and IDE libraries TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform != null) { LibraryList ideLibs = getIDELibs(); LibraryList userLibs = getUserLibs(); try { // Find the current target. Get the platform, and then select the // correct name and core path. PreferencesMap prefs = targetPlatform.getPreferences(); if (prefs != null) { String platformName = prefs.get("name"); if (platformName != null) { JMenuItem platformItem = new JMenuItem(_(platformName)); platformItem.setEnabled(false); importMenu.add(platformItem); } } if (ideLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, ideLibs); } if (userLibs.size() > 0) { importMenu.addSeparator(); addLibraries(importMenu, userLibs); } } catch (IOException e) { e.printStackTrace(); } } } public void rebuildExamplesMenu(JMenu menu) { try { menu.removeAll(); // Add examples from distribution "example" folder boolean found = addSketches(menu, examplesFolder, false); if (found) menu.addSeparator(); // Add examples from libraries LibraryList ideLibs = getIDELibs(); ideLibs.sort(); for (Library lib : ideLibs) addSketchesSubmenu(menu, lib, false); LibraryList userLibs = getUserLibs(); if (userLibs.size()>0) { menu.addSeparator(); userLibs.sort(); for (Library lib : userLibs) addSketchesSubmenu(menu, lib, false); } } catch (IOException e) { e.printStackTrace(); } } public LibraryList scanLibraries(List<File> folders) throws IOException { LibraryList res = new LibraryList(); for (File folder : folders) res.addOrReplaceAll(scanLibraries(folder)); return res; } public LibraryList scanLibraries(File folder) throws IOException { LibraryList res = new LibraryList(); String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return res; for (String libName : list) { File subfolder = new File(folder, libName); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); Base.showMessage(_("Ignoring bad library name"), mess); continue; } try { Library lib = Library.create(subfolder); // (also replace previously found libs with the same name) if (lib != null) res.addOrReplace(lib); } catch (IOException e) { System.out.println(I18n.format(_("Invalid library found in {0}: {1}"), subfolder, e.getMessage())); } } return res; } public void onBoardOrPortChange() { TargetPlatform targetPlatform = getTargetPlatform(); if (targetPlatform == null) return; // Calculate paths for libraries and examples examplesFolder = getContentFile("examples"); toolsFolder = getContentFile("tools"); File platformFolder = targetPlatform.getFolder(); librariesFolders = new ArrayList<File>(); librariesFolders.add(getContentFile("libraries")); String core = getBoardPreferences().get("build.core"); if (core.contains(":")) { String referencedCore = core.split(":")[0]; TargetPlatform referencedPlatform = Base.getTargetPlatform(referencedCore, targetPlatform.getId()); if (referencedPlatform != null) { File referencedPlatformFolder = referencedPlatform.getFolder(); librariesFolders.add(new File(referencedPlatformFolder, "libraries")); } } librariesFolders.add(new File(platformFolder, "libraries")); librariesFolders.add(getSketchbookLibrariesFolder()); // Scan for libraries in each library folder. // Libraries located in the latest folders on the list can override // other libraries with the same name. try { libraries = scanLibraries(librariesFolders); } catch (IOException e) { showWarning(_("Error"), _("Error loading libraries"), e); } // Populate importToLibraryTable importToLibraryTable = new HashMap<String, Library>(); for (Library lib : libraries) { try { String headers[] = headerListFromIncludePath(lib.getSrcFolder()); for (String header : headers) { importToLibraryTable.put(header, lib); } } catch (IOException e) { showWarning(_("Error"), I18n .format("Unable to list header files in {0}", lib.getSrcFolder()), e); } } // Update editors status bar for (Editor editor : editors) editor.onBoardOrPortChange(); } public void rebuildBoardsMenu(JMenu toolsMenu, Editor editor) throws Exception { JMenu boardsMenu = getBoardCustomMenu(); boolean first = true; List<JMenuItem> menuItemsToClickAfterStartup = new LinkedList<JMenuItem>(); ButtonGroup boardsButtonGroup = new ButtonGroup(); Map<String, ButtonGroup> buttonGroupsMap = new HashMap<String, ButtonGroup>(); // Generate custom menus for all platforms Set<String> titles = new HashSet<String>(); for (TargetPackage targetPackage : packages.values()) { for (TargetPlatform targetPlatform : targetPackage.platforms()) titles.addAll(targetPlatform.getCustomMenus().values()); } for (String title : titles) makeBoardCustomMenu(toolsMenu, _(title)); // Cycle through all packages for (TargetPackage targetPackage : packages.values()) { // For every package cycle through all platform for (TargetPlatform targetPlatform : targetPackage.platforms()) { // Add a separator from the previous platform if (!first) boardsMenu.add(new JSeparator()); first = false; // Add a title for each platform String platformLabel = targetPlatform.getPreferences().get("name"); if (platformLabel != null && !targetPlatform.getBoards().isEmpty()) { JMenuItem menuLabel = new JMenuItem(_(platformLabel)); menuLabel.setEnabled(false); boardsMenu.add(menuLabel); } // Cycle through all boards of this platform for (TargetBoard board : targetPlatform.getBoards().values()) { JMenuItem item = createBoardMenusAndCustomMenus(menuItemsToClickAfterStartup, buttonGroupsMap, board, targetPlatform, targetPackage); boardsMenu.add(item); boardsButtonGroup.add(item); } } } if (menuItemsToClickAfterStartup.isEmpty()) { menuItemsToClickAfterStartup.add(selectFirstEnabledMenuItem(boardsMenu)); } for (JMenuItem menuItemToClick : menuItemsToClickAfterStartup) { menuItemToClick.setSelected(true); menuItemToClick.getAction().actionPerformed(new ActionEvent(this, -1, "")); } } private JRadioButtonMenuItem createBoardMenusAndCustomMenus( List<JMenuItem> menuItemsToClickAfterStartup, Map<String, ButtonGroup> buttonGroupsMap, TargetBoard board, TargetPlatform targetPlatform, TargetPackage targetPackage) throws Exception { String selPackage = Preferences.get("target_package"); String selPlatform = Preferences.get("target_platform"); String selBoard = Preferences.get("board"); String boardId = board.getId(); String packageName = targetPackage.getId(); String platformName = targetPlatform.getId(); // Setup a menu item for the current board @SuppressWarnings("serial") Action action = new AbstractAction(board.getName()) { public void actionPerformed(ActionEvent actionevent) { selectBoard((TargetBoard)getValue("b")); } }; action.putValue("b", board); JRadioButtonMenuItem item = new JRadioButtonMenuItem(action); if (selBoard.equals(boardId) && selPackage.equals(packageName) && selPlatform.equals(platformName)) { menuItemsToClickAfterStartup.add(item); } PreferencesMap customMenus = targetPlatform.getCustomMenus(); for (final String menuId : customMenus.keySet()) { String title = customMenus.get(menuId); JMenu menu = getBoardCustomMenu(_(title)); if (board.hasMenu(menuId)) { PreferencesMap boardCustomMenu = board.getMenuLabels(menuId); for (String customMenuOption : boardCustomMenu.keySet()) { @SuppressWarnings("serial") Action subAction = new AbstractAction(_(boardCustomMenu.get(customMenuOption))) { public void actionPerformed(ActionEvent e) { Preferences.set("custom_" + menuId, ((TargetBoard)getValue("board")).getId() + "_" + getValue("custom_menu_option")); } }; subAction.putValue("board", board); subAction.putValue("custom_menu_option", customMenuOption); if (!buttonGroupsMap.containsKey(menuId)) { buttonGroupsMap.put(menuId, new ButtonGroup()); } JRadioButtonMenuItem subItem = new JRadioButtonMenuItem(subAction); menu.add(subItem); buttonGroupsMap.get(menuId).add(subItem); String selectedCustomMenuEntry = Preferences.get("custom_" + menuId); if (selBoard.equals(boardId) && (boardId + "_" + customMenuOption).equals(selectedCustomMenuEntry)) { menuItemsToClickAfterStartup.add(subItem); } } } } return item; } private static void filterVisibilityOfSubsequentBoardMenus(TargetBoard board, int fromIndex) { for (int i = fromIndex; i < Editor.boardsMenus.size(); i++) { JMenu menu = Editor.boardsMenus.get(i); for (int m = 0; m < menu.getItemCount(); m++) { JMenuItem menuItem = menu.getItem(m); menuItem.setVisible(menuItem.getAction().getValue("board").equals(board)); } menu.setVisible(ifThereAreVisibleItemsOn(menu)); if (menu.isVisible()) { JMenuItem visibleSelectedOrFirstMenuItem = selectVisibleSelectedOrFirstMenuItem(menu); if (!visibleSelectedOrFirstMenuItem.isSelected()) { visibleSelectedOrFirstMenuItem.setSelected(true); visibleSelectedOrFirstMenuItem.getAction().actionPerformed(null); } } } } private static boolean ifThereAreVisibleItemsOn(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { if (menu.getItem(i).isVisible()) { return true; } } return false; } private JMenu makeBoardCustomMenu(JMenu toolsMenu, String label) { JMenu menu = new JMenu(label); Editor.boardsMenus.add(menu); toolsMenu.add(menu); return menu; } private JMenu getBoardCustomMenu() throws Exception { return getBoardCustomMenu(_("Board")); } private JMenu getBoardCustomMenu(String label) throws Exception { for (JMenu menu : Editor.boardsMenus) if (label.equals(menu.getText())) return menu; throw new Exception("Custom menu not found!"); } private static JMenuItem selectVisibleSelectedOrFirstMenuItem(JMenu menu) { JMenuItem firstVisible = null; for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isVisible()) { if (item.isSelected()) { return item; } if (firstVisible == null) { firstVisible = item; } } } if (firstVisible != null) { return firstVisible; } throw new IllegalStateException("Menu has no enabled items"); } private static JMenuItem selectFirstEnabledMenuItem(JMenu menu) { for (int i = 0; i < menu.getItemCount(); i++) { JMenuItem item = menu.getItem(i); if (item != null && item.isEnabled()) { return item; } } throw new IllegalStateException("Menu has no enabled items"); } private void selectBoard(TargetBoard targetBoard) { TargetPlatform targetPlatform = targetBoard.getContainerPlatform(); TargetPackage targetPackage = targetPlatform.getContainerPackage(); Preferences.set("target_package", targetPackage.getId()); Preferences.set("target_platform", targetPlatform.getId()); Preferences.set("board", targetBoard.getId()); File platformFolder = targetPlatform.getFolder(); Preferences.set("runtime.platform.path", platformFolder.getAbsolutePath()); Preferences.set("runtime.hardware.path", platformFolder.getParentFile().getAbsolutePath()); filterVisibilityOfSubsequentBoardMenus(targetBoard, 1); onBoardOrPortChange(); rebuildImportMenu(Editor.importMenu); rebuildExamplesMenu(Editor.examplesMenu); } public void rebuildProgrammerMenu(JMenu menu) { menu.removeAll(); ButtonGroup group = new ButtonGroup(); for (TargetPackage targetPackage : packages.values()) { for (TargetPlatform targetPlatform : targetPackage.platforms()) { for (String programmer : targetPlatform.getProgrammers().keySet()) { String id = targetPackage.getId() + ":" + programmer; @SuppressWarnings("serial") AbstractAction action = new AbstractAction(targetPlatform .getProgrammer(programmer).get("name")) { public void actionPerformed(ActionEvent actionevent) { Preferences.set("programmer", "" + getValue("id")); } }; action.putValue("id", id); JMenuItem item = new JRadioButtonMenuItem(action); if (Preferences.get("programmer").equals(id)) item.setSelected(true); group.add(item); menu.add(item); } } } } /** * Scan a folder recursively, and add any sketches found to the menu * specified. Set the openReplaces parameter to true when opening the sketch * should replace the sketch in the current window, or false when the * sketch should open in a new window. */ protected boolean addSketches(JMenu menu, File folder, final boolean replaceExisting) throws IOException { if (folder == null) return false; if (!folder.isDirectory()) return false; File[] files = folder.listFiles(); // If a bad folder or unreadable or whatever, this will come back null if (files == null) return false; // Alphabetize files, since it's not always alpha order Arrays.sort(files, new Comparator<File>() { @Override public int compare(File file, File file2) { return file.getName().compareToIgnoreCase(file2.getName()); } }); boolean ifound = false; for (File subfolder : files) { if (FileUtils.isSCCSOrHiddenFile(subfolder)) { continue; } if (!subfolder.isDirectory()) continue; if (addSketchesSubmenu(menu, subfolder.getName(), subfolder, replaceExisting)) { ifound = true; } } return ifound; } private boolean addSketchesSubmenu(JMenu menu, Library lib, boolean replaceExisting) throws IOException { return addSketchesSubmenu(menu, lib.getName(), lib.getFolder(), replaceExisting); } private boolean addSketchesSubmenu(JMenu menu, String name, File folder, final boolean replaceExisting) throws IOException { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { String path = e.getActionCommand(); if (new File(path).exists()) { boolean replace = replaceExisting; if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { replace = !replace; } if (replace) { handleOpenReplace(path); } else { try { handleOpen(path); } catch (Exception e1) { e1.printStackTrace(); } } } else { showWarning(_("Sketch Does Not Exist"), _("The selected sketch no longer exists.\n" + "You may need to restart Arduino to update\n" + "the sketchbook menu."), null); } } }; File entry = new File(folder, name + ".ino"); if (!entry.exists() && (new File(folder, name + ".pde")).exists()) entry = new File(folder, name + ".pde"); // if a .pde file of the same prefix as the folder exists.. if (entry.exists()) { if (!Sketch.isSanitaryName(name)) { if (!builtOnce) { String complaining = I18n .format( _("The sketch \"{0}\" cannot be used.\n" + "Sketch names must contain only basic letters and numbers\n" + "(ASCII-only with no spaces, " + "and it cannot start with a number).\n" + "To get rid of this message, remove the sketch from\n" + "{1}"), name, entry.getAbsolutePath()); Base.showMessage(_("Ignoring sketch with bad name"), complaining); } return false; } JMenuItem item = new JMenuItem(name); item.addActionListener(listener); item.setActionCommand(entry.getAbsolutePath()); menu.add(item); return true; } // don't create an extra menu level for a folder named "examples" if (folder.getName().equals("examples")) return addSketches(menu, folder, replaceExisting); // not a sketch folder, but maybe a subfolder containing sketches JMenu submenu = new JMenu(name); boolean found = addSketches(submenu, folder, replaceExisting); if (found) { menu.add(submenu); MenuScroller.setScrollerFor(submenu); } return found; } protected void addLibraries(JMenu menu, LibraryList libs) throws IOException { LibraryList list = new LibraryList(libs); list.sort(); for (Library lib : list) { @SuppressWarnings("serial") AbstractAction action = new AbstractAction(lib.getName()) { public void actionPerformed(ActionEvent event) { Library l = (Library) getValue("library"); try { activeEditor.getSketch().importLibrary(l); } catch (IOException e) { showWarning(_("Error"), I18n.format("Unable to list header files in {0}", l.getSrcFolder()), e); } } }; action.putValue("library", lib); // Add new element at the bottom JMenuItem item = new JMenuItem(action); item.putClientProperty("library", lib); menu.add(item); // XXX: DAM: should recurse here so that library folders can be nested } } /** * Given a folder, return a list of the header files in that folder (but not * the header files in its sub-folders, as those should be included from * within the header files at the top-level). */ static public String[] headerListFromIncludePath(File path) throws IOException { String[] list = path.list(new OnlyFilesWithExtension(".h")); if (list == null) { throw new IOException(); } return list; } protected void loadHardware(File folder) { if (!folder.isDirectory()) return; String list[] = folder.list(new OnlyDirs()); // if a bad folder or something like that, this might come back null if (list == null) return; // alphabetize list, since it's not always alpha order // replaced hella slow bubble sort with this feller for 0093 Arrays.sort(list, String.CASE_INSENSITIVE_ORDER); for (String target : list) { // Skip reserved 'tools' folder. if (target.equals("tools")) continue; File subfolder = new File(folder, target); try { packages.put(target, new TargetPackage(target, subfolder)); } catch (TargetPlatformException e) { System.out.println("WARNING: Error loading hardware folder " + target); System.out.println(" " + e.getMessage()); } } } /** * Show the About box. */ @SuppressWarnings("serial") public void handleAbout() { final Image image = Base.getLibImage("about.jpg", activeEditor); final Window window = new Window(activeEditor) { public void paint(Graphics g) { g.drawImage(image, 0, 0, null); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setFont(new Font("SansSerif", Font.PLAIN, 11)); g.setColor(Color.white); g.drawString(Base.VERSION_NAME, 50, 30); } }; window.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { window.dispose(); } }); int w = image.getWidth(activeEditor); int h = image.getHeight(activeEditor); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screen.width-w)/2, (screen.height-h)/2, w, h); window.setVisible(true); } /** * Show the Preferences window. */ public void handlePrefs() { if (preferencesFrame == null) preferencesFrame = new Preferences(); preferencesFrame.showFrame(activeEditor); } /** * Get list of platform constants. */ // static public int[] getPlatforms() { // return platforms; // static public int getPlatform() { // String osname = System.getProperty("os.name"); // if (osname.indexOf("Mac") != -1) { // return PConstants.MACOSX; // } else if (osname.indexOf("Windows") != -1) { // return PConstants.WINDOWS; // } else if (osname.equals("Linux")) { // true for the ibm vm // return PConstants.LINUX; // } else { // return PConstants.OTHER; static public Platform getPlatform() { return platform; } static public String getPlatformName() { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { return "macosx"; } else if (osname.indexOf("Windows") != -1) { return "windows"; } else if (osname.equals("Linux")) { // true for the ibm vm return "linux"; } else { return "other"; } } /** * Map a platform constant to its name. * @param which PConstants.WINDOWS, PConstants.MACOSX, PConstants.LINUX * @return one of "windows", "macosx", or "linux" */ static public String getPlatformName(int which) { return platformNames.get(which); } static public int getPlatformIndex(String what) { Integer entry = platformIndices.get(what); return (entry == null) ? -1 : entry.intValue(); } // These were changed to no longer rely on PApplet and PConstants because // of conflicts that could happen with older versions of core.jar, where // the MACOSX constant would instead read as the LINUX constant. /** * returns true if Processing is running on a Mac OS X machine. */ static public boolean isMacOS() { //return PApplet.platform == PConstants.MACOSX; return System.getProperty("os.name").indexOf("Mac") != -1; } /** * returns true if running on windows. */ static public boolean isWindows() { //return PApplet.platform == PConstants.WINDOWS; return System.getProperty("os.name").indexOf("Windows") != -1; } /** * true if running on linux. */ static public boolean isLinux() { //return PApplet.platform == PConstants.LINUX; return System.getProperty("os.name").indexOf("Linux") != -1; } static public File getSettingsFolder() { if (portableFolder != null) return portableFolder; File settingsFolder = null; String preferencesPath = Preferences.get("settings.path"); if (preferencesPath != null) { settingsFolder = new File(preferencesPath); } else { try { settingsFolder = platform.getSettingsFolder(); } catch (Exception e) { showError(_("Problem getting data folder"), _("Error getting the Arduino data folder."), e); } } // create the folder if it doesn't exist already if (!settingsFolder.exists()) { if (!settingsFolder.mkdirs()) { showError(_("Settings issues"), _("Arduino cannot run because it could not\n" + "create a folder to store your settings."), null); } } return settingsFolder; } /** * Convenience method to get a File object for the specified filename inside * the settings folder. * For now, only used by Preferences to get the preferences.txt file. * @param filename A file inside the settings folder. * @return filename wrapped as a File object inside the settings folder */ static public File getSettingsFile(String filename) { return new File(getSettingsFolder(), filename); } static public File getBuildFolder() { if (buildFolder == null) { String buildPath = Preferences.get("build.path"); if (buildPath != null) { buildFolder = new File(buildPath); } else { //File folder = new File(getTempFolder(), "build"); //if (!folder.exists()) folder.mkdirs(); buildFolder = createTempFolder("build"); buildFolder.deleteOnExit(); } } return buildFolder; } /** * Get the path to the platform's temporary folder, by creating * a temporary temporary file and getting its parent folder. * <br/> * Modified for revision 0094 to actually make the folder randomized * to avoid conflicts in multi-user environments. (Bug 177) */ static public File createTempFolder(String name) { try { File folder = File.createTempFile(name, null); //String tempPath = ignored.getParent(); //return new File(tempPath); folder.delete(); folder.mkdirs(); return folder; } catch (Exception e) { e.printStackTrace(); } return null; } static public LibraryList getLibraries() { return libraries; } static public String getExamplesPath() { return examplesFolder.getAbsolutePath(); } static public List<File> getLibrariesPath() { return librariesFolders; } static public File getToolsFolder() { return toolsFolder; } static public String getToolsPath() { return toolsFolder.getAbsolutePath(); } static public File getHardwareFolder() { // calculate on the fly because it's needed by Preferences.init() to find // the boards.txt and programmers.txt preferences files (which happens // before the other folders / paths get cached). return getContentFile("hardware"); } //Get the core libraries static public File getCoreLibraries(String path) { return getContentFile(path); } static public String getHardwarePath() { return getHardwareFolder().getAbsolutePath(); } static public String getAvrBasePath() { String path = getHardwarePath() + File.separator + "tools" + File.separator + "avr" + File.separator + "bin" + File.separator; if (Base.isLinux() && !(new File(path)).exists()) { return ""; // use distribution provided avr tools if bundled tools missing } return path; } /** * Returns a specific TargetPackage * * @param packageName * @return */ static public TargetPackage getTargetPackage(String packageName) { return packages.get(packageName); } /** * Returns the currently selected TargetPlatform. * * @return */ static public TargetPlatform getTargetPlatform() { String packageName = Preferences.get("target_package"); String platformName = Preferences.get("target_platform"); return getTargetPlatform(packageName, platformName); } /** * Returns a specific TargetPlatform searching Package/Platform * * @param packageName * @param platformName * @return */ static public TargetPlatform getTargetPlatform(String packageName, String platformName) { TargetPackage p = packages.get(packageName); if (p == null) return null; return p.get(platformName); } static public TargetPlatform getCurrentTargetPlatformFromPackage(String pack) { return getTargetPlatform(pack, Preferences.get("target_platform")); } static public PreferencesMap getBoardPreferences() { TargetBoard board = getTargetBoard(); PreferencesMap prefs = new PreferencesMap(board.getPreferences()); for (String menuId : board.getMenuIds()) { String entry = Preferences.get("custom_" + menuId); if (board.hasMenu(menuId) && entry != null && entry.startsWith(board.getId())) { String selectionId = entry.substring(entry.indexOf("_") + 1); prefs.putAll(board.getMenuPreferences(menuId, selectionId)); prefs.put("name", prefs.get("name") + ", " + board.getMenuLabel(menuId, selectionId)); } } return prefs; } public static TargetBoard getTargetBoard() { String boardId = Preferences.get("board"); return getTargetPlatform().getBoard(boardId); } static public File getPortableFolder() { return portableFolder; } static public String getPortableSketchbookFolder() { return portableSketchbookFolder; } static public File getSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, Preferences.get("sketchbook.path")); return new File(Preferences.get("sketchbook.path")); } static public File getSketchbookLibrariesFolder() { File libdir = new File(getSketchbookFolder(), "libraries"); if (!libdir.exists()) { try { libdir.mkdirs(); File readme = new File(libdir, "readme.txt"); FileWriter freadme = new FileWriter(readme); freadme.write(_("For information on installing libraries, see: " + "http://arduino.cc/en/Guide/Libraries\n")); freadme.close(); } catch (Exception e) { } } return libdir; } static public String getSketchbookLibrariesPath() { return getSketchbookLibrariesFolder().getAbsolutePath(); } static public File getSketchbookHardwareFolder() { return new File(getSketchbookFolder(), "hardware"); } protected File getDefaultSketchbookFolder() { if (portableFolder != null) return new File(portableFolder, portableSketchbookFolder); File sketchbookFolder = null; try { sketchbookFolder = platform.getDefaultSketchbookFolder(); } catch (Exception e) { } if (sketchbookFolder == null) { sketchbookFolder = promptSketchbookLocation(); } // create the folder if it doesn't exist already boolean result = true; if (!sketchbookFolder.exists()) { result = sketchbookFolder.mkdirs(); } if (!result) { showError(_("You forgot your sketchbook"), _("Arduino cannot run because it could not\n" + "create a folder to store your sketchbook."), null); } return sketchbookFolder; } /** * Check for a new sketchbook location. */ static protected File promptSketchbookLocation() { File folder = null; folder = new File(System.getProperty("user.home"), "sketchbook"); if (!folder.exists()) { folder.mkdirs(); return folder; } String prompt = _("Select (or create new) folder for sketches..."); folder = Base.selectFolder(prompt, null, null); if (folder == null) { System.exit(0); } return folder; } /** * Implements the cross-platform headache of opening URLs * TODO This code should be replaced by PApplet.link(), * however that's not a static method (because it requires * an AppletContext when used as an applet), so it's mildly * trickier than just removing this method. */ static public void openURL(String url) { try { platform.openURL(url); } catch (Exception e) { showWarning(_("Problem Opening URL"), I18n.format(_("Could not open the URL\n{0}"), url), e); } } /** * Used to determine whether to disable the "Show Sketch Folder" option. * @return true If a means of opening a folder is known to be available. */ static protected boolean openFolderAvailable() { return platform.openFolderAvailable(); } /** * Implements the other cross-platform headache of opening * a folder in the machine's native file browser. */ static public void openFolder(File file) { try { platform.openFolder(file); } catch (Exception e) { showWarning(_("Problem Opening Folder"), I18n.format(_("Could not open the folder\n{0}"), file.getAbsolutePath()), e); } } static public File selectFolder(String prompt, File folder, Frame frame) { JFileChooser fc = new JFileChooser(); fc.setDialogTitle(prompt); if (folder != null) { fc.setSelectedFile(folder); } fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returned = fc.showOpenDialog(new JDialog()); if (returned == JFileChooser.APPROVE_OPTION) { return fc.getSelectedFile(); } return null; } /** * Give this Frame a Processing icon. */ static public void setIcon(Frame frame) { // don't use the low-res icon on Mac OS X; the window should // already have the right icon from the .app file. if (Base.isMacOS()) return; Image image = Toolkit.getDefaultToolkit().createImage(PApplet.ICON_IMAGE); frame.setIconImage(image); } // someone needs to be slapped //static KeyStroke closeWindowKeyStroke; /** * Return true if the key event was a Ctrl-W or an ESC, * both indicators to close the window. * Use as part of a keyPressed() event handler for frames. */ /* static public boolean isCloseWindowEvent(KeyEvent e) { if (closeWindowKeyStroke == null) { int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); closeWindowKeyStroke = KeyStroke.getKeyStroke('W', modifiers); } return ((e.getKeyCode() == KeyEvent.VK_ESCAPE) || KeyStroke.getKeyStrokeForEvent(e).equals(closeWindowKeyStroke)); } */ /** * Registers key events for a Ctrl-W and ESC with an ActionListener * that will take care of disposing the window. */ static public void registerWindowCloseKeys(JRootPane root, ActionListener disposer) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); stroke = KeyStroke.getKeyStroke('W', modifiers); root.registerKeyboardAction(disposer, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); } static public void showReference(String filename) { File referenceFolder = Base.getContentFile("reference"); File referenceFile = new File(referenceFolder, filename); openURL(referenceFile.getAbsolutePath()); } static public void showGettingStarted() { if (Base.isMacOS()) { Base.showReference(_("Guide_MacOSX.html")); } else if (Base.isWindows()) { Base.showReference(_("Guide_Windows.html")); } else { Base.openURL(_("http: } } static public void showReference() { showReference(_("index.html")); } static public void showEnvironment() { showReference(_("Guide_Environment.html")); } static public void showPlatforms() { showReference(_("environment") + File.separator + _("platforms.html")); } static public void showTroubleshooting() { showReference(_("Guide_Troubleshooting.html")); } static public void showFAQ() { showReference(_("FAQ.html")); } /** * "No cookie for you" type messages. Nothing fatal or all that * much of a bummer, but something to notify the user about. */ static public void showMessage(String title, String message) { if (title == null) title = _("Message"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.INFORMATION_MESSAGE); } } /** * Non-fatal error message with optional stack trace side dish. */ static public void showWarning(String title, String message, Exception e) { if (title == null) title = _("Warning"); if (commandLine) { System.out.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.WARNING_MESSAGE); } if (e != null) e.printStackTrace(); } static public void showError(String title, String message, Throwable e) { showError(title, message, e, 1); } static public void showError(String title, String message, int exit_code) { showError(title, message, null, exit_code); } /** * Show an error message that's actually fatal to the program. * This is an error that can't be recovered. Use showWarning() * for errors that allow P5 to continue running. */ static public void showError(String title, String message, Throwable e, int exit_code) { if (title == null) title = _("Error"); if (commandLine) { System.err.println(title + ": " + message); } else { JOptionPane.showMessageDialog(new Frame(), message, title, JOptionPane.ERROR_MESSAGE); } if (e != null) e.printStackTrace(); System.exit(exit_code); } // incomplete static public int showYesNoCancelQuestion(Editor editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(null, primary + "\n" + secondary, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); return result; // if (result == JOptionPane.YES_OPTION) { // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // } else { } else { // Pane formatting adapted from the Quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost.", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Save", "Cancel", "Don't Save" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.CANCEL_OPTION; } else if (result == options[2]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } //if (result == JOptionPane.YES_OPTION) { // } else if (result == JOptionPane.NO_OPTION) { // return true; // ok to continue // } else if (result == JOptionPane.CANCEL_OPTION) { // return false; // } else { static public int showYesNoQuestion(Frame editor, String title, String primary, String secondary) { if (!Base.isMacOS()) { return JOptionPane.showConfirmDialog(editor, "<html><body>" + "<b>" + primary + "</b>" + "<br>" + secondary, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } else { // Pane formatting adapted from the Quaqua guide JOptionPane pane = new JOptionPane("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>" + primary + "</b>" + "<p>" + secondary + "</p>", JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { "Yes", "No" }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); JDialog dialog = pane.createDialog(editor, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { return JOptionPane.YES_OPTION; } else if (result == options[1]) { return JOptionPane.NO_OPTION; } else { return JOptionPane.CLOSED_OPTION; } } } /** * Retrieve a path to something in the Processing folder. Eventually this * may refer to the Contents subfolder of Processing.app, if we bundle things * up as a single .app file with no additional folders. */ // static public String getContentsPath(String filename) { // String basePath = System.getProperty("user.dir"); // /* // // do this later, when moving to .app package // if (PApplet.platform == PConstants.MACOSX) { // basePath = System.getProperty("processing.contents"); // } // */ // return basePath + File.separator + filename; /** * Get a path for something in the Processing lib folder. */ /* static public String getLibContentsPath(String filename) { String libPath = getContentsPath("lib/" + filename); File libDir = new File(libPath); if (libDir.exists()) { return libPath; } // was looking into making this run from Eclipse, but still too much mess // libPath = getContents("build/shared/lib/" + what); // libDir = new File(libPath); // if (libDir.exists()) { // return libPath; // } return null; } */ static public File getContentFile(String name) { String path = System.getProperty("user.dir"); // Get a path to somewhere inside the .app folder if (Base.isMacOS()) { // <key>javaroot</key> // <string>$JAVAROOT</string> String javaroot = System.getProperty("javaroot"); if (javaroot != null) { path = javaroot; } } File working = new File(path); return new File(working, name); } /** * Get an image associated with the current color theme. */ static public Image getThemeImage(String name, Component who) { return getLibImage("theme/" + name, who); } /** * Return an Image object from inside the Processing lib folder. */ static public Image getLibImage(String name, Component who) { Image image = null; Toolkit tk = Toolkit.getDefaultToolkit(); File imageLocation = new File(getContentFile("lib"), name); image = tk.getImage(imageLocation.getAbsolutePath()); MediaTracker tracker = new MediaTracker(who); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } return image; } /** * Return an InputStream for a file inside the Processing lib folder. */ static public InputStream getLibStream(String filename) throws IOException { return new FileInputStream(new File(getContentFile("lib"), filename)); } /** * Get the number of lines in a file by counting the number of newline * characters inside a String (and adding 1). */ static public int countLines(String what) { int count = 1; for (char c : what.toCharArray()) { if (c == '\n') count++; } return count; } /** * Same as PApplet.loadBytes(), however never does gzip decoding. */ static public byte[] loadBytesRaw(File file) throws IOException { int size = (int) file.length(); FileInputStream input = new FileInputStream(file); byte buffer[] = new byte[size]; int offset = 0; int bytesRead; while ((bytesRead = input.read(buffer, offset, size-offset)) != -1) { offset += bytesRead; if (bytesRead == 0) break; } input.close(); // weren't properly being closed input = null; return buffer; } /** * Read from a file with a bunch of attribute/value pairs * that are separated by = and ignore comments with #. */ static public HashMap<String,String> readSettings(File inputFile) { HashMap<String,String> outgoing = new HashMap<String,String>(); if (!inputFile.exists()) return outgoing; // return empty hash String lines[] = PApplet.loadStrings(inputFile); for (int i = 0; i < lines.length; i++) { int hash = lines[i].indexOf(' String line = (hash == -1) ? lines[i].trim() : lines[i].substring(0, hash).trim(); if (line.length() == 0) continue; int equals = line.indexOf('='); if (equals == -1) { System.err.println("ignoring illegal line in " + inputFile); System.err.println(" " + line); continue; } String attr = line.substring(0, equals).trim(); String valu = line.substring(equals + 1).trim(); outgoing.put(attr, valu); } return outgoing; } static public void copyFile(File sourceFile, File targetFile) throws IOException { InputStream from = new BufferedInputStream(new FileInputStream(sourceFile)); OutputStream to = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[16 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) { to.write(buffer, 0, bytesRead); } to.flush(); from.close(); from = null; to.close(); to = null; targetFile.setLastModified(sourceFile.lastModified()); } /** * Grab the contents of a file as a string. */ static public String loadFile(File file) throws IOException { String[] contents = PApplet.loadStrings(file); if (contents == null) return null; return PApplet.join(contents, "\n"); } /** * Spew the contents of a String object out to a file. */ static public void saveFile(String str, File file) throws IOException { File temp = File.createTempFile(file.getName(), null, file.getParentFile()); PApplet.saveStrings(temp, new String[] { str }); if (file.exists()) { boolean result = file.delete(); if (!result) { throw new IOException( I18n.format( _("Could not remove old version of {0}"), file.getAbsolutePath() ) ); } } boolean result = temp.renameTo(file); if (!result) { throw new IOException( I18n.format( _("Could not replace {0}"), file.getAbsolutePath() ) ); } } /** * Copy a folder from one place to another. This ignores all dot files and * folders found in the source directory, to avoid copying silly .DS_Store * files and potentially troublesome .svn folders. */ static public void copyDir(File sourceDir, File targetDir) throws IOException { targetDir.mkdirs(); String files[] = sourceDir.list(); for (int i = 0; i < files.length; i++) { // Ignore dot files (.DS_Store), dot folders (.svn) while copying if (files[i].charAt(0) == '.') continue; //if (files[i].equals(".") || files[i].equals("..")) continue; File source = new File(sourceDir, files[i]); File target = new File(targetDir, files[i]); if (source.isDirectory()) { //target.mkdirs(); copyDir(source, target); target.setLastModified(source.lastModified()); } else { copyFile(source, target); } } } /** * Remove all files in a directory and the directory itself. */ static public void removeDir(File dir) { if (dir.exists()) { removeDescendants(dir); if (!dir.delete()) { System.err.println(I18n.format(_("Could not delete {0}"), dir)); } } } /** * Recursively remove all files within a directory, * used with removeDir(), or when the contents of a dir * should be removed, but not the directory itself. * (i.e. when cleaning temp files from lib/build) */ static public void removeDescendants(File dir) { if (!dir.exists()) return; String files[] = dir.list(); for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || files[i].equals("..")) continue; File dead = new File(dir, files[i]); if (!dead.isDirectory()) { if (!Preferences.getBoolean("compiler.save_build_files")) { if (!dead.delete()) { // temporarily disabled System.err.println(I18n.format(_("Could not delete {0}"), dead)); } } } else { removeDir(dead); //dead.delete(); } } } /** * Calculate the size of the contents of a folder. * Used to determine whether sketches are empty or not. * Note that the function calls itself recursively. */ static public int calcFolderSize(File folder) { int size = 0; String files[] = folder.list(); // null if folder doesn't exist, happens when deleting sketch if (files == null) return -1; for (int i = 0; i < files.length; i++) { if (files[i].equals(".") || (files[i].equals("..")) || files[i].equals(".DS_Store")) continue; File fella = new File(folder, files[i]); if (fella.isDirectory()) { size += calcFolderSize(fella); } else { size += (int) fella.length(); } } return size; } /** * Recursively creates a list of all files within the specified folder, * and returns a list of their relative paths. * Ignores any files/folders prefixed with a dot. */ static public String[] listFiles(String path, boolean relative) { return listFiles(new File(path), relative); } static public String[] listFiles(File folder, boolean relative) { String path = folder.getAbsolutePath(); Vector<String> vector = new Vector<String>(); listFiles(relative ? (path + File.separator) : "", path, vector); String outgoing[] = new String[vector.size()]; vector.copyInto(outgoing); return outgoing; } static protected void listFiles(String basePath, String path, Vector<String> vector) { File folder = new File(path); String list[] = folder.list(); if (list == null) return; for (int i = 0; i < list.length; i++) { if (list[i].charAt(0) == '.') continue; File file = new File(path, list[i]); String newPath = file.getAbsolutePath(); if (newPath.startsWith(basePath)) { newPath = newPath.substring(basePath.length()); } vector.add(newPath); if (file.isDirectory()) { listFiles(basePath, newPath, vector); } } } public void handleAddLibrary() { JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home")); fileChooser.setDialogTitle(_("Select a zip file or a folder containing the library you'd like to add")); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); fileChooser.setFileFilter(new FileNameExtensionFilter(_("ZIP files or folders"), "zip")); Dimension preferredSize = fileChooser.getPreferredSize(); fileChooser.setPreferredSize(new Dimension(preferredSize.width + 200, preferredSize.height + 200)); int returnVal = fileChooser.showOpenDialog(activeEditor); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File sourceFile = fileChooser.getSelectedFile(); File tmpFolder = null; try { // unpack ZIP if (!sourceFile.isDirectory()) { try { tmpFolder = FileUtils.createTempFolder(); ZipDeflater zipDeflater = new ZipDeflater(sourceFile, tmpFolder); zipDeflater.deflate(); File[] foldersInTmpFolder = tmpFolder.listFiles(new OnlyDirs()); if (foldersInTmpFolder.length != 1) { throw new IOException(_("Zip doesn't contain a library")); } sourceFile = foldersInTmpFolder[0]; } catch (IOException e) { activeEditor.statusError(e); return; } } // is there a valid library? File libFolder = sourceFile; String libName = libFolder.getName(); if (!Sketch.isSanitaryName(libName)) { String mess = I18n.format(_("The library \"{0}\" cannot be used.\n" + "Library names must contain only basic letters and numbers.\n" + "(ASCII only and no spaces, and it cannot start with a number)"), libName); activeEditor.statusError(mess); return; } // copy folder File destinationFolder = new File(getSketchbookLibrariesFolder(), sourceFile.getName()); if (!destinationFolder.mkdir()) { activeEditor.statusError(I18n.format(_("A library named {0} already exists"), sourceFile.getName())); return; } try { FileUtils.copy(sourceFile, destinationFolder); } catch (IOException e) { activeEditor.statusError(e); return; } activeEditor.statusNotice(_("Library added to your libraries. Check \"Import library\" menu")); } finally { // delete zip created temp folder, if exists FileUtils.recursiveDelete(tmpFolder); } } public static DiscoveryManager getDiscoveryManager() { return discoveryManager; } }
package crazypants.enderio.machine.power; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.network.packet.Packet; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import thermalexpansion.api.item.IChargeableItem; import buildcraft.api.power.PowerHandler; import buildcraft.api.power.PowerHandler.PowerReceiver; import buildcraft.api.power.PowerHandler.Type; import cofh.api.energy.IEnergyContainerItem; import crazypants.enderio.ModObject; import crazypants.enderio.PacketHandler; import crazypants.enderio.conduit.ConnectionMode; import crazypants.enderio.conduit.IConduitBundle; import crazypants.enderio.conduit.power.IPowerConduit; import crazypants.enderio.machine.RedstoneControlMode; import crazypants.enderio.power.BasicCapacitor; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.enderio.power.IPowerInterface; import crazypants.enderio.power.PowerHandlerUtil; import crazypants.util.BlockCoord; import crazypants.util.Util; import crazypants.vecmath.VecmathUtil; public class TileCapacitorBank extends TileEntity implements IInternalPowerReceptor, IInventory { static enum FaceConnectionMode { INPUT, OUTPUT, LOCKED, NONE } static final BasicCapacitor BASE_CAP = new BasicCapacitor(100, 500000); BlockCoord[] multiblock = null; private PowerHandler powerHandler; private PowerHandler disabledPowerHandler; private float lastSyncPowerStored; private float storedEnergy; private int maxStoredEnergy; private int maxIO; private int maxInput; private int maxOutput; private boolean multiblockDirty = false; private RedstoneControlMode inputControlMode; private RedstoneControlMode outputControlMode; private boolean outputEnabled; private boolean inputEnabled; private boolean isRecievingRedstoneSignal; private boolean redstoneStateDirty = true; private List<Receptor> masterReceptors; private ListIterator<Receptor> receptorIterator; private List<Receptor> localReceptors; private boolean receptorsDirty = true; private final ItemStack[] inventory; private List<GaugeBounds> gaugeBounds; private Map<ForgeDirection, FaceConnectionMode> faceModes; private boolean render = false; private boolean masterReceptorsDirty; public TileCapacitorBank() { inventory = new ItemStack[4]; storedEnergy = 0; inputControlMode = RedstoneControlMode.IGNORE; outputControlMode = RedstoneControlMode.IGNORE; maxStoredEnergy = BASE_CAP.getMaxEnergyStored(); maxIO = BASE_CAP.getMaxEnergyExtracted(); maxInput = maxIO; maxOutput = maxIO; updatePowerHandler(); } public FaceConnectionMode toggleModeForFace(ForgeDirection faceHit) { Object rec = getReceptorForFace(faceHit); FaceConnectionMode curMode = getFaceModeForFace(faceHit); if(curMode == FaceConnectionMode.INPUT) { setFaceMode(faceHit, FaceConnectionMode.OUTPUT, true); return FaceConnectionMode.OUTPUT; } if(curMode == FaceConnectionMode.OUTPUT) { setFaceMode(faceHit, FaceConnectionMode.LOCKED, true); return FaceConnectionMode.LOCKED; } if(curMode == FaceConnectionMode.LOCKED) { if(rec == null || rec instanceof IInternalPowerReceptor) { setFaceMode(faceHit, FaceConnectionMode.NONE, true); return FaceConnectionMode.NONE; } } setFaceMode(faceHit, FaceConnectionMode.INPUT, true); return FaceConnectionMode.INPUT; } private void setFaceMode(ForgeDirection faceHit, FaceConnectionMode mode, boolean b) { if(mode == FaceConnectionMode.NONE && faceModes == null) { return; } if(faceModes == null) { faceModes = new EnumMap<ForgeDirection, TileCapacitorBank.FaceConnectionMode>(ForgeDirection.class); } faceModes.put(faceHit, mode); if(b) { receptorsDirty = true; getController().masterReceptorsDirty = true; } } private Object getReceptorForFace(ForgeDirection faceHit) { BlockCoord checkLoc = new BlockCoord(this).getLocation(faceHit); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); if(!(te instanceof TileCapacitorBank)) { return PowerHandlerUtil.create(te); } return null; } public FaceConnectionMode getFaceModeForFace(ForgeDirection face) { if(faceModes == null) { return FaceConnectionMode.NONE; } FaceConnectionMode res = faceModes.get(face); if(res == null) { return FaceConnectionMode.NONE; } return res; } @Override public void updateEntity() { if(worldObj == null) { // sanity check return; } if(worldObj.isRemote) { if(render) { worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord); render = false; } return; } // else is server, do all logic only on the server if(multiblockDirty) { formMultiblock(); multiblockDirty = false; } if(!isContoller()) { return; } ; boolean requiresClientSync = false; requiresClientSync = chargeItems(); boolean hasSignal = isRecievingRedstoneSignal(); if(inputControlMode == RedstoneControlMode.IGNORE) { inputEnabled = true; } else if(inputControlMode == RedstoneControlMode.NEVER) { inputEnabled = false; } else { inputEnabled = (inputControlMode == RedstoneControlMode.ON && hasSignal) || (inputControlMode == RedstoneControlMode.OFF && !hasSignal); } if(outputControlMode == RedstoneControlMode.IGNORE) { outputEnabled = true; } else if(outputControlMode == RedstoneControlMode.NEVER) { outputEnabled = false; } else { outputEnabled = (outputControlMode == RedstoneControlMode.ON && hasSignal) || (outputControlMode == RedstoneControlMode.OFF && !hasSignal); } if(outputEnabled) { transmitEnergy(); } //input any BC energy, yes, after output to avoid losing energy if we can if(powerHandler != null && powerHandler.getEnergyStored() > 0) { storedEnergy += powerHandler.getEnergyStored(); powerHandler.setEnergy(0); } requiresClientSync |= lastSyncPowerStored != storedEnergy && worldObj.getTotalWorldTime() % 10 == 0; if(requiresClientSync) { lastSyncPowerStored = storedEnergy; worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); onInventoryChanged(); } } public List<GaugeBounds> getGaugeBounds() { if(gaugeBounds == null) { gaugeBounds = GaugeBounds.calculateGaugeBounds(new BlockCoord(this), multiblock); } return gaugeBounds; } private boolean chargeItems() { boolean chargedItem = false; float available = Math.min(maxIO, storedEnergy); for (ItemStack item : inventory) { if(item != null && available > 0) { float used = 0; if(item.getItem() instanceof IEnergyContainerItem) { IEnergyContainerItem chargable = (IEnergyContainerItem) item.getItem(); float max = chargable.getMaxEnergyStored(item); float cur = chargable.getEnergyStored(item); float canUse = Math.min(available * 10, max - cur); if(cur < max) { used = chargable.receiveEnergy(item, (int) canUse, false) / 10; // TODO: I should be able to use 'used' but it is always returning 0 // ATM. used = (chargable.getEnergyStored(item) - cur) / 10; } } else if(item.getItem() instanceof IChargeableItem) { IChargeableItem chargable = (IChargeableItem) item.getItem(); float max = chargable.getMaxEnergyStored(item); float cur = chargable.getEnergyStored(item); float canUse = Math.min(available, max - cur); if(cur < max) { if(chargable.getClass().getName().startsWith("appeng") || "appeng.common.base.AppEngMultiChargeable".equals(chargable.getClass().getName())) { // 256 max limit canUse = Math.min(canUse, 256); NBTTagCompound tc = item.getTagCompound(); if(tc == null) { item.setTagCompound(tc = new NBTTagCompound()); } double newVal = (cur + canUse) * 5.0; tc.setDouble("powerLevel", newVal); used = canUse; } else { used = chargable.receiveEnergy(item, canUse, true); } } } if(used > 0) { storedEnergy = storedEnergy - used; chargedItem = true; available -= used; } } } return chargedItem; } public boolean isOutputEnabled() { return getController().outputEnabled; } public boolean isOutputEnabled(ForgeDirection direction) { FaceConnectionMode mode = getFaceModeForFace(direction); return mode == FaceConnectionMode.OUTPUT || mode == FaceConnectionMode.NONE && isOutputEnabled(); } public boolean isInputEnabled() { return getController().inputEnabled; } public boolean isInputEnabled(ForgeDirection direction) { FaceConnectionMode mode = getFaceModeForFace(direction); return mode == FaceConnectionMode.INPUT || mode == FaceConnectionMode.NONE && isInputEnabled(); } private boolean transmitEnergy() { if(storedEnergy <= 0) { return false; } float canTransmit = Math.min(storedEnergy, maxOutput); float transmitted = 0; updateMasterReceptors(); if(!masterReceptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = masterReceptors.listIterator(); } int appliedCount = 0; int numReceptors = masterReceptors.size(); while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { Receptor receptor = receptorIterator.next(); IPowerInterface powerInterface = receptor.receptor; FaceConnectionMode mode = receptor.mode; if(powerInterface != null && mode != FaceConnectionMode.INPUT && mode != FaceConnectionMode.LOCKED && powerInterface.getMinEnergyReceived(receptor.fromDir.getOpposite()) <= canTransmit) { float used; if(receptor.receptor.getDelegate() instanceof IConduitBundle) { //All other power transfer is handled by the conduit network IConduitBundle bundle = (IConduitBundle) receptor.receptor.getDelegate(); IPowerConduit conduit = bundle.getConduit(IPowerConduit.class); if(conduit != null && conduit.getConectionMode(receptor.fromDir.getOpposite()) == ConnectionMode.INPUT) { used = powerInterface.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); } else { used = 0; } } else { used = powerInterface.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); } transmitted += used; canTransmit -= used; } if(canTransmit <= 0) { break; } if(!masterReceptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = masterReceptors.listIterator(); } appliedCount++; } storedEnergy = storedEnergy - transmitted; return transmitted > 0; } private void updateMasterReceptors() { if(!masterReceptorsDirty && masterReceptors != null) { return; } if(masterReceptors == null) { masterReceptors = new ArrayList<Receptor>(); } masterReceptors.clear(); if(multiblock == null) { updateReceptors(); if(localReceptors != null) { masterReceptors.addAll(localReceptors); } } else { //TODO: Performance warning?? for (BlockCoord bc : multiblock) { TileEntity te = worldObj.getBlockTileEntity(bc.x, bc.y, bc.z); if(te instanceof TileCapacitorBank) { TileCapacitorBank cb = ((TileCapacitorBank) te); cb.updateReceptors(); if(cb.localReceptors != null) { masterReceptors.addAll(cb.localReceptors); } } } } receptorIterator = masterReceptors.listIterator(); masterReceptorsDirty = false; } private void updateReceptors() { if(!receptorsDirty) { return; } if(localReceptors != null) { localReceptors.clear(); } BlockCoord bc = new BlockCoord(this); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { FaceConnectionMode mode = getFaceModeForFace(dir); if(mode != FaceConnectionMode.LOCKED) { BlockCoord checkLoc = bc.getLocation(dir); TileEntity te = worldObj.getBlockTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); if(!(te instanceof TileCapacitorBank)) { IPowerInterface ph = PowerHandlerUtil.create(te); if(ph != null && ph.canConduitConnect(dir)) { if(localReceptors == null) { localReceptors = new ArrayList<Receptor>(); } Receptor r = new Receptor(ph, dir, mode); localReceptors.add(r); if(mode == FaceConnectionMode.NONE && !(ph.getDelegate() instanceof IInternalPowerReceptor)) { setFaceMode(dir, FaceConnectionMode.INPUT, false); worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); render = true; //worldObj.notifyBlocksOfNeighborChange(xCoord, yCoord, zCoord, ModObject.blockCapacitorBank.actualId); } } } } } receptorsDirty = false; } public int getEnergyStoredScaled(int scale) { return getController().doGetEnergyStoredScaled(scale); } public int getMaxInput() { return maxInput; } public void setMaxInput(int maxInput) { getController().doSetMaxInput(maxInput); } public int getMaxOutput() { return maxOutput; } public void setMaxOutput(int maxOutput) { getController().doSetMaxOutput(maxOutput); } public float getEnergyStored() { return getController().doGetEnergyStored(); } public float getEnergyStoredRatio() { return getController().doGetEnergyStoredRatio(); } public int getMaxEnergyStored() { return getController().doGetMaxEnergyStored(); } public int getMaxIO() { return getController().doGetMaxIO(); } @Override public PowerHandler getPowerHandler() { return getController().doGetPowerHandler(); } @Override public PowerReceiver getPowerReceiver(ForgeDirection side) { FaceConnectionMode mode = getFaceModeForFace(side); if(mode == FaceConnectionMode.LOCKED || mode == FaceConnectionMode.OUTPUT) { return getDisabledPowerHandler().getPowerReceiver(); } return getPowerHandler().getPowerReceiver(); } // RF Power @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { return 0; } @Override public boolean canInterface(ForgeDirection from) { return getFaceModeForFace(from) != FaceConnectionMode.LOCKED; } @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { FaceConnectionMode mode = getFaceModeForFace(from); if(mode == FaceConnectionMode.LOCKED || mode == FaceConnectionMode.OUTPUT) { return 0; } return getController().doReceiveEnergy(from, maxReceive, simulate); } @Override public int getEnergyStored(ForgeDirection from) { return getController().doGetEnergyStored(from); } @Override public int getMaxEnergyStored(ForgeDirection from) { return getController().doGetMaxEnergyStored(); } public int doReceiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { float freeSpace = maxStoredEnergy - storedEnergy; int result = (int) Math.min(maxReceive / 10, freeSpace); if(!simulate) { storedEnergy += result; } return result * 10; } public int doGetEnergyStored(ForgeDirection from) { return (int) (storedEnergy * 10); } public int doGetMaxEnergyStored(ForgeDirection from) { return maxStoredEnergy * 10; } // end rf power public void addEnergy(float add) { getController().doAddEnergy(add); } private boolean isRecievingRedstoneSignal() { if(!redstoneStateDirty) { return isRecievingRedstoneSignal; } isRecievingRedstoneSignal = false; redstoneStateDirty = false; if(!isMultiblock()) { isRecievingRedstoneSignal = worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord) > 0; } else { for (BlockCoord bc : multiblock) { if(worldObj.getStrongestIndirectPower(bc.x, bc.y, bc.z) > 0) { isRecievingRedstoneSignal = true; break; } } } return isRecievingRedstoneSignal; } public RedstoneControlMode getInputControlMode() { return inputControlMode; } public void setInputControlMode(RedstoneControlMode inputControlMode) { if(!isMultiblock()) { this.inputControlMode = inputControlMode; } else { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.inputControlMode = inputControlMode; } } } } public RedstoneControlMode getOutputControlMode() { return outputControlMode; } public void setOutputControlMode(RedstoneControlMode outputControlMode) { if(!isMultiblock()) { this.outputControlMode = outputControlMode; } else { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.outputControlMode = outputControlMode; } } } } int doGetMaxIO() { return maxIO; } int doGetMaxEnergyStored() { return maxStoredEnergy; } PowerHandler doGetPowerHandler() { if(inputEnabled) { if(powerHandler == null) { powerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(maxInput, maxInput, maxOutput), this, Type.STORAGE); } return powerHandler; } return getDisabledPowerHandler(); } private PowerHandler getDisabledPowerHandler() { if(disabledPowerHandler == null) { disabledPowerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(0, 0), this, Type.STORAGE); } return disabledPowerHandler; } int doGetEnergyStoredScaled(int scale) { // NB: called on the client so can't use the power provider return VecmathUtil.clamp(Math.round(scale * (storedEnergy / maxStoredEnergy)), 0, scale); } float doGetEnergyStored() { return storedEnergy; } float doGetEnergyStoredRatio() { return storedEnergy / maxStoredEnergy; } void doAddEnergy(float add) { storedEnergy = Math.min(maxStoredEnergy, storedEnergy + add); } void doSetMaxInput(int in) { maxInput = Math.min(in, maxIO); maxInput = Math.max(0, maxInput); if(isMultiblock()) { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.maxInput = maxInput; } } } updatePowerHandler(); } void doSetMaxOutput(int out) { maxOutput = Math.min(out, maxIO); maxOutput = Math.max(0, maxOutput); if(isMultiblock()) { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.maxOutput = maxOutput; } } } updatePowerHandler(); } @Override public void doWork(PowerHandler workProvider) { } @Override public World getWorld() { return worldObj; } @Override public void applyPerdition() { } private void updatePowerHandler() { //powerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(maxInput, maxStoredEnergy, maxOutput), this, Type.STORAGE); if(storedEnergy > maxStoredEnergy) { storedEnergy = maxStoredEnergy; } powerHandler = null; } public void onBlockAdded() { multiblockDirty = true; } public void onNeighborBlockChange(int blockId) { if(blockId != ModObject.blockCapacitorBank.actualId) { receptorsDirty = true; getController().masterReceptorsDirty = true; } redstoneStateDirty = true; } public void onBreakBlock() { TileCapacitorBank controller = getController(); controller.clearCurrentMultiblock(); } private void clearCurrentMultiblock() { if(multiblock == null) { return; } for (BlockCoord bc : multiblock) { TileCapacitorBank res = getCapBank(bc); if(res != null) { res.setMultiblock(null); } } multiblock = null; redstoneStateDirty = true; } private void formMultiblock() { List<TileCapacitorBank> blocks = new ArrayList<TileCapacitorBank>(); blocks.add(this); findNighbouringBanks(this, blocks); if(blocks.size() < 2) { return; } for (TileCapacitorBank cb : blocks) { cb.clearCurrentMultiblock(); } BlockCoord[] mb = new BlockCoord[blocks.size()]; for (int i = 0; i < blocks.size(); i++) { mb[i] = new BlockCoord(blocks.get(i)); } for (TileCapacitorBank cb : blocks) { cb.setMultiblock(mb); } } private void findNighbouringBanks(TileCapacitorBank tileCapacitorBank, List<TileCapacitorBank> blocks) { BlockCoord bc = new BlockCoord(tileCapacitorBank); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { TileCapacitorBank cb = getCapBank(bc.getLocation(dir)); if(cb != null && !blocks.contains(cb)) { blocks.add(cb); findNighbouringBanks(cb, blocks); } } } private void setMultiblock(BlockCoord[] mb) { if(multiblock != null && isMaster()) { // split up current multiblock and reconfigure all the internal capacitors float powerPerBlock = storedEnergy / multiblock.length; for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); if(cb != null) { cb.maxStoredEnergy = BASE_CAP.getMaxEnergyStored(); cb.maxIO = BASE_CAP.getMaxEnergyExtracted(); cb.maxInput = cb.maxIO; cb.maxOutput = cb.maxIO; cb.storedEnergy = powerPerBlock; cb.updatePowerHandler(); cb.multiblockDirty = true; } } } multiblock = mb; if(isMaster()) { List<ItemStack> invItems = new ArrayList<ItemStack>(); float totalStored = 0; int totalCap = multiblock.length * BASE_CAP.getMaxEnergyStored(); int totalIO = multiblock.length * BASE_CAP.getMaxEnergyExtracted(); for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); if(cb != null) { totalStored += cb.storedEnergy; } ItemStack[] inv = cb.inventory; for (int i = 0; i < inv.length; i++) { if(inv[i] != null) { invItems.add(inv[i]); inv[i] = null; } } cb.multiblockDirty = false; } storedEnergy = totalStored; maxStoredEnergy = totalCap; maxIO = totalIO; maxInput = maxIO; maxOutput = maxIO; for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); if(cb != null) { cb.maxIO = totalIO; cb.maxInput = maxIO; cb.maxOutput = maxIO; } } if(invItems.size() > inventory.length) { for (int i = inventory.length; i < invItems.size(); i++) { Util.dropItems(worldObj, invItems.get(i), xCoord, yCoord, zCoord, true); } } for (int i = 0; i < inventory.length && i < invItems.size(); i++) { inventory[i] = invItems.get(i); } updatePowerHandler(); } receptorsDirty = true; getController().masterReceptorsDirty = true; redstoneStateDirty = true; // Forces an update worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); //TODO: WTF? worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, isMultiblock() ? 1 : 0, 2); } TileCapacitorBank getController() { if(isMaster() || !isMultiblock()) { return this; } TileCapacitorBank res = getCapBank(multiblock[0]); return res != null ? res : this; } boolean isContoller() { return multiblock == null ? true : isMaster(); } boolean isMaster() { if(multiblock != null) { return multiblock[0].equals(xCoord, yCoord, zCoord); } return false; } public boolean isMultiblock() { return multiblock != null; } private boolean isCurrentMultiblockValid() { if(multiblock == null) { return false; } for (BlockCoord bc : multiblock) { TileCapacitorBank res = getCapBank(bc); if(res == null || !res.isMultiblock()) { return false; } } return true; } private TileCapacitorBank getCapBank(BlockCoord bc) { return getCapBank(bc.x, bc.y, bc.z); } private TileCapacitorBank getCapBank(int x, int y, int z) { if(worldObj == null) { return null; } TileEntity te = worldObj.getBlockTileEntity(x, y, z); if(te instanceof TileCapacitorBank) { return (TileCapacitorBank) te; } return null; } @Override public int getSizeInventory() { return getController().doGetSizeInventory(); } @Override public ItemStack getStackInSlot(int i) { return getController().doGetStackInSlot(i); } @Override public ItemStack decrStackSize(int i, int j) { return getController().doDecrStackSize(i, j); } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { getController().doSetInventorySlotContents(i, itemstack); } public ItemStack doGetStackInSlot(int i) { if(i < 0 || i >= inventory.length) { return null; } return inventory[i]; } public int doGetSizeInventory() { return inventory.length; } public ItemStack doDecrStackSize(int fromSlot, int amount) { if(fromSlot < 0 || fromSlot >= inventory.length) { return null; } ItemStack item = inventory[fromSlot]; if(item == null) { return null; } if(item.stackSize <= amount) { ItemStack result = item.copy(); inventory[fromSlot] = null; return result; } item.stackSize -= amount; return item.copy(); } public void doSetInventorySlotContents(int i, ItemStack itemstack) { if(i < 0 || i >= inventory.length) { return; } inventory[i] = itemstack; } @Override public ItemStack getStackInSlotOnClosing(int i) { return null; } @Override public String getInvName() { return ModObject.blockCapacitorBank.name(); } @Override public boolean isInvNameLocalized() { return false; } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return true; } @Override public void openChest() { } @Override public void closeChest() { } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { if(itemstack == null) { return false; } return itemstack.getItem() instanceof IChargeableItem || itemstack.getItem() instanceof IEnergyContainerItem; } @Override public void readFromNBT(NBTTagCompound nbtRoot) { super.readFromNBT(nbtRoot); float oldEnergy = storedEnergy; storedEnergy = nbtRoot.getFloat("storedEnergy"); maxStoredEnergy = nbtRoot.getInteger("maxStoredEnergy"); float newEnergy = storedEnergy; if(maxStoredEnergy != 0 && Math.abs(oldEnergy - newEnergy) / maxStoredEnergy > 0.05 || nbtRoot.hasKey("render")) { render = true; } maxIO = nbtRoot.getInteger("maxIO"); if(nbtRoot.hasKey("maxInput")) { maxInput = nbtRoot.getInteger("maxInput"); maxOutput = nbtRoot.getInteger("maxOutput"); } else { maxInput = maxIO; maxOutput = maxIO; } inputControlMode = RedstoneControlMode.values()[nbtRoot.getShort("inputControlMode")]; outputControlMode = RedstoneControlMode.values()[nbtRoot.getShort("outputControlMode")]; updatePowerHandler(); boolean wasMulti = isMultiblock(); if(nbtRoot.getBoolean("isMultiblock")) { int[] coords = nbtRoot.getIntArray("multiblock"); multiblock = new BlockCoord[coords.length / 3]; int c = 0; for (int i = 0; i < multiblock.length; i++) { multiblock[i] = new BlockCoord(coords[c++], coords[c++], coords[c++]); } } else { multiblock = null; } for (int i = 0; i < inventory.length; i++) { inventory[i] = null; } NBTTagList itemList = nbtRoot.getTagList("Items"); for (int i = 0; i < itemList.tagCount(); i++) { NBTTagCompound itemStack = (NBTTagCompound) itemList.tagAt(i); byte slot = itemStack.getByte("Slot"); if(slot >= 0 && slot < inventory.length) { inventory[slot] = ItemStack.loadItemStackFromNBT(itemStack); } } if(nbtRoot.hasKey("hasFaces")) { for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { if(nbtRoot.hasKey("face" + dir.ordinal())) { setFaceMode(dir, FaceConnectionMode.values()[nbtRoot.getShort("face" + dir.ordinal())], false); } } } gaugeBounds = null; } @Override public void writeToNBT(NBTTagCompound nbtRoot) { super.writeToNBT(nbtRoot); nbtRoot.setFloat("storedEnergy", storedEnergy); nbtRoot.setInteger("maxStoredEnergy", maxStoredEnergy); nbtRoot.setInteger("maxIO", maxIO); nbtRoot.setInteger("maxInput", maxInput); nbtRoot.setInteger("maxOutput", maxOutput); nbtRoot.setShort("inputControlMode", (short) inputControlMode.ordinal()); nbtRoot.setShort("outputControlMode", (short) outputControlMode.ordinal()); nbtRoot.setBoolean("isMultiblock", isMultiblock()); if(isMultiblock()) { int[] vals = new int[multiblock.length * 3]; int i = 0; for (BlockCoord bc : multiblock) { vals[i++] = bc.x; vals[i++] = bc.y; vals[i++] = bc.z; } nbtRoot.setIntArray("multiblock", vals); } // write inventory list NBTTagList itemList = new NBTTagList(); for (int i = 0; i < inventory.length; i++) { if(inventory[i] != null) { NBTTagCompound itemStackNBT = new NBTTagCompound(); itemStackNBT.setByte("Slot", (byte) i); inventory[i].writeToNBT(itemStackNBT); itemList.appendTag(itemStackNBT); } } nbtRoot.setTag("Items", itemList); //face modes if(faceModes != null) { nbtRoot.setByte("hasFaces", (byte) 1); for (Entry<ForgeDirection, FaceConnectionMode> e : faceModes.entrySet()) { nbtRoot.setShort("face" + e.getKey().ordinal(), (short) e.getValue().ordinal()); } } if(render) { nbtRoot.setBoolean("render", true); render = false; } } @Override public Packet getDescriptionPacket() { return PacketHandler.getPacket(this); } static class Receptor { IPowerInterface receptor; ForgeDirection fromDir; FaceConnectionMode mode; private Receptor(IPowerInterface rec, ForgeDirection fromDir, FaceConnectionMode mode) { this.receptor = rec; this.fromDir = fromDir; this.mode = mode; } @Override public String toString() { return "Receptor [receptor=" + receptor + ", fromDir=" + fromDir + ", mode=" + mode + "]"; } } }
package com.wonderpush.sdk; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Intent; import android.os.Bundle; import android.util.Log; abstract class NotificationModel { private static final String TAG = WonderPush.TAG; static class NotTargetedForThisInstallationException extends Exception { private static final long serialVersionUID = -1642569383307930845L; public NotTargetedForThisInstallationException(String detailMessage) { super(detailMessage); } } interface Builder { NotificationModel build(String inputJSONString); } enum Type { SIMPLE("simple", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationSimpleModel(inputJSONString); } }), DATA("data", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationDataModel(inputJSONString); } }), TEXT("text", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationTextModel(inputJSONString); } }), HTML("html", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationHtmlModel(inputJSONString); } }), MAP("map", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationMapModel(inputJSONString); } }), URL("url", new Builder() { @Override public NotificationModel build(String inputJSONString) { return new NotificationUrlModel(inputJSONString); } }), ; private final String type; private final Builder builder; Type(String type, Builder builder) { this.type = type; this.builder = builder; } @Override public String toString() { return type; } public Builder getBuilder() { return builder; } public static Type fromString(String type) { if (type == null) { throw new NullPointerException(); } for (Type notificationType : Type.values()) { if (type.equals(notificationType.toString())) { return notificationType; } } throw new IllegalArgumentException("Constant \"" + type + "\" is not a known notification type"); } } private final String inputJSONString; private String targetedInstallation; private String campaignId; private String notificationId; private Type type; private AlertModel alert; private String targetUrl; public List<ActionModel> actions = new ArrayList<>(); // Common in-app message data private final AtomicReference<ButtonModel> choice = new AtomicReference<>(); private final List<ButtonModel> buttons = new ArrayList<>(3); private String title; public static NotificationModel fromGCMBroadcastIntent(Intent intent) throws NotTargetedForThisInstallationException { try { Bundle extras = intent.getExtras(); if (extras == null || extras.isEmpty()) { // has effect of unparcelling Bundle WonderPush.logDebug("Received broadcasted intent has no extra"); return null; } String wpDataJson = extras.getString(WonderPushGcmClient.WONDERPUSH_NOTIFICATION_EXTRA_KEY); if (wpDataJson == null) { WonderPush.logDebug("Received broadcasted intent has no data for WonderPush"); return null; } WonderPush.logDebug("Received broadcasted intent: " + intent); WonderPush.logDebug("Received broadcasted intent extras: " + extras.toString()); for (String key : extras.keySet()) { WonderPush.logDebug("Received broadcasted intent extras " + key + ": " + extras.get(key)); } try { JSONObject wpData = new JSONObject(wpDataJson); WonderPush.logDebug("Received broadcasted intent WonderPush data: " + wpDataJson); return fromGCMNotificationJSONObject(wpData, extras); } catch (JSONException e) { WonderPush.logDebug("data is not a well-formed JSON object", e); } } catch (Exception e) { Log.e(TAG, "Unexpected error while receiving a notification with intent " + intent, e); } return null; } public static NotificationModel fromLocalIntent(Intent intent) { if (WonderPush.containsExplicitNotification(intent)) { String notifString = intent.getData().getQueryParameter(WonderPush.INTENT_NOTIFICATION_QUERY_PARAMETER); if (notifString == null) { return null; } try { JSONObject notifParsed = new JSONObject(notifString); return NotificationModel.fromGCMNotificationJSONObject(notifParsed, null); } catch (JSONException e) { WonderPush.logDebug("data is not a well-formed JSON object", e); } catch (NotTargetedForThisInstallationException e) { WonderPush.logError("Notifications not targeted for this installation should have been filtered earlier", e); } } else if (WonderPush.containsWillOpenNotification(intent)) { try { Intent pushIntent = intent.getParcelableExtra(WonderPush.INTENT_NOTIFICATION_WILL_OPEN_EXTRA_RECEIVED_PUSH_NOTIFICATION); return fromGCMBroadcastIntent(pushIntent); } catch (NotTargetedForThisInstallationException e) { WonderPush.logError("Notifications not targeted for this installation should have been filtered earlier", e); } } return null; } public static NotificationModel fromGCMNotificationJSONObject(JSONObject wpData, Bundle extras) throws NotTargetedForThisInstallationException { try { // Get the notification type Type type; try { type = NotificationModel.Type.fromString(wpData.optString("type", null)); } catch (Exception ex) { WonderPush.logError("Failed to read notification type", ex); if (wpData.has("alert") || extras != null && extras.containsKey("alert")) { type = NotificationModel.Type.SIMPLE; } else { type = NotificationModel.Type.DATA; } WonderPush.logDebug("Inferred notification type: " + type); } if (type == null) { return null; } // Instantiate the appropriate non-abstract subclass NotificationModel rtn = type.getBuilder().build(wpData.toString()); // Read common fields rtn.setType(type); rtn.setTargetedInstallation(wpData.optString("@", null)); rtn.setCampaignId(wpData.optString("c", null)); rtn.setNotificationId(wpData.optString("n", null)); rtn.setTargetUrl(wpData.optString("targetUrl", null)); // Read notification content JSONObject wpAlert = wpData.optJSONObject("alert"); if (wpAlert != null) { rtn.setAlert(AlertModel.fromJSON(wpAlert)); } else if (extras != null) { rtn.setAlert(AlertModel.fromOldFormatStringExtra(extras.getString("alert"))); // <= v1.1.0.0 format } else { // We are probably parsing an opened notification and the extras was not given. // We are not interested in showing a notification anyway, the in-app message is what's important now. } // Read actions JSONArray actions = wpData.optJSONArray("actions"); int actionCount = actions != null ? actions.length() : 0; for (int i = 0 ; i < actionCount ; ++i) { JSONObject action = actions.optJSONObject(i); rtn.addAction(new ActionModel(action)); } // Read common in-app fields rtn.setTitle(wpData.optString("title", null)); JSONArray buttons = wpData.optJSONArray("buttons"); int buttonCount = buttons != null ? buttons.length() : 0; for (int i = 0 ; i < buttonCount ; ++i) { JSONObject wpButton = buttons.optJSONObject(i); if (wpButton == null) { continue; } rtn.addButton(new ButtonModel(wpButton)); } // Let the non-abstract subclass read the rest and return rtn.readFromJSONObject(wpData); return rtn; } catch (Exception e) { Log.e(TAG, "Unexpected error while parsing a notification with JSON input " + wpData.toString(), e); } return null; } protected abstract void readFromJSONObject(JSONObject wpData); public NotificationModel(String inputJSONString) { this.inputJSONString = inputJSONString; } public String getInputJSONString() { return inputJSONString; } public String getTargetedInstallation() { return targetedInstallation; } public void setTargetedInstallation(String targetedInstallation) { this.targetedInstallation = targetedInstallation; } public String getCampaignId() { return campaignId; } public void setCampaignId(String campaignId) { this.campaignId = campaignId; } public String getNotificationId() { return notificationId; } public void setNotificationId(String notificationId) { this.notificationId = notificationId; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public AlertModel getAlert() { return alert; } public void setAlert(AlertModel alert) { this.alert = alert; } public String getTargetUrl() { return targetUrl; } public void setTargetUrl(String targetUrl) { this.targetUrl = targetUrl; } public List<ActionModel> getActions() { return actions; } public void setActions(List<ActionModel> actions) { this.actions = actions; } public void addAction(ActionModel action) { if (action != null) { actions.add(action); } } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getButtonCount() { return buttons.size(); } public ButtonModel getButton(int index) { return buttons.get(index); } public void addButton(ButtonModel button) { if (button != null) { buttons.add(button); } } public AtomicReference<ButtonModel> getChosenButton() { return choice; } }
package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.ba.AnalysisContext; public class FindReturnRef extends BytecodeScanningDetector { boolean check = false; boolean thisOnTOS = false; boolean fieldOnTOS = false; boolean publicClass = false; boolean staticMethod = false; boolean dangerousToStoreIntoField = false; String nameOnStack; String classNameOnStack; String sigOnStack; int parameterCount; int r; int timesRead [] = new int[256]; boolean fieldIsStatic; private BugAccumulator bugAccumulator; //private LocalVariableTable variableNames; public FindReturnRef(BugReporter bugReporter) { this.bugAccumulator = new BugAccumulator(bugReporter); } @Override public void visit(JavaClass obj) { publicClass = obj.isPublic(); super.visit(obj); } @Override public void visitAfter(JavaClass obj) { bugAccumulator.reportAccumulatedBugs(); } @Override public void visit(Method obj) { check = publicClass && (obj.getAccessFlags() & (ACC_PUBLIC)) != 0; if (!check) return; dangerousToStoreIntoField = false; staticMethod = (obj.getAccessFlags() & (ACC_STATIC)) != 0; //variableNames = obj.getLocalVariableTable(); parameterCount = getNumberMethodArguments(); /* System.out.println(betterMethodName); for(int i = 0; i < parameterCount; i++) System.out.println("parameter " + i + ": " + obj.getArgumentTypes()[i]); */ if (!staticMethod) parameterCount++; for (int i = 0; i < parameterCount; i++) timesRead[i] = 0; thisOnTOS = false; fieldOnTOS = false; super.visit(obj); thisOnTOS = false; fieldOnTOS = false; } @Override public void visit(Code obj) { if (check) super.visit(obj); } @Override public void sawOpcode(int seen) { if (!check) return; if (staticMethod && dangerousToStoreIntoField && seen == PUTSTATIC && MutableStaticFields.mutableSignature(getSigConstantOperand())) { bugAccumulator.accumulateBug(new BugInstance(this, "EI_EXPOSE_STATIC_REP2", NORMAL_PRIORITY) .addClassAndMethod(this) .addReferencedField(this) .add(LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(),r,getPC(),getPC()-1)), this); } if (!staticMethod && dangerousToStoreIntoField && seen == PUTFIELD && MutableStaticFields.mutableSignature(getSigConstantOperand())) { bugAccumulator.accumulateBug(new BugInstance(this, "EI_EXPOSE_REP2", NORMAL_PRIORITY) .addClassAndMethod(this) .addReferencedField(this) .add(LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(),r,getPC(),getPC()-1)), this); } dangerousToStoreIntoField = false; int reg = -1; // this value should never be seen checkStore: { switch (seen) { case ALOAD_0: reg = 0; break; case ALOAD_1: reg = 1; break; case ALOAD_2: reg = 2; break; case ALOAD_3: reg = 3; break; case ALOAD: reg = getRegisterOperand(); break; default: break checkStore; } if (reg < parameterCount) timesRead[reg]++; } if (thisOnTOS && !staticMethod) { switch (seen) { case ALOAD_1: case ALOAD_2: case ALOAD_3: case ALOAD: if (reg < parameterCount) { r = reg; dangerousToStoreIntoField = true; // System.out.println("Found dangerous value from parameter " + reg); } default: } } else if (staticMethod) { switch (seen) { case ALOAD_0: case ALOAD_1: case ALOAD_2: case ALOAD_3: case ALOAD: if (reg < parameterCount) { //r = reg; dangerousToStoreIntoField = true; } default: } } if (seen == ALOAD_0 && !staticMethod) { thisOnTOS = true; fieldOnTOS = false; return; } if (thisOnTOS && seen == GETFIELD && getClassConstantOperand().equals(getClassName()) && !AnalysisContext.currentXFactory().isEmptyArrayField(getXFieldOperand())) { fieldOnTOS = true; thisOnTOS = false; nameOnStack = getNameConstantOperand(); classNameOnStack = getDottedClassConstantOperand(); sigOnStack = getSigConstantOperand(); fieldIsStatic = false; return; } if (seen == GETSTATIC && getClassConstantOperand().equals(getClassName()) && !AnalysisContext.currentXFactory().isEmptyArrayField(getXFieldOperand())){ fieldOnTOS = true; thisOnTOS = false; nameOnStack = getNameConstantOperand(); classNameOnStack = getDottedClassConstantOperand(); sigOnStack = getSigConstantOperand(); fieldIsStatic = true; return; } thisOnTOS = false; if (check && fieldOnTOS && seen == ARETURN /* && !sigOnStack.equals("Ljava/lang/String;") && sigOnStack.indexOf("Exception") == -1 && sigOnStack.indexOf("[") >= 0 */ && nameOnStack.indexOf("EMPTY") == -1 && MutableStaticFields.mutableSignature(sigOnStack) ) { bugAccumulator.accumulateBug(new BugInstance(this, staticMethod ? "MS_EXPOSE_REP" : "EI_EXPOSE_REP", NORMAL_PRIORITY) .addClassAndMethod(this) .addField(classNameOnStack, nameOnStack, sigOnStack, fieldIsStatic), this); } fieldOnTOS = false; thisOnTOS = false; } }
package at.ac.tuwien.inso.service; import at.ac.tuwien.inso.controller.lecturer.GradeAuthorizationDTO; import at.ac.tuwien.inso.entity.*; import org.springframework.security.access.prepost.*; import org.springframework.stereotype.*; import java.util.*; @Service public interface GradeService { @PreAuthorize("hasRole('LECTURER')") GradeAuthorizationDTO getDefaultGradeAuthorizationDTOForStudentAndCourse(Long studentId, Long courseId); @PreAuthorize("hasRole('LECTURER')") Grade saveNewGradeForStudentAndCourse(GradeAuthorizationDTO grade); @PreAuthorize("hasRole('LECTURER')") List<Grade> getGradesForCourseOfLoggedInLecturer(Long courseId); @PreAuthorize("hasRole('STUDENT')") List<Grade> getGradesForLoggedInStudent(); Grade getForValidation(String identifier); @PreAuthorize("isAuthenticated()") List<Grade> findAllOfStudent(Student student); @PreAuthorize("isAuthenticated()") List<Mark> getMarkOptions(); }
package br.com.dbsoft.comparator; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Date; import java.sql.Timestamp; import java.util.Comparator; import org.apache.log4j.Logger; import br.com.dbsoft.util.DBSIO; public class DBSComparator<DataModelClass> implements Comparator<DataModelClass>{ protected Logger wLogger = Logger.getLogger(this.getClass()); public enum ORDER{ ASCENDING, DESCENDING; } private String wFieldName; private ORDER wOrder; public DBSComparator(String pFieldName, ORDER pOrder) { wFieldName = pFieldName; wOrder = pOrder; } @Override public int compare(DataModelClass pDataModel1, DataModelClass pDataModel2) { try { Method xMethod1 = DBSIO.findDataModelMethod(pDataModel1.getClass(), "get" + wFieldName); Method xMethod2 = DBSIO.findDataModelMethod(pDataModel2.getClass(), "get" + wFieldName); Object xValue1 = xMethod1.invoke(pDataModel1); Object xValue2 = xMethod2.invoke(pDataModel2); if (xValue1 == null && xValue2 == null){ return 0; } if (xValue1 == null){ if (wOrder == ORDER.ASCENDING){ return -1; }else{ return 1; } }else if (xValue2 == null){ if (wOrder == ORDER.ASCENDING){ return 1; }else{ return -1; } } if (xValue1 instanceof Date){ if (wOrder == ORDER.ASCENDING){ return ((Date) xValue1).compareTo((Date) xValue2); }else{ return ((Date) xValue2).compareTo((Date) xValue1); } }else if (xValue1 instanceof Double){ if (wOrder == ORDER.ASCENDING){ return ((Double) xValue1).compareTo((Double) xValue2); }else{ return ((Double) xValue2).compareTo((Double) xValue1); } }else if (xValue1 instanceof Integer){ if (wOrder == ORDER.ASCENDING){ return ((Integer) xValue1).compareTo((Integer) xValue2); }else{ return ((Integer) xValue2).compareTo((Integer) xValue1); } }else if (xValue1 instanceof Long){ if (wOrder == ORDER.ASCENDING){ return ((Long) xValue1).compareTo((Long) xValue2); }else{ return ((Long) xValue2).compareTo((Long) xValue1); } }else if (xValue1 instanceof Double){ if (wOrder == ORDER.ASCENDING){ return ((String) xValue1).compareTo((String) xValue2); }else{ return ((String) xValue2).compareTo((String) xValue1); } }else if (xValue1 instanceof Timestamp){ if (wOrder == ORDER.ASCENDING){ return ((Timestamp) xValue1).compareTo((Timestamp) xValue2); }else{ return ((Timestamp) xValue2).compareTo((Timestamp) xValue1); } } } catch (SecurityException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return 0; } }
package com.cobalt.cdpipeline.servlet; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.StringWriter; import java.net.URI; import java.util.List; import java.util.Map; import com.google.common.collect.Maps; import com.atlassian.bamboo.plan.PlanManager; import com.atlassian.bamboo.project.ProjectManager; import com.atlassian.bamboo.resultsummary.ResultsSummaryManager; import com.atlassian.sal.api.auth.LoginUriProvider; import com.atlassian.sal.api.user.UserManager; import com.atlassian.templaterenderer.TemplateRenderer; import com.cobalt.cdpipeline.Controllers.MainManager; import com.cobalt.cdpipeline.cdresult.CDResult; public class MainPage extends HttpServlet{ private static final Logger log = LoggerFactory.getLogger(MainPage.class); private final UserManager userManager; private final LoginUriProvider loginUriProvider; private final TemplateRenderer renderer; private final MainManager mainManager; public MainPage(UserManager userManager, LoginUriProvider loginUriProvider, TemplateRenderer renderer, ProjectManager projectManager, PlanManager planManager, ResultsSummaryManager resultsSummaryManager) { this.userManager = userManager; this.loginUriProvider = loginUriProvider; this.renderer = renderer; this.mainManager = new MainManager(projectManager, planManager, resultsSummaryManager); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username = userManager.getRemoteUsername(request); if (username == null || !userManager.isSystemAdmin(username)) { redirectToLogin(request, response); return; } List<CDResult> resultList = mainManager.getCDResults(); Map<String, Object> context = Maps.newHashMap(); context.put("results", resultList); response.setContentType("text/html;charset=utf-8"); renderer.render("cdpipeline.vm", context, response.getWriter()); } private void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendRedirect(loginUriProvider.getLoginUri(getUri(request)).toASCIIString()); } private URI getUri(HttpServletRequest request) { StringBuffer builder = request.getRequestURL(); if (request.getQueryString() != null) { builder.append("?"); builder.append(request.getQueryString()); } return URI.create(builder.toString()); } }
package com.codeborne.selenide; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.io.FileWriter; import static org.apache.commons.io.FileUtils.copyFile; public class WebDriverRunner { static String browser = System.getProperty("browser", "firefox"); private static WebDriver webdriver; static { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { closeWebDriver(); } }); } public static WebDriver getWebDriver() { if (webdriver == null) { webdriver = createDriver(browser); } return webdriver; } public static void closeWebDriver() { if (webdriver != null) { webdriver.close(); webdriver = null; } } public static boolean ie() { return webdriver != null && webdriver instanceof InternetExplorerDriver; } public static void clearBrowserCache() { if (webdriver != null) { webdriver.manage().deleteAllCookies(); } } public static String takeScreenShot(String fileName) { if (webdriver == null) { return null; } else if (webdriver instanceof TakesScreenshot) { try { File scrFile = ((TakesScreenshot) webdriver).getScreenshotAs(OutputType.FILE); String pageSource = webdriver.getPageSource(); String screenshotFileName = "build/reports/tests/" + fileName + ".png"; String htmlFileName = "build/reports/tests/" + fileName + ".html"; copyFile(scrFile, new File(screenshotFileName)); IOUtils.write(pageSource, new FileWriter(htmlFileName)); return screenshotFileName; } catch (Exception e) { System.err.println(e); } } else { System.err.println("Cannot take screenshot, driver does not support it: " + webdriver); } return null; } private static WebDriver createDriver(String browser) { if ("chrome".equalsIgnoreCase(browser)) { ChromeOptions options = new ChromeOptions(); options.addArguments("chrome.switches", "--start-maximized"); return new ChromeDriver(options); } else if ("ie".equalsIgnoreCase(browser)) { DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer(); ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); return new InternetExplorerDriver(ieCapabilities); } else if ("htmlunit".equalsIgnoreCase(browser)) { DesiredCapabilities desiredCapabilities = DesiredCapabilities.htmlUnit(); desiredCapabilities.setCapability(HtmlUnitDriver.INVALIDSELECTIONERROR, true); desiredCapabilities.setCapability(HtmlUnitDriver.INVALIDXPATHERROR, false); desiredCapabilities.setJavascriptEnabled(true); return new HtmlUnitDriver(desiredCapabilities); } else { return new FirefoxDriver(); } } static <T> T fail(String message) { if (webdriver == null) { Assert.fail(message); } else { Assert.fail(message + ", browser.currentUrl=" + webdriver.getCurrentUrl() + ", browser.title=" + webdriver.getTitle() ); } return null; } }
package com.continuum.nova.chunks; import com.continuum.nova.NovaNative; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.BlockFluidRenderer; import net.minecraft.client.renderer.BlockRendererDispatcher; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.color.BlockColors; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * Splits chunks up into meshes with one mesh for each shader * * @author ddubois * @since 27-Jul-17 */ public class ChunkBuilder { private static final Logger LOG = LogManager.getLogger(ChunkBuilder.class); private static final int VERTEX_COLOR_OFFSET = 3; private static final int LIGHTMAP_COORD_OFFSET = 6; private World world; private final Map<String, IGeometryFilter> filters; private final AtomicLong timeSpentInBlockRenderUpdate = new AtomicLong(0); private final AtomicInteger numChunksUpdated = new AtomicInteger(0); private final BlockColors blockColors; private BlockRendererDispatcher blockRendererDispatcher; public ChunkBuilder(Map<String, IGeometryFilter> filters, World world, BlockColors blockColors) { this.filters = filters; this.world = world; this.blockColors = blockColors; } public void createMeshesForChunk(ChunkUpdateListener.BlockUpdateRange range) { blockRendererDispatcher = Minecraft.getMinecraft().getBlockRenderDispatcher(); Map<String, List<BlockPos>> blocksForFilter = new HashMap<>(); long startTime = System.currentTimeMillis(); for(int x = range.min.x; x <= range.max.x; x++) { for(int y = range.min.y; y < range.max.y; y++) { for(int z = range.min.z; z <= range.max.z; z++) { filterBlockAtPos(blocksForFilter, new BlockPos(x, y, z)); } } } final int chunkHashCode = 31 * range.min.x + range.min.z; for(String filterName : blocksForFilter.keySet()) { Optional<NovaNative.mc_chunk_render_object> renderObj = makeMeshForBlocks(blocksForFilter.get(filterName), world, new BlockPos(range.min.x, range.min.y, range.min.z)); renderObj.ifPresent(obj -> { obj.id = chunkHashCode; obj.x = range.min.x; obj.y = range.min.y; obj.z = range.min.z; NovaNative.INSTANCE.add_chunk_geometry_for_filter(filterName, obj); }); } long timeAfterBuildingStruct = System.currentTimeMillis(); // Using JNA in the old way: 550 ms / chunk long deltaTime = System.currentTimeMillis() - startTime; timeSpentInBlockRenderUpdate.addAndGet(deltaTime); numChunksUpdated.incrementAndGet(); if(numChunksUpdated.get() % 10 == 0) { LOG.debug("It's taken an average of {}ms to update {} chunks", (float) timeSpentInBlockRenderUpdate.get() / numChunksUpdated.get(), numChunksUpdated); LOG.debug("Detailed stats:\nTime to build chunk: {}ms", timeAfterBuildingStruct - startTime); } } /** * Adds the block at the given position to the blocksForFilter map under each filter that matches the block * * @param blocksForFilter The map of blocks to potentially add the given block to * @param pos The position of the block to add */ private void filterBlockAtPos(Map<String, List<BlockPos>> blocksForFilter, BlockPos pos) { IBlockState blockState = world.getBlockState(pos); if(blockState.getRenderType().equals(EnumBlockRenderType.INVISIBLE)) { return; } for(Map.Entry<String, IGeometryFilter> entry : filters.entrySet()) { if(entry.getValue().matches(blockState)) { if(!blocksForFilter.containsKey(entry.getKey())) { blocksForFilter.put(entry.getKey(), new ArrayList<>()); } blocksForFilter.get(entry.getKey()).add(pos); } } } private Optional<NovaNative.mc_chunk_render_object> makeMeshForBlocks(List<BlockPos> positions, World world, BlockPos chunkPos) { List<Integer> vertexData = new ArrayList<>(); IndexList indices = new IndexList(); NovaNative.mc_chunk_render_object chunk_render_object = new NovaNative.mc_chunk_render_object(); CapturingVertexBuffer capturingVertexBuffer = new CapturingVertexBuffer(chunkPos); BlockFluidRenderer fluidRenderer = blockRendererDispatcher.getFluidRenderer(); int blockIndexCounter = 0; for(BlockPos blockPos : positions) { IBlockState blockState = world.getBlockState(blockPos); if(blockState.getRenderType() == EnumBlockRenderType.MODEL) { IBakedModel blockModel = blockRendererDispatcher.getModelForState(blockState); int colorMultiplier = blockColors.colorMultiplier(blockState, null, null, 0); List<EnumFacing> actuallyAllValuesOfEnumFacing = new ArrayList<>(); Collections.addAll(actuallyAllValuesOfEnumFacing, EnumFacing.values()); // FUCK YOU NULL // AND FUCK WHOEVER DECIDED THAT NULL WAS A MEMBER OF ENUMFACING actuallyAllValuesOfEnumFacing.add(null); int faceIndexCounter = 0; for(EnumFacing facing : actuallyAllValuesOfEnumFacing) { List<BakedQuad> quads = blockModel.getQuads(blockState, facing, 0); boolean shouldSideBeRendered = true; if(facing != null) { // When Nova explodes and I get invited to Sweden to visit Mojang, the absolute first thing I'm // going to do it find whoever decided to use `null` rather than ADDING ANOTHER FUCKING ENUM // VALUE and I'm going to make them regret everything they've ever done shouldSideBeRendered = blockState.shouldSideBeRendered(world, blockPos, facing); } boolean hasQuads = !quads.isEmpty(); if(shouldSideBeRendered && hasQuads) { int lmCoords; if(facing == null) { // This logic would be reasonable to write and simple to maintain IF THEY HAD JUST ADDED // ANOTHER FUCKING VALUE TO THEIR STUPID FUCKING ENUM lmCoords = blockState.getPackedLightmapCoords(world, blockPos.offset(EnumFacing.UP)); } else { lmCoords = blockState.getPackedLightmapCoords(world, blockPos.offset(facing)); } for(BakedQuad quad : quads) { if(quad.hasTintIndex()) { colorMultiplier = blockColors.colorMultiplier(blockState, world, blockPos, quad.getTintIndex()); } int[] quadVertexData = addPosition(quad, blockPos.subtract(chunkPos)); setVertexColor(quadVertexData, colorMultiplier); setLightmapCoord(quadVertexData, lmCoords); for(int data : quadVertexData) { vertexData.add(data); } indices.addIndicesForFace(faceIndexCounter, blockIndexCounter); faceIndexCounter += 4; } } } blockIndexCounter += faceIndexCounter; } else if(blockState.getRenderType() == EnumBlockRenderType.LIQUID) { // Why do liquids have to be different? :( fluidRenderer.renderFluid(world, blockState, blockPos, capturingVertexBuffer); } } vertexData.addAll(capturingVertexBuffer.getData()); int offset = indices.size(); for(int i = 0; i < capturingVertexBuffer.getVertexCount() / 4; i++) { indices.addIndicesForFace(offset, 0); offset += 4; } if(vertexData.isEmpty()) { return Optional.empty(); } chunk_render_object.setVertex_data(vertexData); chunk_render_object.setIndices(indices); chunk_render_object.format = NovaNative.NovaVertexFormat.POS_UV_LIGHTMAPUV_NORMAL_TANGENT.ordinal(); return Optional.of(chunk_render_object); } private void setLightmapCoord(int[] quadVertexData, int lmCoords) { for(int i = 0; i < 4; i++) { quadVertexData[i * 7 + LIGHTMAP_COORD_OFFSET] = lmCoords; } } private void setVertexColor(int[] vertexData, int vertexColor) { for(int i = 0; i < 4; i++) { vertexData[i * 7 + VERTEX_COLOR_OFFSET] = vertexColor; } } private int[] addPosition(BakedQuad quad, BlockPos blockPos) { int[] data = Arrays.copyOf(quad.getVertexData(), quad.getVertexData().length); for(int vertex = 0; vertex < 28; vertex += 7) { addPosToVertex(blockPos, data, vertex); } return data; } private void addPosToVertex(BlockPos blockPos, int[] data, int vertex) { float x = Float.intBitsToFloat(data[vertex + 0]); float y = Float.intBitsToFloat(data[vertex + 1]); float z = Float.intBitsToFloat(data[vertex + 2]); x += blockPos.getX(); y += blockPos.getY(); z += blockPos.getZ(); data[vertex + 0] = Float.floatToIntBits(x); data[vertex + 1] = Float.floatToIntBits(y); data[vertex + 2] = Float.floatToIntBits(z); } public void setWorld(World world) { this.world = world; } /** * Returns the IBlockState of the block next to the block at the provided position in the given direction * * @param pos The position to get the block next to * @param world The world that all these blocks are in * @param direction The direction to look in * @return The IBlockState of the block in the provided direction */ private static IBlockState blockNextTo(BlockPos pos, World world, EnumFacing direction) { BlockPos lookupPos = pos.add(direction.getDirectionVec()); return world.getBlockState(lookupPos); } }
package com.creactiviti.piper.core; import java.util.Map; import com.creactiviti.piper.core.job.Job; import com.creactiviti.piper.core.task.JobTask; /** * The central interface responsible for coordinating * and executing jobs. * * @author Arik Cohen * @since Jun 12, 2016 */ public interface Coordinator { /** * Starts a job instance. * * @param aPipelineId * The ID of the pipeline that will execute the job. * @param aInput * A Key-Value map representing the Job's input. * @return Job * The instance of the Job */ Job start (String aPipelineId, Map<String, Object> aInput); /** * Stop a running job. * * @param aJobId * The id of the job to stop * * @return The stopped {@link Job} */ Job stop (String aJobId); /** * Resume a stopped or failed job. * * @param aJobId * The id of the job to resume. * @return The resumed job */ Job resume (String aJobId); /** * Complete a task of a given job. * * @param aTask * The task to complete. */ void complete (JobTask aTask); /** * Handle and erroring task. * * @param aTask * The task to handle. */ void error (JobTask aTask); /** * Handles application events. * * @param aEvent * The event to handle */ void on (Object aEvent); }
package com.dragonheart.dijkstra; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; public class DijkstraGraph { private ArrayList<Edge> listOfEdges; private ArrayList<Point> listOfPoints, sourcePoints; public DijkstraGraph() { this.listOfEdges = new ArrayList<Edge>(); this.listOfPoints = new ArrayList<Point>(); this.sourcePoints = new ArrayList<Point>(); } public void addPoint(Point point) { listOfPoints.add(point); } public void addEdge(Edge edge) { listOfEdges.add(edge); } public void addSource(Point point, Double cost) { if(listOfPoints.contains(point)) { point.aggregateCost = cost; sourcePoints.add(point); } } public void addSources(List<Point> points, Double cost) { for(Point point : points) { addSource(point, cost); } } public void setSource(Point point, Double cost) { sourcePoints = new ArrayList<Point>(); addSource(point, cost); } public void setSources(List<Point> points, Double cost) { sourcePoints = new ArrayList<Point>(); addSources(points, cost); } private List<Point> getListOfVisitedPoints() { ArrayList<Point> listOfVisitedPoints = new ArrayList<Point>(); for(Point point : listOfPoints) { if(point.isVisited()) { listOfVisitedPoints.add(point); } } return listOfVisitedPoints; } private PriorityQueue<Edge> getConnectedEdges(Point startpoint) { PriorityQueue<Edge> connectedEdges = new PriorityQueue<Edge>(); for(Edge edge : listOfEdges) { Point otherPoint = edge.getOtherPoint(startpoint); if(otherPoint != null && !otherPoint.isVisited()) { connectedEdges.add(edge); } } return connectedEdges; } private Point getNextBestPoint() { Point nextBestPoint = null; for(Point visitedPoint : getListOfVisitedPoints()) { PriorityQueue<Edge> connectedEdges = getConnectedEdges(visitedPoint); while(connectedEdges.size() > 0) { Edge connectedEdge = connectedEdges.remove(); Point otherPoint = connectedEdge.getOtherPoint(visitedPoint); if(otherPoint.aggregateCost == null || (visitedPoint.aggregateCost + connectedEdge.cost) < otherPoint.aggregateCost) { otherPoint.aggregateCost = visitedPoint.aggregateCost + connectedEdge.cost; otherPoint.edgeWithLowestCost = connectedEdge; } if(nextBestPoint == null || otherPoint.aggregateCost < nextBestPoint.aggregateCost) { nextBestPoint = otherPoint; } } } return nextBestPoint; } private void performCalculationForAllPoints() { for(Point point : sourcePoints) { point.setVisited(); } Point currentPoint = null; do { currentPoint = getNextBestPoint(); currentPoint.setVisited(); } while(Point.TotalVisited < listOfPoints.size()); } public boolean processGraph() { if(sourcePoints.isEmpty()) { return false; } for(Point point : listOfPoints) { point.resetVisited(); point.aggregateCost = null; point.edgeWithLowestCost = null; } performCalculationForAllPoints(); Point.TotalVisited = 0; return true; } }
package com.foundationdb.server.store; import com.foundationdb.ais.model.Group; import com.foundationdb.ais.model.GroupIndex; import com.foundationdb.ais.model.Index; import com.foundationdb.ais.model.PrimaryKey; import com.foundationdb.ais.model.Sequence; import com.foundationdb.ais.model.TableName; import com.foundationdb.ais.model.UserTable; import com.foundationdb.ais.util.TableChangeValidator.ChangeLevel; import com.foundationdb.qp.persistitadapter.FDBAdapter; import com.foundationdb.qp.persistitadapter.PersistitHKey; import com.foundationdb.qp.persistitadapter.indexrow.PersistitIndexRow; import com.foundationdb.qp.persistitadapter.indexrow.PersistitIndexRowBuffer; import com.foundationdb.qp.rowtype.IndexRowType; import com.foundationdb.qp.rowtype.Schema; import com.foundationdb.qp.util.SchemaCache; import com.foundationdb.server.FDBTableStatusCache; import com.foundationdb.server.error.AkibanInternalException; import com.foundationdb.server.error.DuplicateKeyException; import com.foundationdb.server.error.FDBAdapterException; import com.foundationdb.server.error.QueryCanceledException; import com.foundationdb.server.rowdata.FieldDef; import com.foundationdb.server.rowdata.IndexDef; import com.foundationdb.server.rowdata.RowData; import com.foundationdb.server.rowdata.RowDef; import com.foundationdb.server.service.Service; import com.foundationdb.server.service.config.ConfigurationService; import com.foundationdb.server.service.listener.ListenerService; import com.foundationdb.server.service.lock.LockService; import com.foundationdb.server.service.metrics.LongMetric; import com.foundationdb.server.service.metrics.MetricsService; import com.foundationdb.server.service.session.Session; import com.foundationdb.server.service.transaction.TransactionService; import com.foundationdb.server.service.tree.TreeLink; import com.foundationdb.server.store.FDBTransactionService.TransactionState; import com.foundationdb.server.util.ReadWriteMap; import com.foundationdb.FDBException; import com.foundationdb.KeySelector; import com.foundationdb.KeyValue; import com.foundationdb.MutationType; import com.foundationdb.Range; import com.foundationdb.ReadTransaction; import com.foundationdb.Transaction; import com.foundationdb.async.AsyncIterator; import com.foundationdb.async.Function; import com.foundationdb.async.Future; import com.foundationdb.tuple.ByteArrayUtil; import com.foundationdb.tuple.Tuple; import com.foundationdb.util.layers.DirectorySubspace; import com.google.inject.Inject; import com.persistit.Key; import com.persistit.Persistit; import com.persistit.Value; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.locks.ReentrantLock; public class FDBStore extends AbstractStore<FDBStoreData> implements Service { private static final Tuple INDEX_COUNT_DIR_PATH = Tuple.from("indexCount"); private static final Tuple INDEX_NULL_DIR_PATH = Tuple.from("indexNull"); private static final Logger LOG = LoggerFactory.getLogger(FDBStore.class); private final FDBHolder holder; private final ConfigurationService configService; private final FDBSchemaManager schemaManager; private final FDBTransactionService txnService; private final MetricsService metricsService; private static final String ROWS_FETCHED_METRIC = "SQLLayerRowsFetched"; private static final String ROWS_STORED_METRIC = "SQLLayerRowsStored"; private static final String ROWS_CLEARED_METRIC = "SQLLayerRowsCleared"; private LongMetric rowsFetchedMetric, rowsStoredMetric, rowsClearedMetric; private DirectorySubspace rootDir; private byte[] packedIndexCountPrefix; private byte[] packedIndexNullPrefix; @Inject public FDBStore(FDBHolder holder, ConfigurationService configService, SchemaManager schemaManager, TransactionService txnService, LockService lockService, ListenerService listenerService, MetricsService metricsService) { super(lockService, schemaManager, listenerService); this.holder = holder; this.configService = configService; if(schemaManager instanceof FDBSchemaManager) { this.schemaManager = (FDBSchemaManager)schemaManager; } else { throw new IllegalStateException("Only usable with FDBSchemaManager, found: " + txnService); } if(txnService instanceof FDBTransactionService) { this.txnService = (FDBTransactionService)txnService; } else { throw new IllegalStateException("Only usable with FDBTransactionService, found: " + txnService); } this.metricsService = metricsService; } public Iterator<KeyValue> groupIterator(Session session, Group group) { TransactionState txn = txnService.getTransaction(session); byte[] packedPrefix = packedTuple(group); return txn.getTransaction().getRange(Range.startsWith(packedPrefix)).iterator(); } // TODO: Creates range for hKey and descendants, add another API to specify public Iterator<KeyValue> groupIterator(Session session, Group group, Key hKey) { TransactionState txn = txnService.getTransaction(session); byte[] packedPrefix = packedTuple(group, hKey); Key after = createKey(); hKey.copyTo(after); after.append(Key.AFTER); byte[] packedAfter = packedTuple(group, after); return txn.getTransaction().getRange(packedPrefix, packedAfter).iterator(); } public Iterator<KeyValue> indexIterator(Session session, Index index, boolean reverse) { TransactionState txn = txnService.getTransaction(session); byte[] packedPrefix = packedTuple(index); return txn.getTransaction().getRange(Range.startsWith(packedPrefix), Transaction.ROW_LIMIT_UNLIMITED, reverse).iterator(); } public Iterator<KeyValue> indexIterator(Session session, Index index, Key key, boolean inclusive, boolean reverse) { TransactionState txn = txnService.getTransaction(session); byte[] packedEdge = packedTuple(index); byte[] packedKey = packedTuple(index, key); // begin and end always need to be ordered properly (i.e begin less than end). // End values are *always* exclusive and KeySelector just picks which key ends up there (note strinc on edges). final KeySelector begin, end; if(inclusive) { if(reverse) { begin = KeySelector.firstGreaterThan(packedEdge); end = KeySelector.firstGreaterThan(packedKey); } else { begin = KeySelector.firstGreaterOrEqual(packedKey); end = KeySelector.firstGreaterThan(ByteArrayUtil.strinc(packedEdge)); } } else { if(reverse) { begin = KeySelector.firstGreaterThan(packedEdge); end = KeySelector.firstGreaterOrEqual(packedKey); } else { begin = KeySelector.firstGreaterThan(packedKey); end = KeySelector.firstGreaterThan(ByteArrayUtil.strinc(packedEdge)); } } return txn.getTransaction().getRange(begin, end, Transaction.ROW_LIMIT_UNLIMITED, reverse).iterator(); } @Override public long nextSequenceValue(Session session, Sequence sequence) { long rawValue = 0; SequenceCache cache = sequenceCache.getOrCreateAndPut(sequence.getTreeName(), SEQUENCE_CACHE_VALUE_CREATOR); cache.cacheLock(); try { rawValue = cache.nextCacheValue(); if (rawValue < 0) { rawValue = updateCacheFromServer (cache, sequence); } } finally { cache.cacheUnlock(); } long outValue = sequence.realValueForRawNumber(rawValue); return outValue; } // insert or update the sequence value from the server. // Works only under the cache lock from nextSequenceValue. private long updateCacheFromServer (final SequenceCache cache, final Sequence sequence) { final long [] rawValue = new long[1]; try { txnService.runTransaction(new Function<Transaction,Void> (){ @Override public Void apply (Transaction tr) { byte[] packedTuple = packedTuple(sequence); byte[] byteValue = tr.get(packedTuple).get(); if(byteValue != null) { Tuple tuple = Tuple.fromBytes(byteValue); rawValue[0] = tuple.getLong(0); } else { rawValue[0] = 1; } tr.set(packedTuple, Tuple.from(rawValue[0] + sequence.getCacheSize()).pack()); return null; } }); } catch (Throwable e) { throw new FDBAdapterException(e); } cache.updateCache(rawValue[0], sequence.getCacheSize()); return rawValue[0]; } @Override public long curSequenceValue(Session session, Sequence sequence) { long rawValue = 0; SequenceCache cache = sequenceCache.get(sequence.getTreeName()); if (cache != null) { rawValue = cache.currentValue(); } else { TransactionState txn = txnService.getTransaction(session); byte[] byteValue = txn.getTransaction().get(packedTuple(sequence)).get(); if(byteValue != null) { Tuple tuple = Tuple.fromBytes(byteValue); rawValue = tuple.getLong(0); } } return sequence.realValueForRawNumber(rawValue); } private final ReadWriteMap<String, SequenceCache> sequenceCache = ReadWriteMap.wrapFair(new TreeMap<String, SequenceCache>()); public long getGICount(Session session, GroupIndex index) { TransactionState txn = txnService.getTransaction(session); return getGICountInternal(txn.getTransaction(), index); } public long getGICountApproximate(Session session, GroupIndex index) { TransactionState txn = txnService.getTransaction(session); return getGICountInternal(txn.getTransaction().snapshot(), index); } public static void expandRowData(RowData rowData, KeyValue kv, boolean copyBytes) { expandRowData(rowData, kv.getValue(), copyBytes); } public static void expandRowData(RowData rowData, byte[] value, boolean copyBytes) { if(copyBytes) { byte[] rowBytes = rowData.getBytes(); if((rowBytes == null) || (rowBytes.length < value.length)) { rowBytes = Arrays.copyOf(value, value.length); rowData.reset(rowBytes); } else { System.arraycopy(value, 0, rowBytes, 0, value.length); rowData.reset(0, value.length); } } else { rowData.reset(value); } rowData.prepareRow(0); } public void setRollbackPending(Session session) { if(txnService.isTransactionActive(session)) { txnService.setRollbackPending(session); } } // Service @Override public void start() { rowsFetchedMetric = metricsService.addLongMetric(ROWS_FETCHED_METRIC); rowsStoredMetric = metricsService.addLongMetric(ROWS_STORED_METRIC); rowsClearedMetric = metricsService.addLongMetric(ROWS_CLEARED_METRIC); rootDir = holder.getRootDirectory(); packedIndexCountPrefix = holder.getDatabase().run(new Function<Transaction, byte[]>() { @Override public byte[] apply(Transaction txn) { DirectorySubspace dirSub = holder.getRootDirectory().createOrOpen(txn, INDEX_COUNT_DIR_PATH); return dirSub.pack(); } }); packedIndexNullPrefix = holder.getDatabase().run(new Function<Transaction, byte[]>() { @Override public byte[] apply(Transaction txn) { DirectorySubspace dirSub = holder.getRootDirectory().createOrOpen(txn, INDEX_NULL_DIR_PATH); return dirSub.pack(); } }); } @Override public void stop() { } @Override public void crash() { } // Store @Override protected FDBStoreData createStoreData(Session session, TreeLink treeLink) { return new FDBStoreData(treeLink, createKey()); } @Override protected void releaseStoreData(Session session, FDBStoreData storeData) { // None } @Override protected Key getKey(Session session, FDBStoreData storeData) { return storeData.key; } @Override protected void store(Session session, FDBStoreData storeData) { TransactionState txn = txnService.getTransaction(session); byte[] packedKey = packedTuple(storeData.link, storeData.key); byte[] value; if(storeData.persistitValue != null) { value = Arrays.copyOf(storeData.persistitValue.getEncodedBytes(), storeData.persistitValue.getEncodedSize()); } else { value = storeData.value; } txn.setBytes(packedKey, value); rowsStoredMetric.increment(); } @Override protected boolean fetch(Session session, FDBStoreData storeData) { TransactionState txn = txnService.getTransaction(session); byte[] packedKey = packedTuple(storeData.link, storeData.key); storeData.value = txn.getTransaction().get(packedKey).get(); rowsFetchedMetric.increment(); return (storeData.value != null); } @Override protected boolean clear(Session session, FDBStoreData storeData) { TransactionState txn = txnService.getTransaction(session); byte[] packed = packedTuple(storeData.link, storeData.key); // TODO: Remove get when clear() API changes boolean existed = (txn.getTransaction().get(packed).get() != null); txn.getTransaction().clear(packed); rowsClearedMetric.increment(); return existed; } @Override void resetForWrite(FDBStoreData storeData, Index index, PersistitIndexRowBuffer indexRowBuffer) { if(storeData.persistitValue == null) { storeData.persistitValue = new Value((Persistit) null); } indexRowBuffer.resetForWrite(index, storeData.key, storeData.persistitValue); } @Override protected void expandRowData(FDBStoreData storeData, RowData rowData) { expandRowData(rowData, storeData.value, true); } @Override protected void packRowData(FDBStoreData storeData, RowData rowData) { storeData.value = Arrays.copyOfRange(rowData.getBytes(), rowData.getRowStart(), rowData.getRowEnd()); } @Override protected Iterator<Void> createDescendantIterator(Session session, final FDBStoreData storeData) { TransactionState txn = txnService.getTransaction(session); int prevDepth = storeData.key.getDepth(); storeData.key.append(Key.BEFORE); byte[] packedBegin = packedTuple(storeData.link, storeData.key); storeData.key.to(Key.AFTER); byte[] packedEnd = packedTuple(storeData.link, storeData.key); storeData.key.setDepth(prevDepth); storeData.it = txn.getTransaction().getRange(packedBegin, packedEnd).iterator(); return new Iterator<Void>() { @Override public boolean hasNext() { return storeData.it.hasNext(); } @Override public Void next() { KeyValue kv = storeData.it.next(); unpackTuple(storeData.key, kv.getKey()); storeData.value = kv.getValue(); return null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override protected void sumAddGICount(Session session, FDBStoreData storeData, GroupIndex index, int count) { TransactionState txn = txnService.getTransaction(session); txn.getTransaction().mutate( MutationType.ADD, packedTupleGICount(index), FDBTableStatusCache.packForAtomicOp(count) ); } @Override protected PersistitIndexRowBuffer readIndexRow(Session session, Index parentPKIndex, FDBStoreData storeData, RowDef childRowDef, RowData childRowData) { Key parentPkKey = storeData.key; PersistitKeyAppender keyAppender = PersistitKeyAppender.create(parentPkKey); int[] fields = childRowDef.getParentJoinFields(); for(int field : fields) { FieldDef fieldDef = childRowDef.getFieldDef(field); keyAppender.append(fieldDef, childRowData); } TransactionState txn = txnService.getTransaction(session); byte[] pkValue = txn.getTransaction().get(packedTuple(parentPKIndex, parentPkKey)).get(); PersistitIndexRowBuffer indexRow = null; if (pkValue != null) { Value value = new Value((Persistit)null); value.putEncodedBytes(pkValue, 0, pkValue.length); indexRow = new PersistitIndexRowBuffer(this); indexRow.resetForRead(parentPKIndex, parentPkKey, value); } return indexRow; } @Override protected void writeIndexRow(Session session, Index index, RowData rowData, Key hKey, PersistitIndexRowBuffer indexRow) { TransactionState txn = txnService.getTransaction(session); Key indexKey = createKey(); constructIndexRow(session, indexKey, rowData, index, hKey, indexRow, true); checkUniqueness(txn, index, rowData, indexKey); byte[] packedKey = packedTuple(index, indexRow.getPKey()); byte[] packedValue = Arrays.copyOf(indexRow.getValue().getEncodedBytes(), indexRow.getValue().getEncodedSize()); txn.setBytes(packedKey, packedValue); } @Override protected void deleteIndexRow(Session session, Index index, RowData rowData, Key hKey, PersistitIndexRowBuffer indexRowBuffer) { TransactionState txn = txnService.getTransaction(session); Key indexKey = createKey(); // See big note in PersistitStore#deleteIndexRow() about format. if(index.isUniqueAndMayContainNulls()) { // IndexRow is used below, use these as intermediates. Key spareKey = indexRowBuffer.getPKey(); Value spareValue = indexRowBuffer.getValue(); if(spareKey == null) { spareKey = createKey(); } if(spareValue == null) { spareValue = new Value((Persistit)null); } // Can't use a PIRB, because we need to get the hkey. Need a PersistitIndexRow. FDBAdapter adapter = createAdapter(session, SchemaCache.globalSchema(getAIS(session))); IndexRowType indexRowType = adapter.schema().indexRowType(index); PersistitIndexRow indexRow = adapter.takeIndexRow(indexRowType); constructIndexRow(session, indexKey, rowData, index, hKey, indexRow, false); for(KeyValue kv : txn.getTransaction().getRange(Range.startsWith(packedTuple(index, indexKey)))) { // Key unpackTuple(spareKey, kv.getKey()); // Value byte[] valueBytes = kv.getValue(); spareValue.clear(); spareValue.putEncodedBytes(valueBytes, 0, valueBytes.length); // Delicate: copyFromKeyValue initializes the key returned by hKey indexRow.copyFrom(spareKey, spareValue); PersistitHKey rowHKey = (PersistitHKey)indexRow.hKey(); if(rowHKey.key().compareTo(hKey) == 0) { txn.getTransaction().clear(kv.getKey()); break; } } adapter.returnIndexRow(indexRow); } else { constructIndexRow(session, indexKey, rowData, index, hKey, indexRowBuffer, false); txn.getTransaction().clear(packedTuple(index, indexKey)); } } @Override protected void preWrite(Session session, FDBStoreData storeData, RowDef rowDef, RowData rowData) { // None } @Override public void truncateTree(Session session, TreeLink treeLink) { TransactionState txn = txnService.getTransaction(session); txn.getTransaction().clear(Range.startsWith(packedTuple(treeLink))); } @Override public void deleteIndexes(Session session, Collection<? extends Index> indexes) { Transaction txn = txnService.getTransaction(session).getTransaction(); for(Index index : indexes) { rootDir.removeIfExists(txn, FDBNameGenerator.dataPath(index)); if(index.isGroupIndex()) { txn.clear(packedTupleGICount((GroupIndex)index)); } } } @Override public void removeTrees(Session session, UserTable table) { Transaction txn = txnService.getTransaction(session).getTransaction(); // Table and indexes (and group and group indexes if root table) rootDir.removeIfExists(txn, FDBNameGenerator.dataPath(table.getName())); // Sequence if(table.getIdentityColumn() != null) { deleteSequences(session, Collections.singleton(table.getIdentityColumn().getIdentityGenerator())); } } @Override public void removeTree(Session session, TreeLink treeLink) { if(!schemaManager.treeRemovalIsDelayed()) { truncateTree(session, treeLink); if(treeLink instanceof IndexDef) { Index index = ((IndexDef)treeLink).getIndex(); if(index.isGroupIndex()) { TransactionState txn = txnService.getTransaction(session); txn.getTransaction().clear(packedTupleGICount((GroupIndex)index)); } } } schemaManager.treeWasRemoved(session, treeLink.getSchemaName(), treeLink.getTreeName()); } @Override public void truncateIndexes(Session session, Collection<? extends Index> indexes) { TransactionState txn = txnService.getTransaction(session); for(Index index : indexes) { truncateTree(session, index.indexDef()); if(index.isGroupIndex()) { txn.setBytes(packedTupleGICount((GroupIndex)index), FDBTableStatusCache.packForAtomicOp(0)); } } } @Override public void deleteSequences(Session session, Collection<? extends Sequence> sequences) { for (Sequence sequence : sequences) { sequenceCache.remove(sequence.getTreeName()); rootDir.removeIfExists( txnService.getTransaction(session).getTransaction(), FDBNameGenerator.dataPath(sequence) ); } } @Override public FDBAdapter createAdapter(Session session, Schema schema) { return new FDBAdapter(this, schema, session, configService); } @Override public boolean treeExists(Session session, String schemaName, String treeName) { TransactionState txn = txnService.getTransaction(session); return txn.getTransaction().getRange(Range.startsWith(packTreeName(treeName)), 1).iterator().hasNext(); } @Override public boolean isRetryableException(Throwable t) { if(t instanceof FDBException) { int code = ((FDBException)t).getCode(); // not_committed || commit_unknown_result return (code == 1020) || (code == 1021); } return false; } // TODO: A little ugly and slow, but unique indexes will get refactored soon and need for separator goes away. @Override public long nullIndexSeparatorValue(Session session, final Index index) { // New txn to avoid spurious conflicts return holder.getDatabase().run(new Function<Transaction,Long>() { @Override public Long apply(Transaction txn) { byte[] keyBytes = ByteArrayUtil.join(packedIndexNullPrefix, packTreeName(index.getTreeName())); byte[] valueBytes = txn.get(keyBytes).get(); long outValue = 1; if(valueBytes != null) { outValue += Tuple.fromBytes(valueBytes).getLong(0); } txn.set(keyBytes, Tuple.from(outValue).pack()); return outValue; } }); } @Override public void finishedAlter(Session session, Map<TableName, TableName> tableNames, ChangeLevel changeLevel) { if(changeLevel == ChangeLevel.NONE) { return; } Transaction txn = txnService.getTransaction(session).getTransaction(); for(Entry<TableName, TableName> entry : tableNames.entrySet()) { TableName oldName = entry.getKey(); TableName newName = entry.getValue(); Tuple dataPath = FDBNameGenerator.dataPath(oldName); Tuple alterPath = FDBNameGenerator.alterPath(newName); switch(changeLevel) { case METADATA: case METADATA_NOT_NULL: // - move renamed directories if(!oldName.equals(newName)) { schemaManager.renamingTable(session, oldName, newName); } break; case INDEX: if(!rootDir.exists(txn, alterPath)) { continue; } // - Move everything from dataAltering/foo/ to data/foo/ // - remove dataAltering/foo/ for(Object subPath : rootDir.list(txn, alterPath)) { Tuple subDataPath = dataPath.addObject(subPath); Tuple subAlterPath = alterPath.addObject(subPath); rootDir.move(txn, subAlterPath, subDataPath); } rootDir.remove(txn, alterPath); break; case TABLE: case GROUP: if(!rootDir.exists(txn, alterPath)) { continue; } // - move everything from data/foo/ to dataAltering/foo/ // - remove data/foo // - move dataAltering/foo to data/foo/ if(rootDir.exists(txn, dataPath)) { for(Object subPath : rootDir.list(txn, dataPath)) { Tuple subDataPath = dataPath.addObject(subPath); Tuple subAlterPath = alterPath.addObject(subPath); if(!rootDir.exists(txn, subAlterPath)) { rootDir.move(txn, subDataPath, subAlterPath); } } rootDir.remove(txn, dataPath); } rootDir.move(txn, alterPath, dataPath); break; default: throw new AkibanInternalException("Unexpected ChangeLevel: " + changeLevel); } } } @Override public void traverse(Session session, Group group, TreeRecordVisitor visitor) { TransactionState txn = txnService.getTransaction(session); visitor.initialize(session, this); Key key = createKey(); for(KeyValue kv : txn.getTransaction().getRange(Range.startsWith(packedTuple(group)))) { // Key unpackTuple(key, kv.getKey()); // Value RowData rowData = new RowData(); expandRowData(rowData, kv, true); // Visit visitor.visit(key, rowData); } } @Override public <V extends IndexVisitor<Key, Value>> V traverse(Session session, Index index, V visitor, long scanTimeLimit, long sleepTime) { Key key = createKey(); Value value = new Value((Persistit)null); TransactionState txn = txnService.getTransaction(session); long nextCommitTime = 0; if (scanTimeLimit >= 0) { nextCommitTime = txn.getStartTime() + scanTimeLimit; } byte[] packedPrefix = packedTuple(index); KeySelector start = KeySelector.firstGreaterOrEqual(packedPrefix); KeySelector end = KeySelector.firstGreaterThan(ByteArrayUtil.strinc(packedPrefix)); Iterator<KeyValue> it = txn.getTransaction().getRange(start, end).iterator(); while(it.hasNext()) { KeyValue kv = it.next(); // Key unpackTuple(key, kv.getKey()); // Value value.clear(); byte[] valueBytes = kv.getValue(); value.putEncodedBytes(valueBytes, 0, valueBytes.length); // Visit visitor.visit(key, value); if ((scanTimeLimit >= 0) && (System.currentTimeMillis() >= nextCommitTime)) { ((AsyncIterator)it).dispose(); txn.getTransaction().commit().get(); if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException ex) { throw new QueryCanceledException(session); } } txn.reset(); txn.getTransaction().reset(); nextCommitTime = txn.getStartTime() + scanTimeLimit; start = KeySelector.firstGreaterThan(kv.getKey()); it = txn.getTransaction().getRange(start, end).iterator(); } } return visitor; } // KeyCreator @Override public Key createKey() { return new Key(null, 2047); } // Internal private void constructIndexRow(Session session, Key indexKey, RowData rowData, Index index, Key hKey, PersistitIndexRowBuffer indexRow, boolean forInsert) { indexKey.clear(); indexRow.resetForWrite(index, indexKey, new Value((Persistit) null)); indexRow.initialize(rowData, hKey); indexRow.close(session, this, forInsert); } private void checkUniqueness(TransactionState txn, Index index, RowData rowData, Key key) { if(index.isUnique() && !hasNullIndexSegments(rowData, index)) { int segmentCount = index.indexDef().getIndexKeySegmentCount(); // An index that isUniqueAndMayContainNulls has the extra null-separating field. if (index.isUniqueAndMayContainNulls()) { segmentCount++; } key.setDepth(segmentCount); checkKeyDoesNotExistInIndex(txn, index, key); } } private void checkKeyDoesNotExistInIndex(TransactionState txn, Index index, Key key) { assert index.isUnique() : index; byte[] bkey = packedTuple(index, key); Future<byte[]> future = txn.getTransaction().get(bkey); if (txn.getUniquenessChecks() == null) { long startNanos = System.nanoTime(); future.blockUntilReady(); long endNanos = System.nanoTime(); txn.uniquenessTime += (endNanos - startNanos); if (future.get() != null) { throw new DuplicateKeyException(index.getIndexName().getName(), key); } } else { txn.getUniquenessChecks().add(txn, index, bkey, future); } } // Static public static void unpackTuple(Key key, byte[] tupleBytes) { Tuple t = Tuple.fromBytes(tupleBytes); byte[] keyBytes = t.getBytes(t.size() - 1); key.clear(); if(key.getMaximumSize() < keyBytes.length) { key.setMaximumSize(keyBytes.length); } System.arraycopy(keyBytes, 0, key.getEncodedBytes(), 0, keyBytes.length); key.setEncodedSize(keyBytes.length); } private static byte[] packedTuple(Index index) { return packedTuple(index.indexDef()); } private static byte[] packedTuple(Index index, Key key) { return packedTuple(index.indexDef(), key); } private static byte[] packedTuple(TreeLink treeLink) { return packTreeName(treeLink.getTreeName()); } private static byte[] packedTuple(TreeLink treeLink, Key key) { return packedTuple(treeLink.getTreeName(), key); } public static byte[] packTreeName(String treeName) { return Base64.decodeBase64(treeName); } private static byte[] packedTuple(String treeName, Key key) { byte[] treeBytes = packTreeName(treeName); byte[] keyBytes = Arrays.copyOf(key.getEncodedBytes(), key.getEncodedSize()); return ByteArrayUtil.join(treeBytes, Tuple.from(keyBytes).pack()); } private byte[] packedTupleGICount(GroupIndex index) { return ByteArrayUtil.join(packedIndexCountPrefix, packTreeName(index.indexDef().getTreeName())); } private long getGICountInternal(ReadTransaction txn, GroupIndex index) { byte[] key = packedTupleGICount(index); byte[] value = txn.get(key).get(); return FDBTableStatusCache.unpackForAtomicOp(value); } private static final ReadWriteMap.ValueCreator<String, SequenceCache> SEQUENCE_CACHE_VALUE_CREATOR = new ReadWriteMap.ValueCreator<String, SequenceCache>() { public SequenceCache createValueForKey (String treeName) { return new SequenceCache(); } }; private static class SequenceCache { private long value; private long cacheSize; private final ReentrantLock cacheLock; public SequenceCache() { this(0L, 1L); } public SequenceCache(long startValue, long cacheSize) { this.value = startValue; this.cacheSize = startValue + cacheSize; this.cacheLock = new ReentrantLock(false); } public void updateCache (long startValue, long cacheSize) { this.value = startValue; this.cacheSize = startValue + cacheSize; } public long nextCacheValue() { if (++value == cacheSize) { // ensure the next call to nextCacheValue also fails // and will do so until the updateCache() is called. --value; return -1; } return value; } public long currentValue() { return value; } public void cacheLock() { cacheLock.lock(); } public void cacheUnlock() { cacheLock.unlock(); } } }
package com.github.jaws.proto.v13; import static com.github.jaws.proto.v13.HeaderConstants.*; public class EncodedFrame { public boolean valid = false; public byte[] raw = new byte[126]; public int payloadLength = 0; public int payloadStart = 0; public int totalLength = 0; public static EncodedFrame encode(final int opcode, final boolean fin, final boolean masked, final byte[] data, final int offset, final int length, EncodedFrame reuse) throws EncodeException { // Create a new frame if the user passes us null if(reuse == null) reuse = new EncodedFrame(); reuse.valid = false; int header = 0; // TODO: Check opcode for correctness. For now we'll just // bitwise AND it to make sure it fits. header |= opcode & OPCODE_MASK; if(fin) header |= FIN_BIT; else header &= ~FIN_BIT; if(masked) header |= MASK_BIT; else header &= ~MASK_BIT; int extraBytes = 0; byte[] payloadExtra = { 0, 0, 0, 0, 0, 0, 0, 0 }; if(length < 126) { header |= length & PAYLOAD_MASK; } else if(length < Short.MAX_VALUE) { header |= 126 & PAYLOAD_MASK; payloadExtra[0] = (byte)((length & 0xFF00) >>> 8); payloadExtra[1] = (byte)((length & 0x00FF) >>> 0); extraBytes += 2; } else { header |= 127 & PAYLOAD_MASK; payloadExtra[4] = (byte)((length & 0xFF000000) >>> 24); payloadExtra[5] = (byte)((length & 0x00FF0000) >>> 16); payloadExtra[6] = (byte)((length & 0x0000FF00) >>> 8); payloadExtra[7] = (byte)((length & 0x000000FF) >>> 0); extraBytes += 8; } byte[] mask = { 0, 0, 0, 0 }; int payloadStart = 2 + extraBytes; if(masked) { for(int i = 0; i < mask.length; ++i) { mask[i] = (byte)(Math.random() * 256.0); } payloadStart += 4; } if(reuse.raw.length < payloadStart + length) { reuse.raw = new byte[payloadStart + length]; } byte[] raw = reuse.raw; // Write out header raw[0] = (byte)((header & 0xFF00) >>> 8); raw[1] = (byte)((header & 0x00FF) >>> 0); System.arraycopy(payloadExtra, 0, raw, 2, extraBytes); if(masked) { System.arraycopy(mask, 0, raw, 2 + extraBytes, mask.length); } for(int i = payloadStart, j = offset; j < length; ++j, ++i) { // mask is zeroed out in case MASK_BIT isn't set raw[i] = (byte)(data[j] ^ mask[j % 4]); } reuse.payloadLength = length; reuse.payloadStart = payloadStart; reuse.totalLength = payloadStart + length; reuse.valid = true; return reuse; } }
package com.github.lutzblox.sockets; import com.github.lutzblox.*; import com.github.lutzblox.exceptions.Errors; import com.github.lutzblox.exceptions.NetworkException; import com.github.lutzblox.packets.Packet; import com.github.lutzblox.packets.PacketReader; import com.github.lutzblox.packets.PacketWriter; import com.github.lutzblox.packets.encryption.EncryptedPacketReader; import com.github.lutzblox.packets.encryption.EncryptedPacketWriter; import com.github.lutzblox.packets.encryption.EncryptionKey; import com.github.lutzblox.query.Query; import com.github.lutzblox.query.QueryPolicy; import com.github.lutzblox.query.QueryStatus; import com.github.lutzblox.query.QueryType; import com.github.lutzblox.states.State; import java.io.*; import java.lang.Thread.UncaughtExceptionHandler; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A wrapper for a {@code Socket}, used to send/receive {@code Packets} * * @author Christopher Lutz */ public class Connection { private Listenable listenable; private Socket socket; private Thread listener, connCheck; private State mainState, state, nextState = null; private List<Packet> dropped = new ArrayList<Packet>(); private List<Packet> vitalDropped = new ArrayList<Packet>(); private Packet waiting = null; private long ping = -1, pingStart = 0, pingTotal = 0, pingTimes = 0; private boolean encrypted = false, allowSettingState = true, running = false, serverSide = false, firstReceive = true, firstSend = true, shouldRespond = false, pingShouldRespond = false, remoteClosed = false, canExecute = true, canGetInput = true, canOutput = true, initialized = false, qrySent = false; private int readTimeout = 8000; private PacketReader packetReader; private PacketWriter packetWriter; private EncryptedPacketReader encryptedReader; private EncryptedPacketWriter encryptedWriter; private Map<QueryType, QueryPolicy> policies = new ConcurrentHashMap<QueryType, QueryPolicy>(); private Map<String, Query> toQuery = new ConcurrentHashMap<String, Query>(); private Map<String, Query> queries = new ConcurrentHashMap<String, Query>(); private Map<String, Object> completedQueries = new ConcurrentHashMap<String, Object>(); private EncryptionKey encryptionKey = null; private static final String EMPTY_PLACEHOLDER = "::REMCL"; /** * Creates a new {@code Connection} with the specified parameters * * @param listenable The {@code Listenable} object that created this * {@code Connection} * @param socket The {@code Socket} to wrap in this {@code Connection} * @param state The beginning {@code State} of this {@code Connection} * @param serverSide Whether or not this {@code Connection} represents a * server-side connection */ public Connection(Listenable listenable, Socket socket, State state, boolean serverSide) { this(listenable, socket, state, serverSide, true); } /** * Creates a new {@code Connection} with the specified parameters * * @param listenable The {@code Listenable} object that created this * {@code Connection} * @param socket The {@code Socket} to wrap in this {@code Connection} * @param state The beginning {@code State} of this {@code Connection} * @param serverSide Whether or not this {@code Connection} represents a * server-side connection * @param allowSettingState Whether or not {@code setToSend()} or {@code setToReceive()} have any effect on this {@code Connection}'s {@code State} * @param policies The {@code QueryPolicies} to use when this server/client is queried */ public Connection(Listenable listenable, Socket socket, State state, boolean serverSide, boolean allowSettingState, Map<QueryType, QueryPolicy> policies) { this(listenable, socket, state, serverSide, allowSettingState); this.policies = policies; } /** * Creates a new {@code Connection} with the specified parameters * * @param listenable The {@code Listenable} object that created this * {@code Connection} * @param socket The {@code Socket} to wrap in this {@code Connection} * @param state The beginning {@code State} of this {@code Connection} * @param serverSide Whether or not this {@code Connection} represents a * server-side connection * @param policies The {@code QueryPolicies} to use when this server/client is queried */ public Connection(Listenable listenable, Socket socket, State state, boolean serverSide, Map<QueryType, QueryPolicy> policies) { this(listenable, socket, state, serverSide, true); this.policies = policies; } /** * Creates a new {@code Connection} with the specified parameters * * @param listenable The {@code Listenable} object that created this * {@code Connection} * @param socket The {@code Socket} to wrap in this {@code Connection} * @param state The beginning {@code State} of this {@code Connection} * @param serverSide Whether or not this {@code Connection} represents a * server-side connection * @param allowSettingState Whether or not {@code setToSend()} or {@code setToReceive()} have any effect on this {@code Connection}'s {@code State} */ public Connection(final Listenable listenable, Socket socket, State state, boolean serverSide, boolean allowSettingState) { this.initialized = true; this.listenable = listenable; this.socket = socket; this.mainState = state; this.state = state; this.serverSide = serverSide; this.allowSettingState = allowSettingState; packetReader = new PacketReader(); packetWriter = new PacketWriter(); encryptedReader = new EncryptedPacketReader(); encryptedReader.setListenable(listenable); encryptedWriter = new EncryptedPacketWriter(); encryptedWriter.setListenable(listenable); listener = new Thread() { @Override public void run() { listenerRun(); } }; listener.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { Errors.threadErrored(t.getName(), Connection.this.listenable, e); } }); listener.setName("Packet Listener: " + (serverSide ? "Server" : "Client") + " on IP " + getIp()); connCheck = new Thread() { @Override public void run() { Socket socket = Connection.this.socket; while (running) { if (socket != null) { if (socket.isClosed() || !socket.isConnected()) { try { listener.interrupt(); close(); } catch (Exception e) { Errors.genericFatalConnection(listenable, getIp(), getPort(), e); } } } try { Thread.sleep(1000); } catch (Exception e) { // Ignore sleep interruptions } } } }; connCheck.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { Errors.threadErrored(t.getName(), Connection.this.listenable, e); } }); connCheck.setName("Connection Check: " + (serverSide ? "Server" : "Client") + " on IP " + getIp()); running = true; shouldRespond = !serverSide; listener.start(); connCheck.start(); } /** * Creates an uninitialized Connection with default values<br><br> * <p> * Default values:<br> * - Listenable: {@code null}<br> * - Socket: {@code null}<br> * - State: {@code MUTUAL}<br> * - Side: Client ({@code false})<br> */ private Connection() { this.listenable = null; this.socket = null; this.mainState = State.MUTUAL; this.state = State.MUTUAL; this.serverSide = false; } /** * Sets the {@code QueryPolicy} to use when this server receives a query of the specified {@code QueryType} * * @param type The {@code QueryType} to assign the policy to * @param policy The {@code QueryPolicy} to assign to the type */ public void setQueryPolicy(QueryType type, QueryPolicy policy) { policies.put(type, policy); } /** * Gets the {@code QueryPolicies} attached to this {@code Connection} * * @return A {@code Map} of the {@code QueryTypes} and their respective {@code QueryPolicies} */ public Map<QueryType, QueryPolicy> getQueryPolicies() { return policies; } /** * Gets the {@code QueryPolicy} attached to this {@code Connection} for the specified {@code QueryType} * * @param type The {@code QueryType} to retrieve the policy from * @return The {@code QueryPolicy} for the specified {@code QueryType} */ public QueryPolicy getQueryPolicy(QueryType type) { return getQueryPolicies().get(type); } /** * Sends a {@code Packet} across the connection * * @param p The {@code Packet} to send * @param expectResponse Whether or not the {@code Connection} should wait for a * response (decides whether or not to timeout the {@code read()} * calls */ public void sendPacket(Packet p, boolean expectResponse) { if (waiting != null) { dropped.add(waiting); if (waiting.isVital()) { vitalDropped.add(waiting); } } if (p.isEmpty()) { p.putData(Packet.EMPTY_PACKET); } waiting = p; this.shouldRespond = expectResponse; qrySent = false; } /** * Gets all {@code Packets} dropped by this {@code Connection} * * @return A {@code Packet[]} containing all dropped {@code Packets} */ public Packet[] getDroppedPackets() { return dropped.toArray(new Packet[]{}); } /** * Gets the IP of this {@code Connection} * * @return The IP of this {@code Connection} */ public String getIp() { if (socket != null) { InetAddress address = socket.getInetAddress(); if (address != null) { return address.getHostAddress(); } else { return "null"; } } else { return "null"; } } /** * Gets the port of this {@code Connection} * * @return The port of this {@code Connection}, or -1 if the underlying {@code Socket} is null */ public int getPort() { if (socket != null) { return socket.getPort(); } else { return -1; } } /** * Checks the connection state of this {@code Connection} * * @return Whether or not this {@code Connection} is connected */ public boolean isConnected() { return socket.isConnected(); } /** * Checks whether or not this {@code Connection} is closed * * @return Whether or not this {@code Connection} is closed */ public boolean isClosed() { return socket.isClosed(); } /** * Checks if the remote side of this connection is closed * * @return Whether the remote side of this connection is closed */ public boolean isRemoteClosed() { return remoteClosed; } /** * Makes the {@code Connection} set itself back to the {@code Receiving} * state */ public void setToReceive() { if (allowSettingState) { this.nextState = State.RECEIVING; } else { Errors.disallowedForcedStateChange(listenable, new NetworkException("")); } } /** * Makes the {@code Connection} set itself back to the {@code Sending} state */ public void setToSend() { if (allowSettingState) { this.nextState = State.SENDING; } else { Errors.disallowedForcedStateChange(listenable, new NetworkException("")); } } /** * Sets the timeout on reading from the {@code Connection} * * @param timeout The timeout in milliseconds */ public void setReadTimeout(int timeout) { this.readTimeout = timeout; } /** * Gets the timeout on reading from the {@code Connection} * * @return The timeout in milliseconds */ public int getReadTimeout() { return readTimeout; } /** * Attempts to close this {@code Connection} * * @throws IOException If an I/O error occurs while shutting down this * {@code Connection} */ public void close() throws IOException { close(false); } /** * Attempts to close this {@code Connection} * * @param socketClosed Whether or not the socket is already closed (closing it again will cause an error) * @throws IOException If an I/O error occurs while shutting down this * {@code Connection} */ public void close(boolean socketClosed) throws IOException { running = false; listener.interrupt(); connCheck.interrupt(); if (!socket.isClosed() && !socketClosed) { socket.close(); } } /** * Gets the time between the last client-server communication in milliseconds * * @return The ping of the {@code Connection} in milliseconds */ public long getPing() { return ping; } /** * Gets the average time between client-server communications in milliseconds * * @return The average ping of the {@code Connection} in milliseconds; */ public long getAveragePing() { if (pingTimes > 0) { return pingTotal / pingTimes; } else { return 0; } } /** * Sets this {@code Connection} to be encrypted with the specified {@code EncryptionKey} * * @param encrypted {@code true} to encrypt the {@code Connection}, {@code false} to stop encrypting * @param key The {@code EncryptionKey} to use for the encryption */ public void setEncrypted(boolean encrypted, EncryptionKey key) { this.encryptionKey = key; this.encrypted = encrypted; } /** * Gets whether or not the {@code Connection} is set to be encrypted * * @return Whether or not this {@code Connection} is set to be encrypted (i.e. the {@code setEncrypted(true, ...)} has been called) */ public boolean getEncrypted() { return encrypted; } /** * Gets the {@code EncryptionKey} used to encrypt this {@code Connection} * * @return The {@code EncryptionKey} used to encrypt this {@code Connection}, or {@code null} if the {@code Connection} is not being encrypted */ public EncryptionKey getEncryptionKey() { return encryptionKey; } /** * Retrieves the current {@code State} of this {@code Connection} * * @return This {@code Connection}'s current {@code State} */ public State getCurrentState() { return state; } /** * Gets whether or not this {@code Connection} is initialized. The only way this would return {@code false} is if the {@code Connection} was created using the default constructor * * @return Whether or not this {@code Connection} is initialized */ public boolean getInitialized() { return initialized; } private void listenerRun() { try { while (running && socket != null && socket.isConnected() && !socket.isClosed() && !remoteClosed) { if (mainState == State.MUTUAL) { // Check if this is a server connection and the first packet sent if (firstSend && serverSide) { state = State.SENDING; // Check if there are packets waiting to be read } else if (new InputStreamReader( socket.getInputStream()).ready()) { state = State.RECEIVING; // Check if there are packets waiting to be written } else if (waiting != null) { state = State.SENDING; // Default the state back to mutual } else { state = State.MUTUAL; } } if (state == State.SENDING && socket != null && !socket.isOutputShutdown()) { // Add a delay between attempts to send packages to avoid locking the thread if (!(firstSend && serverSide) && waiting == null && vitalDropped.size() == 0) { // Wait until there is a waiting packet (there cannot be any vital dropped packets until there is a waiting one, which is why this check is all we need) while (waiting == null) { try { Thread.sleep(100); } catch (InterruptedException e) { // Ignore sleep interruptions } } } Packet p = new Packet(); boolean skip = false; if (firstSend && serverSide) { if (listenable instanceof Server) { p = ((Server) listenable).getInformationPacket(); } p = ((ServerListenable) listenable).fireListenerOnConnect(this, p); if(p == null){ p = new Packet(); } firstSend = false; } else if (waiting != null) { p = waiting; waiting = null; } else if (vitalDropped.size() > 0) { p = vitalDropped.get(0); vitalDropped.remove(0); } else { skip = true; if (nextState != null) { state = nextState; nextState = null; } } // Check to make sure that one of the above conditions was true if (!skip) { if(p.isEmpty()){ p.putData(Packet.EMPTY_PACKET); } String toWrite; Throwable[] errors; p = handleQueries(p); if (getEncrypted()) { toWrite = encryptedWriter.getPacketAsWriteableString(this, p); errors = encryptedWriter.getErrors(); } else { toWrite = packetWriter.getPacketAsWriteableString(this, p); errors = packetWriter.getErrors(); } send(toWrite); if (qrySent) { qrySent = false; } if (shouldRespond) { pingStart = System.currentTimeMillis(); pingShouldRespond = true; } for (Throwable t : errors) { listenable.report(t); } if(nextState != null){ state = nextState; nextState = null; }else{ state = State.RECEIVING; } } } else if (state == State.RECEIVING && socket != null && !socket.isInputShutdown()) { InputStream stream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder read = new StringBuilder(); String inTemp; try { if (shouldRespond) { shouldRespond = false; socket.setSoTimeout(readTimeout); } else { socket.setSoTimeout(0); } if ((inTemp = reader.readLine()) != null) { read.append(inTemp); } else { remoteClosed = true; } if (pingShouldRespond) { ping = System.currentTimeMillis() - pingStart; pingTotal += ping; pingTimes++; } } catch (Exception e) { if (e instanceof SocketTimeoutException) { timeoutQueries(); listenable.fireListenerOnTimeout(this); } else if (!(e instanceof SocketException)) { listenable.report(e); } } String readStr = read.toString(); if (!readStr.equals(EMPTY_PLACEHOLDER) && !readStr.equals("")) { Packet p; Throwable[] errors; if (readStr.startsWith(":ENC:")) { p = encryptedReader.getPacketFromString(this, readStr); errors = encryptedReader.getErrors(); } else { p = packetReader.getPacketFromString(this, readStr); errors = packetReader.getErrors(); } for (Throwable t : errors) { listenable.report(t); } if (p.getData().length == 1 && p.getData()[0] == Packet.EMPTY_PACKET) { p.clearData(); } // Handle queries Map<String, Object> requests = p.getAllForType(Query.class); if (requests == null) { requests = new ConcurrentHashMap<String, Object>(); } for (String s : requests.keySet()) { Query q = (Query) requests.get(s); Object result; QueryPolicy policy = policies.get(q.getType()); if (policy == null || policy.getPolicyDecider().allow(getConnectionInfo())) { result = q.getType().query(this, listenable, q.getParameters()); } else { result = "qry-rej:" + policy.getMessage(); } completedQueries.put(q.getId(), result); } p.removeAllForType(Query.class); if (completedQueries.size() > 0 && waiting == null) { waiting = new Packet(); waiting.setVital(true); shouldRespond = false; qrySent = true; } Map<String, Object> completions = p.getAllForNamePrefix("qry-resp:"); if(completions == null){ completions = new ConcurrentHashMap<String, Object>(); } for(String id : completions.keySet()){ if(queries.containsKey(id)){ Query q = queries.get(id); if(q != null){ Object result = completions.get(id); if(result instanceof String && ((String) result).startsWith("qry-rej:")){ q.setValue(null); q.setStatus(QueryStatus.getRejectedStatus(((String) result).substring("qry-rej:".length()))); }else{ q.setValue(result); q.setStatus(QueryStatus.getSuccessfulStatus("")); } } queries.remove(id); } } p.removeAllForNamePrefix("qry-resp:"); if(p.hasData(":QRYONLY:")){ p.clearData(); state = State.SENDING; } else { if(firstReceive && !serverSide){ ((ClientListenable) listenable).fireListenerOnConnect(p); state = State.SENDING; firstReceive = false; }else{ listenable.fireListenerOnReceive(this, p); if(nextState != null) { state = nextState; nextState = null; }else{ state = State.SENDING; } } } } } } close(); } catch (Exception e) { boolean close = false; if(e instanceof SocketException){ if(socket.isClosed() || e.getMessage().equalsIgnoreCase("socket closed")) { close = true; } }else if(e instanceof IOException){ if(socket.isClosed() || e.getMessage().equalsIgnoreCase("socket closed")){ close = true; }else{ remoteClosed = true; } } listenable.report(e); try{ close(close); }catch (Exception e1){ listenable.report(e1); } } } private void timeoutQueries() { for (String id : toQuery.keySet()) { Query q = toQuery.get(id); q.setStatus(QueryStatus.getTimedOutStatus((serverSide ? "Client" : "Server") + " timed out!")); toQuery.remove(id); } for (String id : queries.keySet()) { Query q = queries.get(id); q.setStatus(QueryStatus.getTimedOutStatus((serverSide ? "Client" : "Server") + " timed out!")); queries.remove(id); } } private Packet handleQueries(Packet p) { if (qrySent) { p.putData(":QRYONLY:", "null"); } for (String id : toQuery.keySet()) { Query q = toQuery.get(id); if (q != null) { p.putData(q.getId(), q); queries.put(id, q); } toQuery.remove(id); } for (String id : completedQueries.keySet()) { Object result = completedQueries.get(id); p.putData("qry-resp:" + id, result); completedQueries.remove(id); } if (queries.size() > 0) { shouldRespond = true; p.setVital(true); } return p; } private void send(String data) throws IOException { if(socket != null && !socket.isOutputShutdown()) { OutputStream stream = socket.getOutputStream(); PrintWriter out = new PrintWriter(stream, true); out.println(data); } } /** * Creates and executes a {@code Query} against the remote side of this {@code Connection} * * @param id The id to use for the {@code Query} * @param type The type of query to request * @param params The parameters to pass to the {@code Query} * @return A {@code Query} object to be used to obtain the results of the query request */ public Query query(String id, QueryType type, Map<String, Object> params) { Query q = new Query(id, type, params); toQuery.put(id, q); if (waiting == null) { waiting = new Packet(); waiting.setVital(true); shouldRespond = true; qrySent = true; } return q; } public ConnectionInfo getConnectionInfo() { return new ConnectionInfo(this); } /** * Gets the IP of the local machine * * @return The local IP as a {@code String} */ public static String getLocalIp() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (Exception e) { return "null"; } } /** * Gets an uninitialized instance of {@code Connection} with no open ports or listening {@code Threads} * * @return An uninitialized {@code Connection} with no open ports or listening {@code Threads} */ public static Connection getUninitializedConnection() { return new Connection(); } }
package com.worth.ifs.finance.resource.cost; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.*; import java.math.BigDecimal; /** * {@code CapitalUsage} implements {@link FinanceRowItem} */ public class CapitalUsage implements FinanceRowItem { Long id; String name; @NotNull(message = NOT_BLANK_MESSAGE) @Min(value = 1, message = VALUE_MUST_BE_HIGHER_MESSAGE) @Digits(integer = MAX_DIGITS_INT, fraction = MAX_FRACTION, message = MAX_DIGITS_MESSAGE) Integer deprecation; @NotBlank(message = NOT_BLANK_MESSAGE) @NotNull(message = NOT_BLANK_MESSAGE) @Length(max = MAX_STRING_LENGTH, message = MAX_LENGTH_MESSAGE) String description; @NotBlank(message = NOT_BLANK_MESSAGE) @NotNull(message = NOT_BLANK_MESSAGE) @Length(max = MAX_STRING_LENGTH, message = MAX_LENGTH_MESSAGE) String existing; @NotNull(message = NOT_BLANK_MESSAGE) @DecimalMin(value = "1", message = VALUE_MUST_BE_HIGHER_MESSAGE) @Digits(integer = MAX_DIGITS, fraction = MAX_FRACTION, message = MAX_DIGITS_MESSAGE) BigDecimal npv; @DecimalMin(value = "0", message = VALUE_MUST_BE_HIGHER_MESSAGE) @Digits(integer = MAX_DIGITS, fraction = MAX_FRACTION, message = MAX_DIGITS_MESSAGE) BigDecimal residualValue; @NotNull(message = NOT_BLANK_MESSAGE) @Min(value = 0, message = VALUE_MUST_BE_HIGHER_MESSAGE) @Max(value = 100, message = VALUE_MUST_BE_LOWER_MESSAGE) @Digits(integer = MAX_DIGITS_INT, fraction = MAX_FRACTION, message = MAX_DIGITS_MESSAGE) Integer utilisation; public CapitalUsage() { this.name = getCostType().getType(); } public CapitalUsage(Long id, Integer deprecation, String description, String existing, BigDecimal npv, BigDecimal residualValue, Integer utilisation ) { this(); this.id = id; this.deprecation = deprecation; this.description = description; this.existing = existing; this.npv = npv; this.residualValue = residualValue; this.utilisation = utilisation; } @Override public Long getId() { return id; } public Integer getDeprecation() { return deprecation; } public String getDescription() { return description; } public String getExisting() { return existing; } public BigDecimal getNpv() { return npv; } public BigDecimal getResidualValue() { return residualValue; } public Integer getUtilisation() { return utilisation; } @Override public BigDecimal getTotal() { // ( npv - residualValue ) * utilisation-percentage if(npv == null || residualValue == null || utilisation == null) { return BigDecimal.ZERO; } return npv.subtract(residualValue) .multiply(new BigDecimal(utilisation) .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_EVEN)); } @Override public String getName() { return name; } @Override public boolean isEmpty() { return false; } @Override public int getMinRows() { return 0; } @Override public FinanceRowType getCostType() { return FinanceRowType.CAPITAL_USAGE; } public void setDescription(String description) { this.description = description; } public void setNpv(BigDecimal npv) { this.npv = npv; } public void setResidualValue(BigDecimal residualValue) { this.residualValue = residualValue; } public void setUtilisation(Integer utilisation) { this.utilisation = utilisation; } public void setDeprecation(Integer deprecation) { this.deprecation = deprecation; } public void setExisting(String existing) { this.existing = existing; } }
// ZeissLSMReader.java package loci.formats.in; import java.io.*; import java.util.*; import loci.common.*; import loci.formats.*; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; public class ZeissLSMReader extends BaseTiffReader { // -- Constants -- public static final String[] MDB_SUFFIX = {"mdb"}; /** Tag identifying a Zeiss LSM file. */ private static final int ZEISS_ID = 34412; /** Data types. */ private static final int TYPE_SUBBLOCK = 0; private static final int TYPE_ASCII = 2; private static final int TYPE_LONG = 4; private static final int TYPE_RATIONAL = 5; /** Subblock types. */ private static final int SUBBLOCK_RECORDING = 0x10000000; private static final int SUBBLOCK_LASERS = 0x30000000; private static final int SUBBLOCK_LASER = 0x50000000; private static final int SUBBLOCK_TRACKS = 0x20000000; private static final int SUBBLOCK_TRACK = 0x40000000; private static final int SUBBLOCK_DETECTION_CHANNELS = 0x60000000; private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000; private static final int SUBBLOCK_ILLUMINATION_CHANNELS = 0x80000000; private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000; private static final int SUBBLOCK_BEAM_SPLITTERS = 0xa0000000; private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000; private static final int SUBBLOCK_DATA_CHANNELS = 0xc0000000; private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000; private static final int SUBBLOCK_TIMERS = 0x11000000; private static final int SUBBLOCK_TIMER = 0x12000000; private static final int SUBBLOCK_MARKERS = 0x13000000; private static final int SUBBLOCK_MARKER = 0x14000000; private static final int SUBBLOCK_END = (int) 0xffffffff; private static final int SUBBLOCK_GAMMA = 1; private static final int SUBBLOCK_BRIGHTNESS = 2; private static final int SUBBLOCK_CONTRAST = 3; private static final int SUBBLOCK_RAMP = 4; private static final int SUBBLOCK_KNOTS = 5; private static final int SUBBLOCK_PALETTE = 6; /** Data types. */ private static final int RECORDING_ENTRY_DESCRIPTION = 0x10000002; private static final int RECORDING_ENTRY_OBJECTIVE = 0x10000004; private static final int TRACK_ENTRY_TIME_BETWEEN_STACKS = 0x4000000b; private static final int LASER_ENTRY_NAME = 0x50000001; private static final int CHANNEL_ENTRY_DETECTOR_GAIN = 0x70000003; private static final int CHANNEL_ENTRY_PINHOLE_DIAMETER = 0x70000009; private static final int CHANNEL_ENTRY_SPI_WAVELENGTH_START = 0x70000022; private static final int CHANNEL_ENTRY_SPI_WAVELENGTH_END = 0x70000023; private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003; private static final int START_TIME = 0x10000036; private static final int DATA_CHANNEL_NAME = 0xd0000001; // -- Static fields -- private static Hashtable metadataKeys = createKeys(); // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private boolean thumbnailsRemoved = false; private byte[] lut = null; private Vector timestamps; private int validChannels; private String mdbFilename; // -- Constructor -- /** Constructs a new Zeiss LSM reader. */ public ZeissLSMReader() { super("Zeiss Laser-Scanning Microscopy", "lsm"); } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); pixelSizeX = pixelSizeY = pixelSizeZ = 0f; lut = null; thumbnailsRemoved = false; timestamps = null; validChannels = 0; mdbFilename = null; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 1); if (mdbFilename == null) return super.getUsedFiles(); return new String[] {currentId, mdbFilename}; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || getPixelType() != FormatTools.UINT8) return null; byte[][] b = new byte[3][256]; for (int i=2; i>=3-validChannels; i for (int j=0; j<256; j++) { b[i][j] = (byte) j; } } return b; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || getPixelType() != FormatTools.UINT16) return null; short[][] s = new short[3][65536]; for (int i=2; i>=3-validChannels; i for (int j=0; j<s[i].length; j++) { s[i][j] = (short) j; } } return s; } // -- Internal BaseTiffReader API methods -- /* @see BaseTiffReader#initMetadata() */ protected void initMetadata() { if (!thumbnailsRemoved) return; Hashtable ifd = ifds[0]; status("Reading LSM metadata"); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); try { super.initStandardMetadata(); // get TIF_CZ_LSMINFO structure short[] s = TiffTools.getIFDShortArray(ifd, ZEISS_ID, true); byte[] cz = new byte[s.length]; for (int i=0; i<s.length; i++) { cz[i] = (byte) s[i]; } RandomAccessStream ras = new RandomAccessStream(cz); ras.order(isLittleEndian()); put("MagicNumber", ras.readInt()); put("StructureSize", ras.readInt()); put("DimensionX", ras.readInt()); put("DimensionY", ras.readInt()); core[0].sizeZ = ras.readInt(); ras.skipBytes(4); core[0].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: put("DataType", "12 bit unsigned integer"); break; case 5: put("DataType", "32 bit float"); break; case 0: put("DataType", "varying data types"); break; default: put("DataType", "8 bit unsigned integer"); } put("ThumbnailX", ras.readInt()); put("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; put("VoxelSizeX", new Double(pixelSizeX)); put("VoxelSizeY", new Double(pixelSizeY)); put("VoxelSizeZ", new Double(pixelSizeZ)); put("OriginX", ras.readDouble()); put("OriginY", ras.readDouble()); put("OriginZ", ras.readDouble()); int scanType = ras.readShort(); switch (scanType) { case 0: put("ScanType", "x-y-z scan"); core[0].dimensionOrder = "XYZCT"; break; case 1: put("ScanType", "z scan (x-z plane)"); core[0].dimensionOrder = "XYZCT"; break; case 2: put("ScanType", "line scan"); core[0].dimensionOrder = "XYZCT"; break; case 3: put("ScanType", "time series x-y"); core[0].dimensionOrder = "XYTCZ"; break; case 4: put("ScanType", "time series x-z"); core[0].dimensionOrder = "XYZTC"; break; case 5: put("ScanType", "time series 'Mean of ROIs'"); core[0].dimensionOrder = "XYTCZ"; break; case 6: put("ScanType", "time series x-y-z"); core[0].dimensionOrder = "XYZTC"; break; case 7: put("ScanType", "spline scan"); core[0].dimensionOrder = "XYCTZ"; break; case 8: put("ScanType", "spline scan x-z"); core[0].dimensionOrder = "XYCZT"; break; case 9: put("ScanType", "time series spline plane x-z"); core[0].dimensionOrder = "XYTCZ"; break; case 10: put("ScanType", "point mode"); core[0].dimensionOrder = "XYZCT"; break; default: put("ScanType", "x-y-z scan"); core[0].dimensionOrder = "XYZCT"; } store.setImageName("", 0); MetadataTools.setDefaultCreationDate(store, getCurrentFile(), 0); int spectralScan = ras.readShort(); if (spectralScan != 1) put("SpectralScan", "no spectral scan"); else put("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: put("DataType2", "calculated data"); break; case 2: put("DataType2", "animation"); break; default: put("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); long channelColorsOffset = ras.readInt(); put("TimeInterval", ras.readDouble()); ras.skipBytes(4); long scanInformationOffset = ras.readInt(); ras.skipBytes(4); long timeStampOffset = ras.readInt(); long eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); put("DisplayAspectX", ras.readDouble()); put("DisplayAspectY", ras.readDouble()); put("DisplayAspectZ", ras.readDouble()); put("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(overlayOffsets[i], overlayKeys[i]); } put("ToolbarFlags", ras.readInt()); ras.close(); // read referenced structures core[0].indexed = lut != null && getSizeC() == 1; if (isIndexed()) { core[0].sizeC = 1; core[0].rgb = false; } if (getSizeC() == 0) core[0].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[0].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[0].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } put("DimensionZ", getSizeZ()); put("DimensionChannels", getSizeC()); if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 16); int namesOffset = in.readInt(); // read in the intensity value for each color if (namesOffset > 0) { in.skipBytes(namesOffset - 16); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) put("ChannelName" + i, name); } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 8); for (int i=0; i<getSizeT(); i++) { double stamp = in.readDouble(); put("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); put("Event" + i + " Time", eventTime); put("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; put("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); Stack prefix = new Stack(); int count = 1; Object value = null; boolean done = false; int nextLaserMedium = 0, nextLaserType = 0, nextGain = 0; int nextPinhole = 0, nextEmWave = 0, nextExWave = 0; int nextChannelName = 0; while (!done) { int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); switch (blockType) { case TYPE_SUBBLOCK: switch (entry) { case SUBBLOCK_RECORDING: prefix.push("Recording"); break; case SUBBLOCK_LASERS: prefix.push("Lasers"); break; case SUBBLOCK_LASER: prefix.push("Laser " + count); count++; break; case SUBBLOCK_TRACKS: prefix.push("Tracks"); break; case SUBBLOCK_TRACK: prefix.push("Track " + count); count++; break; case SUBBLOCK_DETECTION_CHANNELS: prefix.push("Detection Channels"); break; case SUBBLOCK_DETECTION_CHANNEL: prefix.push("Detection Channel " + count); count++; validChannels = count; break; case SUBBLOCK_ILLUMINATION_CHANNELS: prefix.push("Illumination Channels"); break; case SUBBLOCK_ILLUMINATION_CHANNEL: prefix.push("Illumination Channel " + count); count++; break; case SUBBLOCK_BEAM_SPLITTERS: prefix.push("Beam Splitters"); break; case SUBBLOCK_BEAM_SPLITTER: prefix.push("Beam Splitter " + count); count++; break; case SUBBLOCK_DATA_CHANNELS: prefix.push("Data Channels"); break; case SUBBLOCK_DATA_CHANNEL: prefix.push("Data Channel " + count); count++; break; case SUBBLOCK_TIMERS: prefix.push("Timers"); break; case SUBBLOCK_TIMER: prefix.push("Timer " + count); count++; break; case SUBBLOCK_MARKERS: prefix.push("Markers"); break; case SUBBLOCK_MARKER: prefix.push("Marker " + count); count++; break; case SUBBLOCK_END: count = 1; if (prefix.size() > 0) prefix.pop(); if (prefix.size() == 0) done = true; break; } break; case TYPE_LONG: value = new Long(in.readInt()); break; case TYPE_RATIONAL: value = new Double(in.readDouble()); break; case TYPE_ASCII: value = in.readString(dataSize); break; } String key = getKey(prefix, entry).trim(); if (value instanceof String) value = ((String) value).trim(); if (key != null) addMeta(key, value); float n; switch (entry) { case RECORDING_ENTRY_DESCRIPTION: store.setImageDescription(value.toString(), 0); break; case RECORDING_ENTRY_OBJECTIVE: String[] tokens = value.toString().split(" "); StringBuffer model = new StringBuffer(); int next = 0; for (; next<tokens.length; next++) { if (tokens[next].indexOf("/") != -1) break; model.append(tokens[next]); } store.setObjectiveModel(model.toString(), 0, 0); if (next < tokens.length) { String p = tokens[next++]; String mag = p.substring(0, p.indexOf("/") - 1); String na = p.substring(p.indexOf("/") + 1); store.setObjectiveNominalMagnification(new Integer(mag), 0, 0); store.setObjectiveLensNA(new Float(na), 0, 0); } if (next < tokens.length) { store.setObjectiveImmersion(tokens[next++], 0, 0); } break; case TRACK_ENTRY_TIME_BETWEEN_STACKS: store.setDimensionsTimeIncrement( new Float(value.toString()), 0, 0); break; case LASER_ENTRY_NAME: String medium = value.toString(); String laserType = null; if (medium.startsWith("HeNe")) { medium = "HeNe"; laserType = "Gas"; } else if (medium.startsWith("Argon")) { medium = "Ar"; laserType = "Gas"; } else if (medium.equals("Titanium:Sapphire") || medium.equals("Mai Tai")) { medium = "TiSapphire"; laserType = "SolidState"; } else if (medium.equals("YAG")) { medium = null; laserType = "SolidState"; } else if (medium.equals("Ar/Kr")) { medium = null; laserType = "Gas"; } else if (medium.equals("Enterprise")) medium = null; if (medium != null && laserType != null) { store.setLaserLaserMedium(medium, 0, nextLaserMedium++); store.setLaserType(laserType, 0, nextLaserType++); } break; //case LASER_POWER: // TODO: this is a setting, not a fixed value //n = Float.parseFloat(value.toString()); //store.setLaserPower(new Float(n), 0, count - 1); //break; case CHANNEL_ENTRY_DETECTOR_GAIN: //n = Float.parseFloat(value.toString()); //store.setDetectorSettingsGain(new Float(n), 0, nextGain++); break; case CHANNEL_ENTRY_PINHOLE_DIAMETER: n = Float.parseFloat(value.toString()); if (n > 0 && nextPinhole < getSizeC()) { store.setLogicalChannelPinholeSize(new Float(n), 0, nextPinhole++); } break; case CHANNEL_ENTRY_SPI_WAVELENGTH_START: n = Float.parseFloat(value.toString()); store.setLogicalChannelEmWave(new Integer((int) n), 0, (nextEmWave % getSizeC())); nextEmWave++; break; case CHANNEL_ENTRY_SPI_WAVELENGTH_END: n = Float.parseFloat(value.toString()); store.setLogicalChannelExWave(new Integer((int) n), 0, (nextExWave % getSizeC())); nextExWave++; break; case ILLUM_CHANNEL_WAVELENGTH: n = Float.parseFloat(value.toString()); store.setLogicalChannelEmWave(new Integer((int) n), 0, (nextEmWave % getSizeC())); store.setLogicalChannelExWave(new Integer((int) n), 0, (nextExWave % getSizeC())); nextEmWave++; nextExWave++; break; case START_TIME: // date/time on which the first pixel was acquired, in days // since 30 December 1899 double time = Double.parseDouble(value.toString()); store.setImageCreationDate(DataTools.convertDate( (long) (time * 86400000), DataTools.MICROSOFT), 0); break; case DATA_CHANNEL_NAME: store.setLogicalChannelName(value.toString(), 0, nextChannelName++); break; } if (!done) done = in.getFilePointer() >= in.length() - 12; } } } catch (FormatException exc) { if (debug) trace(exc); } catch (IOException exc) { if (debug) trace(exc); } if (isIndexed()) core[0].rgb = false; if (getEffectiveSizeC() == 0) core[0].imageCount = getSizeZ() * getSizeT(); else core[0].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); if (getImageCount() != ifds.length) { int diff = getImageCount() - ifds.length; core[0].imageCount = ifds.length; if (diff % getSizeZ() == 0) { core[0].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[0].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[0].sizeZ = ifds.length; core[0].sizeT = 1; } else if (getSizeT() > 1) { core[0].sizeT = ifds.length; core[0].sizeZ = 1; } } if (getSizeZ() == 0) core[0].sizeZ = getImageCount(); if (getSizeT() == 0) core[0].sizeT = getImageCount() / getSizeZ(); MetadataTools.populatePixels(store, this, true); Float pixX = new Float((float) pixelSizeX); Float pixY = new Float((float) pixelSizeY); Float pixZ = new Float((float) pixelSizeZ); store.setDimensionsPhysicalSizeX(pixX, 0, 0); store.setDimensionsPhysicalSizeY(pixY, 0, 0); store.setDimensionsPhysicalSizeZ(pixZ, 0, 0); float firstStamp = timestamps.size() == 0 ? 0f : ((Double) timestamps.get(0)).floatValue(); for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (zct[2] < timestamps.size()) { float thisStamp = ((Double) timestamps.get(zct[2])).floatValue(); store.setPlaneTimingDeltaT(new Float(thisStamp - firstStamp), 0, 0, i); float nextStamp = zct[2] < getSizeT() - 1 ? ((Double) timestamps.get(zct[2] + 1)).floatValue() : thisStamp; if (i == getSizeT() - 1 && zct[2] > 0) { thisStamp = ((Double) timestamps.get(zct[2] - 1)).floatValue(); } store.setPlaneTimingExposureTime(new Float(nextStamp - thisStamp), 0, 0, i); } } // see if we have an associated MDB file Location dir = new Location(currentId).getAbsoluteFile().getParentFile(); String[] dirList = dir.list(); for (int i=0; i<dirList.length; i++) { if (checkSuffix(dirList[i], MDB_SUFFIX)) { try { Location file = new Location(dir.getPath(), dirList[i]); if (!file.isDirectory()) { mdbFilename = file.getAbsolutePath(); Vector[] tables = MDBParser.parseDatabase(mdbFilename); for (int table=0; table<tables.length; table++) { String[] columnNames = (String[]) tables[table].get(0); for (int row=1; row<tables[table].size(); row++) { String[] tableRow = (String[]) tables[table].get(row); String baseKey = columnNames[0] + " "; for (int col=0; col<tableRow.length; col++) { addMeta(baseKey + columnNames[col + 1] + " " + row, tableRow[col]); } } } } } catch (Exception exc) { if (debug) trace(exc); } i = dirList.length; } } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (debug) debug("ZeissLSMReader.initFile(" + id + ")"); thumbnailsRemoved = false; super.initFile(id); timestamps = new Vector(); // go through the IFD hashtable array and // remove anything with NEW_SUBFILE_TYPE = 1 // NEW_SUBFILE_TYPE = 1 indicates that the IFD // contains a thumbnail image status("Removing thumbnails"); Vector newIFDs = new Vector(); for (int i=0; i<ifds.length; i++) { long subFileType = TiffTools.getIFDLongValue(ifds[i], TiffTools.NEW_SUBFILE_TYPE, true, 0); if (subFileType == 0) { // check that predictor is set to 1 if anything other // than LZW compression is used if (TiffTools.getCompression(ifds[i]) != TiffTools.LZW) { ifds[i].put(new Integer(TiffTools.PREDICTOR), new Integer(1)); } newIFDs.add(ifds[i]); } } // reset numImages and ifds ifds = (Hashtable[]) newIFDs.toArray(new Hashtable[0]); thumbnailsRemoved = true; initMetadata(); core[0].littleEndian = !isLittleEndian(); } // -- Helper methods -- /** Parses overlay-related fields. */ protected void parseOverlays(long data, String suffix) throws IOException { if (data == 0) return; in.seek(data); int nde = in.readInt(); put("NumberDrawingElements-" + suffix, nde); int size = in.readInt(); int idata = in.readInt(); put("LineWidth-" + suffix, idata); idata = in.readInt(); put("Measure-" + suffix, idata); in.skipBytes(8); put("ColorRed-" + suffix, in.read()); put("ColorGreen-" + suffix, in.read()); put("ColorBlue-" + suffix, in.read()); in.skipBytes(1); put("Valid-" + suffix, in.readInt()); put("KnotWidth-" + suffix, in.readInt()); put("CatchArea-" + suffix, in.readInt()); // some fields describing the font put("FontHeight-" + suffix, in.readInt()); put("FontWidth-" + suffix, in.readInt()); put("FontEscapement-" + suffix, in.readInt()); put("FontOrientation-" + suffix, in.readInt()); put("FontWeight-" + suffix, in.readInt()); put("FontItalic-" + suffix, in.readInt()); put("FontUnderline-" + suffix, in.readInt()); put("FontStrikeOut-" + suffix, in.readInt()); put("FontCharSet-" + suffix, in.readInt()); put("FontOutPrecision-" + suffix, in.readInt()); put("FontClipPrecision-" + suffix, in.readInt()); put("FontQuality-" + suffix, in.readInt()); put("FontPitchAndFamily-" + suffix, in.readInt()); put("FontFaceName-" + suffix, in.readString(64)); // some flags for measuring values of different drawing element types put("ClosedPolyline-" + suffix, in.read()); put("OpenPolyline-" + suffix, in.read()); put("ClosedBezierCurve-" + suffix, in.read()); put("OpenBezierCurve-" + suffix, in.read()); put("ArrowWithClosedTip-" + suffix, in.read()); put("ArrowWithOpenTip-" + suffix, in.read()); put("Ellipse-" + suffix, in.read()); put("Circle-" + suffix, in.read()); put("Rectangle-" + suffix, in.read()); put("Line-" + suffix, in.read()); /* try { int drawingEl = (size - 194) / nde; if (drawingEl <= 0) return; if (DataTools.swap(nde) < nde) nde = DataTools.swap(nde); for (int i=0; i<nde; i++) { put("DrawingElement" + i + "-" + suffix, in.readString(drawingEl)); } } catch (ArithmeticException exc) { if (debug) trace(exc); } */ } /** Construct a metadata key from the given stack. */ private String getKey(Stack stack, int entry) { StringBuffer sb = new StringBuffer(); for (int i=0; i<stack.size(); i++) { sb.append((String) stack.get(i)); sb.append("/"); } sb.append(" - "); sb.append(metadataKeys.get(new Integer(entry))); return sb.toString(); } private static Hashtable createKeys() { Hashtable h = new Hashtable(); h.put(new Integer(0x10000001), "Name"); h.put(new Integer(0x4000000c), "Name"); h.put(new Integer(0x50000001), "Name"); h.put(new Integer(0x90000001), "Name"); h.put(new Integer(0x90000005), "Name"); h.put(new Integer(0xb0000003), "Name"); h.put(new Integer(0xd0000001), "Name"); h.put(new Integer(0x12000001), "Name"); h.put(new Integer(0x14000001), "Name"); h.put(new Integer(0x10000002), "Description"); h.put(new Integer(0x14000002), "Description"); h.put(new Integer(0x10000003), "Notes"); h.put(new Integer(0x10000004), "Objective"); h.put(new Integer(0x10000005), "Processing Summary"); h.put(new Integer(0x10000006), "Special Scan Mode"); h.put(new Integer(0x10000007), "Scan Type"); h.put(new Integer(0x10000008), "Scan Mode"); h.put(new Integer(0x10000009), "Number of Stacks"); h.put(new Integer(0x1000000a), "Lines Per Plane"); h.put(new Integer(0x1000000b), "Samples Per Line"); h.put(new Integer(0x1000000c), "Planes Per Volume"); h.put(new Integer(0x1000000d), "Images Width"); h.put(new Integer(0x1000000e), "Images Height"); h.put(new Integer(0x1000000f), "Number of Planes"); h.put(new Integer(0x10000010), "Number of Stacks"); h.put(new Integer(0x10000011), "Number of Channels"); h.put(new Integer(0x10000012), "Linescan XY Size"); h.put(new Integer(0x10000013), "Scan Direction"); h.put(new Integer(0x10000014), "Time Series"); h.put(new Integer(0x10000015), "Original Scan Data"); h.put(new Integer(0x10000016), "Zoom X"); h.put(new Integer(0x10000017), "Zoom Y"); h.put(new Integer(0x10000018), "Zoom Z"); h.put(new Integer(0x10000019), "Sample 0X"); h.put(new Integer(0x1000001a), "Sample 0Y"); h.put(new Integer(0x1000001b), "Sample 0Z"); h.put(new Integer(0x1000001c), "Sample Spacing"); h.put(new Integer(0x1000001d), "Line Spacing"); h.put(new Integer(0x1000001e), "Plane Spacing"); h.put(new Integer(0x1000001f), "Plane Width"); h.put(new Integer(0x10000020), "Plane Height"); h.put(new Integer(0x10000021), "Volume Depth"); h.put(new Integer(0x10000034), "Rotation"); h.put(new Integer(0x10000035), "Precession"); h.put(new Integer(0x10000036), "Sample 0Time"); h.put(new Integer(0x10000037), "Start Scan Trigger In"); h.put(new Integer(0x10000038), "Start Scan Trigger Out"); h.put(new Integer(0x10000039), "Start Scan Event"); h.put(new Integer(0x10000040), "Start Scan Time"); h.put(new Integer(0x10000041), "Stop Scan Trigger In"); h.put(new Integer(0x10000042), "Stop Scan Trigger Out"); h.put(new Integer(0x10000043), "Stop Scan Event"); h.put(new Integer(0x10000044), "Stop Scan Time"); h.put(new Integer(0x10000045), "Use ROIs"); h.put(new Integer(0x10000046), "Use Reduced Memory ROIs"); h.put(new Integer(0x10000047), "User"); h.put(new Integer(0x10000048), "Use B/C Correction"); h.put(new Integer(0x10000049), "Position B/C Contrast 1"); h.put(new Integer(0x10000050), "Position B/C Contrast 2"); h.put(new Integer(0x10000051), "Interpolation Y"); h.put(new Integer(0x10000052), "Camera Binning"); h.put(new Integer(0x10000053), "Camera Supersampling"); h.put(new Integer(0x10000054), "Camera Frame Width"); h.put(new Integer(0x10000055), "Camera Frame Height"); h.put(new Integer(0x10000056), "Camera Offset X"); h.put(new Integer(0x10000057), "Camera Offset Y"); h.put(new Integer(0x40000001), "Multiplex Type"); h.put(new Integer(0x40000002), "Multiplex Order"); h.put(new Integer(0x40000003), "Sampling Mode"); h.put(new Integer(0x40000004), "Sampling Method"); h.put(new Integer(0x40000005), "Sampling Number"); h.put(new Integer(0x40000006), "Acquire"); h.put(new Integer(0x50000002), "Acquire"); h.put(new Integer(0x7000000b), "Acquire"); h.put(new Integer(0x90000004), "Acquire"); h.put(new Integer(0xd0000017), "Acquire"); h.put(new Integer(0x40000007), "Sample Observation Time"); h.put(new Integer(0x40000008), "Time Between Stacks"); h.put(new Integer(0x4000000d), "Collimator 1 Name"); h.put(new Integer(0x4000000e), "Collimator 1 Position"); h.put(new Integer(0x4000000f), "Collimator 2 Name"); h.put(new Integer(0x40000010), "Collimator 2 Position"); h.put(new Integer(0x40000011), "Is Bleach Track"); h.put(new Integer(0x40000012), "Bleach After Scan Number"); h.put(new Integer(0x40000013), "Bleach Scan Number"); h.put(new Integer(0x40000014), "Trigger In"); h.put(new Integer(0x12000004), "Trigger In"); h.put(new Integer(0x14000003), "Trigger In"); h.put(new Integer(0x40000015), "Trigger Out"); h.put(new Integer(0x12000005), "Trigger Out"); h.put(new Integer(0x14000004), "Trigger Out"); h.put(new Integer(0x40000016), "Is Ratio Track"); h.put(new Integer(0x40000017), "Bleach Count"); h.put(new Integer(0x40000018), "SPI Center Wavelength"); h.put(new Integer(0x40000019), "Pixel Time"); h.put(new Integer(0x40000020), "ID Condensor Frontlens"); h.put(new Integer(0x40000021), "Condensor Frontlens"); h.put(new Integer(0x40000022), "ID Field Stop"); h.put(new Integer(0x40000023), "Field Stop Value"); h.put(new Integer(0x40000024), "ID Condensor Aperture"); h.put(new Integer(0x40000025), "Condensor Aperture"); h.put(new Integer(0x40000026), "ID Condensor Revolver"); h.put(new Integer(0x40000027), "Condensor Revolver"); h.put(new Integer(0x40000028), "ID Transmission Filter 1"); h.put(new Integer(0x40000029), "ID Transmission 1"); h.put(new Integer(0x40000030), "ID Transmission Filter 2"); h.put(new Integer(0x40000031), "ID Transmission 2"); h.put(new Integer(0x40000032), "Repeat Bleach"); h.put(new Integer(0x40000033), "Enable Spot Bleach Pos"); h.put(new Integer(0x40000034), "Spot Bleach Position X"); h.put(new Integer(0x40000035), "Spot Bleach Position Y"); h.put(new Integer(0x40000036), "Bleach Position Z"); h.put(new Integer(0x50000003), "Power"); h.put(new Integer(0x90000002), "Power"); h.put(new Integer(0x70000003), "Detector Gain"); h.put(new Integer(0x70000005), "Amplifier Gain"); h.put(new Integer(0x70000007), "Amplifier Offset"); h.put(new Integer(0x70000009), "Pinhole Diameter"); h.put(new Integer(0x7000000c), "Detector Name"); h.put(new Integer(0x7000000d), "Amplifier Name"); h.put(new Integer(0x7000000e), "Pinhole Name"); h.put(new Integer(0x7000000f), "Filter Set Name"); h.put(new Integer(0x70000010), "Filter Name"); h.put(new Integer(0x70000013), "Integrator Name"); h.put(new Integer(0x70000014), "Detection Channel Name"); h.put(new Integer(0x70000015), "Detector Gain B/C 1"); h.put(new Integer(0x70000016), "Detector Gain B/C 2"); h.put(new Integer(0x70000017), "Amplifier Gain B/C 1"); h.put(new Integer(0x70000018), "Amplifier Gain B/C 2"); h.put(new Integer(0x70000019), "Amplifier Offset B/C 1"); h.put(new Integer(0x70000020), "Amplifier Offset B/C 2"); h.put(new Integer(0x70000021), "Spectral Scan Channels"); h.put(new Integer(0x70000022), "SPI Wavelength Start"); h.put(new Integer(0x70000023), "SPI Wavelength End"); h.put(new Integer(0x70000026), "Dye Name"); h.put(new Integer(0xd0000014), "Dye Name"); h.put(new Integer(0x70000027), "Dye Folder"); h.put(new Integer(0xd0000015), "Dye Folder"); h.put(new Integer(0x90000003), "Wavelength"); h.put(new Integer(0x90000006), "Power B/C 1"); h.put(new Integer(0x90000007), "Power B/C 2"); h.put(new Integer(0xb0000001), "Filter Set"); h.put(new Integer(0xb0000002), "Filter"); h.put(new Integer(0xd0000004), "Color"); h.put(new Integer(0xd0000005), "Sample Type"); h.put(new Integer(0xd0000006), "Bits Per Sample"); h.put(new Integer(0xd0000007), "Ratio Type"); h.put(new Integer(0xd0000008), "Ratio Track 1"); h.put(new Integer(0xd0000009), "Ratio Track 2"); h.put(new Integer(0xd000000a), "Ratio Channel 1"); h.put(new Integer(0xd000000b), "Ratio Channel 2"); h.put(new Integer(0xd000000c), "Ratio Const. 1"); h.put(new Integer(0xd000000d), "Ratio Const. 2"); h.put(new Integer(0xd000000e), "Ratio Const. 3"); h.put(new Integer(0xd000000f), "Ratio Const. 4"); h.put(new Integer(0xd0000010), "Ratio Const. 5"); h.put(new Integer(0xd0000011), "Ratio Const. 6"); h.put(new Integer(0xd0000012), "Ratio First Images 1"); h.put(new Integer(0xd0000013), "Ratio First Images 2"); h.put(new Integer(0xd0000016), "Spectrum"); h.put(new Integer(0x12000003), "Interval"); return h; } }
package com.github.scr.j8iterables; import com.github.scr.j8iterables.core.*; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.*; import java.util.stream.Collector; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Utility methods to extend Guava Iterables with Java 8 Stream-like classes such as Collectors. * * @author scr */ public class J8Iterables { /** * The empty iterable to be shared across calls to {@link #emptyIterable()}. */ public static final FluentIterable EMPTY_ITERABLE = fromSupplier(Collections::emptyIterator); @VisibleForTesting J8Iterables() { } /** * Collect iterable of iterables into a mutable container. * * @param iterables The iterable of iterables * @param supplier The container supplier * @param accumulator The accumulator function * @param combiner The combiner function * @param <T> The type of elements * @param <R> The return type * @return Collected result * @see Stream#collect(Supplier, BiConsumer, BiConsumer) */ public static <T, R> R collect(@NotNull Iterable<Iterable<T>> iterables, @NotNull Supplier<R> supplier, @NotNull BiConsumer<R, ? super T> accumulator, @NotNull BiConsumer<R, R> combiner) { R result = supplier.get(); for (Iterable<T> iterable : iterables) { R innerResult = supplier.get(); for (T element : iterable) { accumulator.accept(innerResult, element); } combiner.accept(result, innerResult); } return result; } /** * Collect iterable into a mutable container. * * @param iterable The iterable * @param collector The collector object * @param <T> The type of elements * @param <A> The type of accumulator * @param <R> The return type * @return Collected result * @see Stream#collect(Collector) */ public static <T, A, R> R collect(@NotNull Iterable<T> iterable, @NotNull Collector<? super T, A, R> collector) { A container = collector.supplier().get(); BiConsumer<A, ? super T> accumulator = collector.accumulator(); for (T t : iterable) { accumulator.accept(container, t); } return collector.finisher().apply(container); } /** * Perform a reduction on iterable. * * @param iterable The iterable * @param accumulator The accumulator function * @param <T> The type of elements * @return The reduced result * @see Stream#reduce(BinaryOperator) */ public static <T> Optional<T> reduce(@NotNull Iterable<T> iterable, @NotNull BinaryOperator<T> accumulator) { boolean foundAny = false; T result = null; for (T element : iterable) { if (!foundAny) { foundAny = true; result = element; } else { result = accumulator.apply(result, element); } } return foundAny ? Optional.of(result) : Optional.empty(); } /** * Perform a reduction on an iterable. * * @param iterable The iterable * @param identity The identity to start reduction with * @param accumulator The accumulator function * @param <T> The type of elements * @return The reduced result * @see Stream#reduce(Object, BinaryOperator) */ public static <T> T reduce(@NotNull Iterable<T> iterable, T identity, @NotNull BinaryOperator<T> accumulator) { T result = identity; for (T element : iterable) { result = accumulator.apply(result, element); } return result; } /** * Perform a reduction on an iterable of iterables. * * @param iterables An iterator of iterables. * @param identity The identity to start reduction with * @param accumulator The accumulator function * @param combiner The combiner function * @param <T> The type of elements * @param <U> The reduced type * @return The reduced result * @see Stream#reduce(Object, BiFunction, BinaryOperator) */ public static <T, U> U reduce(@NotNull Iterable<Iterable<T>> iterables, U identity, @NotNull BiFunction<U, ? super T, U> accumulator, @NotNull BinaryOperator<U> combiner) { U result = identity; for (Iterable<T> iterable : iterables) { U innerResult = identity; for (T element : iterable) { innerResult = accumulator.apply(innerResult, element); } result = combiner.apply(result, innerResult); } return result; } /** * Return the first and last elements or {@link Optional#empty()} if {@code Iterables.isEmpty(iterable)}. * * @param iterable The iterable to get the ends from * @param <T> The type of element in the iterable * @return optional {@link Ends} with the first and last of the iterable */ @NotNull public static <T> Optional<Ends<T>> ends(@NotNull Iterable<T> iterable) { return J8Iterators.ends(iterable.iterator()); } /** * Peek at the iterable without modifying the result. * * @param iterable The iterable to peek at * @param consumer The peeking function * @param <T> The type of elements * @return an Iterable that, when traversed will invoke the consumer on each element * @see Stream#peek(Consumer) */ @NotNull public static <T> FluentIterable<T> peek(@NotNull Iterable<T> iterable, @NotNull Consumer<? super T> consumer) { return fromSupplier(() -> new PeekIterator<>(iterable.iterator(), consumer)); } /** * Return a peeking transformer - a UnaryOperator that will send each element to the consumer and return identity. * * @param consumer The peeking function * @param <T> The type of elements * @return a peeking (non-transforming) transformer */ @NotNull public static <T> ConsumingIdentity<T> peeker(@NotNull Consumer<T> consumer) { return new ConsumingIdentity<>(consumer); } /** * Create a one-time Iterable from a Stream. * * @param stream The Stream to use in creating an Iterable * @param <T> The type of elements * @return Iterable from the given stream */ @NotNull public static <T> FluentIterable<T> fromStream(@NotNull Stream<T> stream) { return new StreamIterable<>(stream); } /** * Create a Stream from the given Iterable. * * @param iterable The Iterable to use in creating a Stream * @param <T> The type of elements * @return Stream from the given iterable */ @NotNull public static <T> Stream<T> toStream(@NotNull Iterable<T> iterable) { if (iterable instanceof Collection) { return ((Collection<T>) iterable).stream(); } // TODO(scr): Is it possible to do late-binding (iterable::spliterator)? Need to know characteristics. return StreamSupport.stream(iterable.spliterator(), false); } /** * Return a {@link FluentIterable} that is always empty. * * @param <T> The type of the FluentIterable * @return an empty FluentIterable */ @SuppressWarnings("unchecked") public static <T> FluentIterable<T> emptyIterable() { return (FluentIterable<T>) EMPTY_ITERABLE; } /** * Create a FluentIterable for elements. * * Provides a wrapper to help where {@link FluentIterable} falls short - no varargs static constructor for testing. * * @param elements the elements to iterate over * @param <T> the type of elements * @return a FluentIterable for elements */ @SafeVarargs public static <T> FluentIterable<T> of(T... elements) { return FluentIterable.of(elements); } /** * Reverse the given {@code iterable}. * * @param iterable an iterable to reverse * @param <T> the type of elements * @return an iterable that reverses the navigableSet */ public static <T> FluentIterable<T> reverse(Iterable<? extends T> iterable) { // If it's already reversable, return it. if (iterable instanceof NavigableSet) { @SuppressWarnings("unchecked") NavigableSet<T> navigableSet = (NavigableSet<T>) iterable; return fromSupplier(navigableSet::descendingIterator); } else if (iterable instanceof Deque) { @SuppressWarnings("unchecked") Deque<T> deque = (Deque<T>) iterable; return fromSupplier(deque::descendingIterator); } else if (iterable instanceof List) { @SuppressWarnings("unchecked") List<T> list = (List<T>) iterable; return fromSupplier(() -> J8Iterators.reverse(list.listIterator(list.size()))); } // Slurp everything into a deque and then reverse its order. return fromSupplier(() -> { Deque<T> deque = new ArrayDeque<>(); Iterables.addAll(deque, iterable); return deque.descendingIterator(); }); } /** * Create a {@link FluentIterable} from the given {@link Supplier}. * * @param supplier the supplier * @param <T> the type of elements of the supplied iterable * @return an iterable */ public static <T> SupplierIterable<T> fromSupplier(Supplier<Iterator<? extends T>> supplier) { @SuppressWarnings("unchecked") Supplier<Iterator<T>> tSupplier = (Supplier<Iterator<T>>) (Supplier) supplier; return new SupplierIterable<>(tSupplier); } }
package com.almasb.fxgl.effect; import javafx.geometry.Point2D; import javafx.scene.effect.BlendMode; import javafx.scene.paint.Color; import javafx.util.Duration; import java.util.Random; /** * Holds configuration of predefined particle emitters. * * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com) */ public final class ParticleEmitters { private static final Random random = new Random(); /** * Returns a value in [0..1). * * @return random value between 0 (incl) and 1 (excl) */ private static double rand() { return random.nextDouble(); } /** * Returns a value in [min..max). * * @param min min bounds * @param max max bounds * @return a random value between min (incl) and max (excl) */ private static double rand(double min, double max) { return rand() * (max - min) + min; } /** * @return new emitter with fire configuration */ public static ParticleEmitter newFireEmitter() { ParticleEmitter emitter = new ParticleEmitter(); emitter.setNumParticles(15); emitter.setEmissionRate(0.5); emitter.setColorFunction(() -> Color.rgb(230, 75, 40)); emitter.setSize(9, 12); emitter.setVelocityFunction((i, x, y) -> new Point2D(rand(-0.5, 0.5) * 0.25, rand() * -1)); emitter.setSpawnPointFunction((i, x, y) -> new Point2D(x, y).add(new Point2D(i * (rand() - 0.5), (rand() - 1)))); emitter.setScaleFunction((i, x, y) -> new Point2D(rand(-0.01, 0.01) * 10, rand() * -0.1)); emitter.setExpireFunction((i, x, y) -> Duration.seconds(1)); emitter.setBlendFunction((i, x, y) -> i < emitter.getNumParticles() / 2 ? BlendMode.ADD : BlendMode.COLOR_DODGE); return emitter; } /** * @return new emitter with explosion configuration */ public static ParticleEmitter newExplosionEmitter() { ParticleEmitter emitter = new ParticleEmitter(); emitter.setNumParticles(100); emitter.setEmissionRate(0.0166); emitter.setSize(5, 20); emitter.setSpawnPointFunction((i, x, y) -> new Point2D(x, y)); emitter.setVelocityFunction((i, x, y) -> new Point2D(Math.cos(i), Math.sin(i)).multiply(0.75)); emitter.setScaleFunction((i, x, y) -> new Point2D(rand() * -0.1, rand() * -0.1)); emitter.setExpireFunction((i, x, y) -> Duration.seconds(0.5)); emitter.setColorFunction(() -> Color.rgb((int) rand(200, 255), 30, 20)); emitter.setBlendFunction((i, x, y) -> i < emitter.getNumParticles() / 2 ? BlendMode.ADD : BlendMode.COLOR_BURN); return emitter; } /** * @return new emitter with implosion configuration */ public static ParticleEmitter newImplosionEmitter() { ParticleEmitter emitter = new ParticleEmitter(); emitter.setNumParticles(100); emitter.setEmissionRate(0.0166); emitter.setSize(5, 20); emitter.setSpawnPointFunction((i, x, y) -> { Point2D vector = new Point2D(Math.cos(i), Math.sin(i)); return new Point2D(x, y).add(vector.multiply(25)); }); emitter.setVelocityFunction((i, x, y) -> { Point2D vector = new Point2D(Math.cos(i), Math.sin(i)); Point2D newPos = new Point2D(x, y).add(vector.multiply(25)); return newPos.subtract(new Point2D(x, y)).multiply(-0.05); }); emitter.setScaleFunction((i, x, y) -> new Point2D(rand() * -0.1, rand() * -0.1)); emitter.setExpireFunction((i, x, y) -> Duration.seconds(0.5)); emitter.setColorFunction(() -> Color.rgb((int) rand(200, 255), 30, 20)); emitter.setBlendFunction((i, x, y) -> i < emitter.getNumParticles() / 2 ? BlendMode.ADD : BlendMode.COLOR_DODGE); return emitter; } /** * @return new emitter with sparks configuration */ public static ParticleEmitter newSparkEmitter() { ParticleEmitter emitter = new ParticleEmitter(); emitter.setNumParticles(30); emitter.setEmissionRate(0.0166 / 2); emitter.setSize(1, 2); emitter.setSpawnPointFunction((i, x, y) -> new Point2D(x, y)); emitter.setVelocityFunction((i, x, y) -> new Point2D(rand(-1, 1), rand(-6, -5)).multiply(0.1)); emitter.setGravityFunction(() -> new Point2D(0, rand(0.01, 0.015))); emitter.setExpireFunction((i, x, y) -> Duration.seconds(2)); emitter.setColorFunction(() -> Color.rgb(30, 35, (int) rand(200, 255))); return emitter; } /** * @return new emitter with smoke configuration */ public static ParticleEmitter newSmokeEmitter() { ParticleEmitter emitter = new ParticleEmitter(); emitter.setNumParticles(5); emitter.setEmissionRate(1); emitter.setSize(9, 10); emitter.setSpawnPointFunction((i, x, y) -> new Point2D(x, y).add(rand(-1, 1), 0)); emitter.setVelocityFunction((i, x, y) -> new Point2D((rand() * 0.1), 0)); emitter.setGravityFunction(() -> new Point2D(0, rand() * -0.03)); emitter.setExpireFunction((i, x, y) -> Duration.seconds(rand(1, 3))); emitter.setColorFunction(() -> Color.rgb(230, 230, 230)); emitter.setScaleFunction((i, x, y) -> new Point2D(-0.01, -0.05)); return emitter; } /** * @param width width of the rain wall * @return new emitter with rain configuration */ public static ParticleEmitter newRainEmitter(int width) { ParticleEmitter emitter = new ParticleEmitter(); emitter.setNumParticles(5); emitter.setEmissionRate(1); emitter.setSize(6, 7); emitter.setSpawnPointFunction((i, x, y) -> new Point2D(rand()*width + x, -25 + y)); emitter.setVelocityFunction((i, x, y) -> new Point2D(0, (rand() * 15))); emitter.setGravityFunction(() -> new Point2D(0, rand() * 0.03)); emitter.setExpireFunction((i, x, y) -> Duration.seconds(rand(1, 3))); emitter.setScaleFunction((i, x, y) -> new Point2D(-0.02, 0)); emitter.setBlendFunction((i, x, y) -> BlendMode.SRC_OVER); return emitter; } }
// package package org.mskcc.cbio.importer.converter.internal; // imports import org.mskcc.cbio.importer.Config; import org.mskcc.cbio.importer.CaseIDs; import org.mskcc.cbio.importer.IDMapper; import org.mskcc.cbio.importer.Converter; import org.mskcc.cbio.importer.FileUtils; import org.mskcc.cbio.importer.DatabaseUtils; import org.mskcc.cbio.importer.model.ImportDataRecord; import org.mskcc.cbio.importer.model.PortalMetadata; import org.mskcc.cbio.importer.model.DataMatrix; import org.mskcc.cbio.importer.model.DatatypeMetadata; import org.mskcc.cbio.importer.model.DataSourcesMetadata; import org.mskcc.cbio.importer.model.CaseListMetadata; import org.mskcc.cbio.importer.model.CancerStudyMetadata; import org.mskcc.cbio.importer.dao.ImportDataRecordDAO; import org.mskcc.cbio.importer.util.ClassLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Vector; import java.util.Collection; import java.util.LinkedHashSet; import java.io.File; /** * Class which implements the Converter interface. */ class ConverterImpl implements Converter { // all cases indicator private static final String ALL_CASES_FILENAME = "cases_all.txt"; // our logger private static final Log LOG = LogFactory.getLog(ConverterImpl.class); // ref to configuration private Config config; // ref to file utils private FileUtils fileUtils; // ref to import data private ImportDataRecordDAO importDataRecordDAO; // ref to caseids private CaseIDs caseIDs; // ref to IDMapper private IDMapper idMapper; /** * Constructor. * * @param config Config * @param fileUtils FileUtils * @param importDataRecordDAO ImportDataRecordDAO; * @param caseIDs CaseIDs; * @param idMapper IDMapper */ public ConverterImpl(Config config, FileUtils fileUtils, ImportDataRecordDAO importDataRecordDAO, CaseIDs caseIDs, IDMapper idMapper) throws Exception { // set members this.config = config; this.fileUtils = fileUtils; this.importDataRecordDAO = importDataRecordDAO; this.caseIDs = caseIDs; this.idMapper = idMapper; } /** * Converts data for the given portal. * * @param portal String * @param applyOverrides Boolean * @throws Exception */ @Override public void convertData(String portal, Boolean applyOverrides) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("convertData(), portal: " + portal); LOG.info("convertData(), applyOverrides: " + applyOverrides); } // check args if (portal == null) { throw new IllegalArgumentException("portal must not be null"); } // get portal metadata PortalMetadata portalMetadata = config.getPortalMetadata(portal).iterator().next(); if (portalMetadata == null) { if (LOG.isInfoEnabled()) { LOG.info("convertData(), cannot find PortalMetadata, returning"); } return; } // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // create cancer study metadata file // note - we call this again after we compute the number of cases fileUtils.writeCancerStudyMetadataFile(portalMetadata, cancerStudyMetadata, -1); // iterate over all datatypes for (DatatypeMetadata datatypeMetadata : config.getDatatypeMetadata(portalMetadata, cancerStudyMetadata)) { // get DataMatrices (may be multiple in the case of methylation, median zscores, gistic-genes DataMatrix[] dataMatrices = getDataMatrices(portalMetadata, cancerStudyMetadata, datatypeMetadata, applyOverrides); if (dataMatrices == null || dataMatrices.length == 0) { if (LOG.isInfoEnabled()) { LOG.info("convertData(), no dataMatrices to process, skipping."); } continue; } // get converter and create staging file Object[] args = { config, fileUtils, caseIDs, idMapper }; Converter converter = (Converter)ClassLoader.getInstance(datatypeMetadata.getConverterClassName(), args); converter.createStagingFile(portalMetadata, cancerStudyMetadata, datatypeMetadata, dataMatrices); } } } /** * Generates case lists for the given portal. * * @param portal String * @throws Exception */ @Override public void generateCaseLists(String portal) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists()"); } // check args if (portal == null) { throw new IllegalArgumentException("portal must not be null"); } // get portal metadata PortalMetadata portalMetadata = config.getPortalMetadata(portal).iterator().next(); if (portalMetadata == null) { if (LOG.isInfoEnabled()) { LOG.info("convertData(), cannot find PortalMetadata, returning"); } return; } // get CaseListMetadata Collection<CaseListMetadata> caseListMetadatas = config.getCaseListMetadata(Config.ALL); // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // iterate over case lists for (CaseListMetadata caseListMetadata : caseListMetadatas) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processing cancer study: " + cancerStudyMetadata + ", case list: " + caseListMetadata.getCaseListFilename()); } // how many staging files are we working with? String[] stagingFilenames = null; // union (all cases) if (caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_UNION_DELIMITER)) { stagingFilenames = caseListMetadata.getStagingFilenames().split("\\" + CaseListMetadata.CASE_LIST_UNION_DELIMITER); } // intersection (like all complete or all cna & seq) else if (caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER)) { stagingFilenames = caseListMetadata.getStagingFilenames().split("\\" + CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER); } // just a single staging file else { stagingFilenames = new String[] { caseListMetadata.getStagingFilenames() }; } if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), stagingFilenames: " + java.util.Arrays.toString(stagingFilenames)); } // this is the set we will pass to writeCaseListFile LinkedHashSet<String> caseSet = new LinkedHashSet<String>(); for (String stagingFilename : stagingFilenames) { // compute the case set LinkedHashSet<String> thisSet = new LinkedHashSet<String>(); String[] stagingFileHeader = fileUtils.getStagingFileHeader(portalMetadata, cancerStudyMetadata, stagingFilename).split(CASE_DELIMITER); // we may not have this datatype in study if (stagingFileHeader.length == 0) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), stagingFileHeader is empty: " + stagingFilename + ", skipping..."); } continue; } // filter out column headings that are not case ids (like gene symbol or gene id) if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), filtering case ids..."); } for (String caseID : stagingFileHeader) { if (caseIDs.isTumorCaseID(caseID)) { thisSet.add(caseID); } } if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), filtering case ids complete, " + thisSet.size() + " remaining case ids..."); } // if intersection if (caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER)) { caseSet.retainAll(thisSet); } // otherwise union else { caseSet.addAll(thisSet); } } // write the case list file (don't make empty case lists) if (caseSet.size() > 0) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), calling writeCaseListFile()..."); } fileUtils.writeCaseListFile(portalMetadata, cancerStudyMetadata, caseListMetadata, caseSet.toArray(new String[0])); } else if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), caseSet.size() <= 0, skipping call to writeCaseListFile()..."); } // if union, write out the cancer study metadata file if (caseSet.size() > 0 && caseListMetadata.getCaseListFilename().equals(ALL_CASES_FILENAME)) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processed all cases list, we can now update cancerStudyMetadata file()..."); } fileUtils.writeCancerStudyMetadataFile(portalMetadata, cancerStudyMetadata, caseSet.size()); } } } } /** * Applies overrides to the given portal using the given data source. * * @param portal String * @throws Exception */ @Override public void applyOverrides(String portal) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("applyOverrides(), portal: " + portal); } // check args if (portal == null) { throw new IllegalArgumentException("portal must not be null"); } // get portal metadata PortalMetadata portalMetadata = config.getPortalMetadata(portal).iterator().next(); if (portalMetadata == null) { if (LOG.isInfoEnabled()) { LOG.info("applyOverrides(), cannot find PortalMetadata, returning"); } return; } // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // iterate over all datatypes for (DatatypeMetadata datatypeMetadata : config.getDatatypeMetadata(portalMetadata, cancerStudyMetadata)) { // apply staging override String stagingFilename = datatypeMetadata.getStagingFilename().replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); fileUtils.applyOverride(portalMetadata, cancerStudyMetadata, stagingFilename); // apply metadata override if (datatypeMetadata.requiresMetafile()) { fileUtils.applyOverride(portalMetadata, cancerStudyMetadata, datatypeMetadata.getMetaFilename()); } } // case lists fileUtils.applyOverride(portalMetadata, cancerStudyMetadata, "case_lists"); } } /** * Creates a staging file from the given import data. * * @param portalMetadata PortalMetadata * @param cancerStudyMetadata CancerStudyMetadata * @param datatypeMetadata DatatypeMetadata * @param dataMatrices DataMatrix[] * @throws Exception */ @Override public void createStagingFile(PortalMetadata portalMetadata, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DataMatrix[] dataMatrices) throws Exception { throw new UnsupportedOperationException(); } /** * Helper function to get DataMatrix[] array. * - may return null. * * @param portalMetadata PortalMetadata * @param cancerStudyMetadata CancerStudyMetadata * @param datatypeMetadata DatatypeMetadata * @param applyOverrides Boolean * @return DataMatrix[] * @throws Exception */ private DataMatrix[] getDataMatrices(PortalMetadata portalMetadata, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, Boolean applyOverrides) throws Exception { // this is what we are returing Vector<DataMatrix> toReturn = new Vector<DataMatrix>(); // the data type we are interested in... String datatype = datatypeMetadata.getDatatype(); if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), looking for all ImportDataRecord matching: " + cancerStudyMetadata.getTumorType() + ":" + datatype + ":" + cancerStudyMetadata.getCenter() + "."); } Collection<ImportDataRecord> importDataRecords = importDataRecordDAO.getImportDataRecordByTumorTypeAndDatatypeAndCenter(cancerStudyMetadata.getTumorType(), datatype, cancerStudyMetadata.getCenter()); if (importDataRecords.size() > 0) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), found " + importDataRecords.size() + " ImportDataRecord objects matching: " + cancerStudyMetadata.getTumorType() + ":" + datatype + ":" + cancerStudyMetadata.getCenter() + "."); } for (ImportDataRecord importData : importDataRecords) { // do we have to check for an override file? if (applyOverrides) { String dataFilename = importData.getDataFilename().replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG, cancerStudyMetadata.getTumorType()); File overrideFile = fileUtils.getOverrideFile(portalMetadata, cancerStudyMetadata, dataFilename); if (overrideFile != null) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), found an override file for: " + cancerStudyMetadata.toString() + ", datatype: " + datatype + ": " + overrideFile.getCanonicalPath()); } // if an override file does exist, lets replace canonical path in importData importData.setCanonicalPathToData(overrideFile.getCanonicalPath()); } } toReturn.add(fileUtils.getFileContents(importData)); } } else if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), cannot find any ImportDataRecord objects matching: " + cancerStudyMetadata.getTumorType() + ":" + datatype + ":" + cancerStudyMetadata.getCenter() + "."); } // outta here return toReturn.toArray(new DataMatrix[0]); } }
package com.gitrekt.resort.model.entities; import java.util.Objects; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Room { @Id private String roomNumber; @ManyToOne(cascade = CascadeType.ALL) private RoomCategory roomCategory; /** * DO NOT CALL THIS CONSTRUCTOR. IT EXISTS ONLY BECAUSE IT IS REQUIRED BY * HIBERNATE. */ Room() { // REQUIRED BY HIBERNATE } public Room(String roomNumber, RoomCategory roomCategory) { this.roomNumber = roomNumber; this.roomCategory = roomCategory; } public String getRoomNumber() { return roomNumber; } public RoomCategory getRoomCategory() { return roomCategory; } @Override public int hashCode() { int hash = 7; hash = 17 * hash + Objects.hashCode(this.roomNumber); hash = 17 * hash + Objects.hashCode(this.roomCategory); return hash; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } final Room other = (Room) obj; if(!Objects.equals(this.roomNumber, other.roomNumber)) { return false; } if(!Objects.equals(this.roomCategory, other.roomCategory)) { return false; } return true; } }
// package package org.mskcc.cbio.importer.converter.internal; // imports import org.mskcc.cbio.importer.Admin; import org.mskcc.cbio.importer.Config; import org.mskcc.cbio.importer.CaseIDs; import org.mskcc.cbio.importer.IDMapper; import org.mskcc.cbio.importer.Converter; import org.mskcc.cbio.importer.FileUtils; import org.mskcc.cbio.importer.DatabaseUtils; import org.mskcc.cbio.importer.model.ImportDataRecord; import org.mskcc.cbio.importer.model.PortalMetadata; import org.mskcc.cbio.importer.model.DataMatrix; import org.mskcc.cbio.importer.model.DatatypeMetadata; import org.mskcc.cbio.importer.model.DataSourcesMetadata; import org.mskcc.cbio.importer.model.CaseListMetadata; import org.mskcc.cbio.importer.model.CancerStudyMetadata; import org.mskcc.cbio.importer.dao.ImportDataRecordDAO; import org.mskcc.cbio.importer.util.ClassLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Date; import java.util.List; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.io.File; /** * Class which implements the Converter interface. */ class ConverterImpl implements Converter { // all cases indicator private static final String ALL_CASES_FILENAME = "cases_all.txt"; // our logger private static final Log LOG = LogFactory.getLog(ConverterImpl.class); // ref to configuration private Config config; // ref to file utils private FileUtils fileUtils; // ref to import data private ImportDataRecordDAO importDataRecordDAO; // ref to caseids private CaseIDs caseIDs; // ref to IDMapper private IDMapper idMapper; /** * Constructor. * * @param config Config * @param fileUtils FileUtils * @param importDataRecordDAO ImportDataRecordDAO; * @param caseIDs CaseIDs; * @param idMapper IDMapper */ public ConverterImpl(Config config, FileUtils fileUtils, ImportDataRecordDAO importDataRecordDAO, CaseIDs caseIDs, IDMapper idMapper) throws Exception { // set members this.config = config; this.fileUtils = fileUtils; this.importDataRecordDAO = importDataRecordDAO; this.caseIDs = caseIDs; this.idMapper = idMapper; } /** * Converts data for the given portal. * * @param portal String * @param runDate String * @param applyOverrides Boolean * @throws Exception */ @Override public void convertData(String portal, String runDate, Boolean applyOverrides) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("convertData(), portal: " + portal); LOG.info("convertData(), runDate: " + runDate); LOG.info("convertData(), applyOverrides: " + applyOverrides); } // check args if (portal == null) { throw new IllegalArgumentException("portal must not be null"); } // get portal metadata PortalMetadata portalMetadata = config.getPortalMetadata(portal).iterator().next(); if (portalMetadata == null) { if (LOG.isInfoEnabled()) { LOG.info("convertData(), cannot find PortalMetadata, returning"); } return; } // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // iterate over all datatypes boolean createCancerStudyMetadataFile = false; for (DatatypeMetadata datatypeMetadata : config.getDatatypeMetadata(portalMetadata, cancerStudyMetadata)) { // get DataMatrices (may be multiple in the case of methylation, median zscores, gistic-genes DataMatrix[] dataMatrices = getDataMatrices(portalMetadata, cancerStudyMetadata, datatypeMetadata, runDate, applyOverrides); if (dataMatrices == null || dataMatrices.length == 0) { if (LOG.isInfoEnabled()) { LOG.info("convertData(), no dataMatrices to process, skipping."); } continue; } // we have at least 1 data matrix, we will need to create a cancer study metadata file createCancerStudyMetadataFile = true; // get converter and create staging file Object[] args = { config, fileUtils, caseIDs, idMapper }; Converter converter = (Converter)ClassLoader.getInstance(datatypeMetadata.getConverterClassName(), args); converter.createStagingFile(portalMetadata, cancerStudyMetadata, datatypeMetadata, dataMatrices); } if (createCancerStudyMetadataFile) { // create cancer study metadata file // note - we call this again after we compute the number of cases fileUtils.writeCancerStudyMetadataFile(portalMetadata, cancerStudyMetadata, -1); } } } /** * Generates case lists for the given portal. * * @param portal String * @throws Exception */ @Override public void generateCaseLists(String portal) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists()"); } // check args if (portal == null) { throw new IllegalArgumentException("portal must not be null"); } // get portal metadata PortalMetadata portalMetadata = config.getPortalMetadata(portal).iterator().next(); if (portalMetadata == null) { if (LOG.isInfoEnabled()) { LOG.info("convertData(), cannot find PortalMetadata, returning"); } return; } // get CaseListMetadata Collection<CaseListMetadata> caseListMetadatas = config.getCaseListMetadata(Config.ALL); // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // iterate over case lists for (CaseListMetadata caseListMetadata : caseListMetadatas) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processing cancer study: " + cancerStudyMetadata + ", case list: " + caseListMetadata.getCaseListFilename()); } // how many staging files are we working with? String[] stagingFilenames = null; // union (all cases) if (caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_UNION_DELIMITER)) { stagingFilenames = caseListMetadata.getStagingFilenames().split("\\" + CaseListMetadata.CASE_LIST_UNION_DELIMITER); } // intersection (like all complete or all cna & seq) else if (caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER)) { stagingFilenames = caseListMetadata.getStagingFilenames().split("\\" + CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER); } // just a single staging file else { stagingFilenames = new String[] { caseListMetadata.getStagingFilenames() }; } if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), stagingFilenames: " + java.util.Arrays.toString(stagingFilenames)); } // this is the set we will pass to writeCaseListFile LinkedHashSet<String> caseSet = new LinkedHashSet<String>(); for (String stagingFilename : stagingFilenames) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processing stagingFile: " + stagingFilename); } // compute the case set List<String> caseList = fileUtils.getCaseListFromStagingFile(caseIDs, portalMetadata, cancerStudyMetadata, stagingFilename); // we may not have this datatype in study if (caseList.size() == 0) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), stagingFileHeader is empty: " + stagingFilename + ", skipping..."); } continue; } // if intersection if (caseListMetadata.getStagingFilenames().contains(CaseListMetadata.CASE_LIST_INTERSECTION_DELIMITER)) { if (caseSet.isEmpty()) { caseSet.addAll(caseList); } else { caseSet.retainAll(caseList); } } // otherwise union else { caseSet.addAll(caseList); } } // write the case list file (don't make empty case lists) if (caseSet.size() > 0) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), calling writeCaseListFile()..."); } fileUtils.writeCaseListFile(portalMetadata, cancerStudyMetadata, caseListMetadata, caseSet.toArray(new String[0])); } else if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), caseSet.size() <= 0, skipping call to writeCaseListFile()..."); } // if union, write out the cancer study metadata file if (caseSet.size() > 0 && caseListMetadata.getCaseListFilename().equals(ALL_CASES_FILENAME)) { if (LOG.isInfoEnabled()) { LOG.info("generateCaseLists(), processed all cases list, we can now update cancerStudyMetadata file()..."); } fileUtils.writeCancerStudyMetadataFile(portalMetadata, cancerStudyMetadata, caseSet.size()); } } } } /** * Applies overrides to the given portal using the given data source. * * @param portal String * @throws Exception */ @Override public void applyOverrides(String portal) throws Exception { if (LOG.isInfoEnabled()) { LOG.info("applyOverrides(), portal: " + portal); } // check args if (portal == null) { throw new IllegalArgumentException("portal must not be null"); } // get portal metadata PortalMetadata portalMetadata = config.getPortalMetadata(portal).iterator().next(); if (portalMetadata == null) { if (LOG.isInfoEnabled()) { LOG.info("applyOverrides(), cannot find PortalMetadata, returning"); } return; } // iterate over all cancer studies for (CancerStudyMetadata cancerStudyMetadata : config.getCancerStudyMetadata(portalMetadata.getName())) { // iterate over all datatypes for (DatatypeMetadata datatypeMetadata : config.getDatatypeMetadata(portalMetadata, cancerStudyMetadata)) { // apply staging override String stagingFilename = datatypeMetadata.getStagingFilename().replaceAll(DatatypeMetadata.CANCER_STUDY_TAG, cancerStudyMetadata.toString()); fileUtils.applyOverride(portalMetadata, cancerStudyMetadata, stagingFilename, stagingFilename); // apply metadata override if (datatypeMetadata.requiresMetafile()) { fileUtils.applyOverride(portalMetadata, cancerStudyMetadata, datatypeMetadata.getMetaFilename(), datatypeMetadata.getMetaFilename()); } } // case lists fileUtils.applyOverride(portalMetadata, cancerStudyMetadata, "case_lists", "case_lists"); } } /** * Creates a staging file from the given import data. * * @param portalMetadata PortalMetadata * @param cancerStudyMetadata CancerStudyMetadata * @param datatypeMetadata DatatypeMetadata * @param dataMatrices DataMatrix[] * @throws Exception */ @Override public void createStagingFile(PortalMetadata portalMetadata, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, DataMatrix[] dataMatrices) throws Exception { throw new UnsupportedOperationException(); } /** * Helper function to get DataMatrix[] array. * - may return null. * * @param portalMetadata PortalMetadata * @param cancerStudyMetadata CancerStudyMetadata * @param datatypeMetadata DatatypeMetadata * @param runDate String * @param applyOverrides Boolean * @return DataMatrix[] * @throws Exception */ private DataMatrix[] getDataMatrices(PortalMetadata portalMetadata, CancerStudyMetadata cancerStudyMetadata, DatatypeMetadata datatypeMetadata, String runDate, Boolean applyOverrides) throws Exception { // this is what we are returing List<DataMatrix> toReturn = new ArrayList<DataMatrix>(); // the data type we are interested in... String datatype = datatypeMetadata.getDatatype(); if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), looking for all ImportDataRecord matching: " + cancerStudyMetadata.getTumorType() + ":" + datatype + ":" + cancerStudyMetadata.getCenter() + "."); } Collection<ImportDataRecord> importDataRecords = importDataRecordDAO.getImportDataRecordByTumorTypeAndDatatypeAndCenterAndRunDate(cancerStudyMetadata.getTumorType(), datatype, cancerStudyMetadata.getCenter(), runDate); if (importDataRecords.size() > 0) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), found " + importDataRecords.size() + " ImportDataRecord objects matching: " + cancerStudyMetadata.getTumorType() + ":" + datatype + ":" + cancerStudyMetadata.getCenter() + "."); } for (ImportDataRecord importData : importDataRecords) { // do we have to check for an override file? if (applyOverrides) { String dataFilename = importData.getDataFilename().replaceAll(DatatypeMetadata.TUMOR_TYPE_TAG, cancerStudyMetadata.getTumorType().toUpperCase()); File overrideFile = fileUtils.getOverrideFile(portalMetadata, cancerStudyMetadata, dataFilename); if (overrideFile != null) { if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), found an override file for: " + cancerStudyMetadata.toString() + ", datatype: " + datatype + ": " + overrideFile.getCanonicalPath()); } // if an override file does exist, lets replace canonical path in importData importData.setCanonicalPathToData(overrideFile.getCanonicalPath()); } } toReturn.add(fileUtils.getFileContents(importData)); } } else if (LOG.isInfoEnabled()) { LOG.info("getDataMatrices(), cannot find any ImportDataRecord objects matching: " + cancerStudyMetadata.getTumorType() + ":" + datatype + ":" + cancerStudyMetadata.getCenter() + "."); } // outta here return toReturn.toArray(new DataMatrix[0]); } }
package de.saumya.mojo.gem; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.io.ModelReader; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import de.saumya.mojo.ruby.gems.GemException; import de.saumya.mojo.ruby.script.ScriptException; import org.apache.maven.project.MavenProject; /** * installs a set of given gems without resolving any transitive dependencies */ @Mojo( name = "sets", defaultPhase = LifecyclePhase.INITIALIZE ) public class SetsMojo extends AbstractGemMojo { /** * the scope under which the gems get installed */ @Parameter( defaultValue = "compile" ) protected String scope; /** * map of gemname to version, i.e. it is a "list" of gems with fixed version */ @Parameter protected Map<String, String> gems = Collections.emptyMap(); @Component protected ModelReader reader; protected void executeWithGems() throws MojoExecutionException, ScriptException, IOException, GemException { List<Artifact> gems = new LinkedList<Artifact>(); Set<Artifact> jars = new LinkedHashSet<Artifact>(); for( Map.Entry<String, String> gem : this.gems.entrySet() ) { Set<Artifact> set = manager.resolve( manager.createGemArtifact( gem.getKey(), gem.getValue() ), localRepository, project.getRemoteArtifactRepositories() ); if ( set.size() == 1 ) { Artifact artifact = set.iterator().next(); artifact.setScope(scope); gems.add(artifact); collectJarDependencies(jars, artifact); } else if ( set.size() > 1 ) { getLog().error( "found more then one artifact for given version: " + gem.getKey() + " " + gem.getValue() ); } } resolveJarDepedencies(jars); installGems(gems); } private void installGems(List<Artifact> gems) throws IOException, ScriptException, GemException { project.getArtifacts().addAll(gems); File home = gemsConfig.getGemHome(); // use gemHome as base for other gems installation directories String base = this.gemsConfig.getGemHome() != null ? this.gemsConfig.getGemHome().getAbsolutePath() : (project.getBuild().getDirectory() + "/rubygems"); try { final File gemHome; if ( "test".equals( scope ) || "provided".equals( scope ) ) { gemHome = gemHome( base, scope); } else { gemHome = new File( base ); } this.gemsConfig.setGemHome(gemHome); this.gemsConfig.addGemPath(gemHome); getLog().info( "installing gem sets for " + scope + " scope into " + gemHome.getAbsolutePath().replace(project.getBasedir().getAbsolutePath() + File.separatorChar, "") ); gemsInstaller.installGems( project, gems, null, (List<ArtifactRepository>) null); } finally { // reset old gem home again this.gemsConfig.setGemHome(home); } } private void collectJarDependencies(Set<Artifact> jars, Artifact artifact) throws GemException, IOException { Set<Artifact> set = manager.resolve(manager.createArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), "pom"), localRepository, project.getRemoteArtifactRepositories()); Model pom = reader.read(set.iterator().next().getFile(), null); for( Dependency dependency : pom.getDependencies() ){ if (!dependency.getType().equals("gem")) { if (dependency.getScope() == null || dependency.getScope().equals("compile") || dependency.equals("runtime")) { jars.add(manager.createArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getClassifier(), dependency.getType())); } } } } private void resolveJarDepedencies(Set<Artifact> jars) { ArtifactResolutionRequest req = new ArtifactResolutionRequest() .setArtifact(project.getArtifact()) .setResolveRoot(false) .setArtifactDependencies(jars) .setResolveTransitively(true) .setLocalRepository(localRepository) .setRemoteRepositories(project.getRemoteArtifactRepositories()); Set<Artifact> resolvedArtifacts = this.repositorySystem.resolve(req).getArtifacts(); for( Artifact artifact : resolvedArtifacts ){ artifact.setScope(scope); } project.setResolvedArtifacts(resolvedArtifacts); } }
package com.gmail.trentech.simpletags.tags; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.spongepowered.api.Sponge; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.serializer.TextSerializers; import com.gmail.trentech.simpletags.events.ChangeTagEvent; import com.gmail.trentech.simpletags.utils.SQLUtils; public class Tag extends SQLUtils { private String name; private final String type; private Text tag; protected Tag(String name, Class<? extends Tag> type, String tag) { this.name = name; this.type = type.getSimpleName(); this.tag = TextSerializers.FORMATTING_CODE.deserialize(tag); if (!exists()) { create(); } else { update(); } } protected Tag(Tag tag) { this.name = tag.getName(); this.type = tag.getType(); this.tag = tag.getTag(); } public String getName() { return name; } public Text getTag() { return tag; } public void setTag(String tag) { if (tag == null) { delete(); } else { this.tag = TextSerializers.FORMATTING_CODE.deserialize(tag); update(); } } private String getType() { return type; } private void create() { try { Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT into " + getType() + " (Name, Tag) VALUES (?, ?)"); statement.setString(1, getName()); statement.setString(2, TextSerializers.FORMATTING_CODE.serialize(getTag())); statement.executeUpdate(); connection.close(); Sponge.getEventManager().post(new ChangeTagEvent.Update(this)); } catch (SQLException e) { e.printStackTrace(); } } private void update() { try { Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE " + getType() + " SET Tag = ? WHERE Name = ?"); statement.setString(1, TextSerializers.FORMATTING_CODE.serialize(getTag())); statement.setString(2, getName()); statement.executeUpdate(); connection.close(); Sponge.getEventManager().post(new ChangeTagEvent.Update(this)); } catch (SQLException e) { e.printStackTrace(); } } private void delete() { try { Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE from " + getType() + " WHERE Name = ?"); statement.setString(1, getName()); statement.executeUpdate(); connection.close(); Sponge.getEventManager().post(new ChangeTagEvent.Delete(this)); } catch (SQLException e) { e.printStackTrace(); } } private boolean exists() { try { Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + getType()); ResultSet result = statement.executeQuery(); while (result.next()) { if (result.getString("Name").equals(getName())) { connection.close(); return true; } } connection.close(); } catch (SQLException e) { e.printStackTrace(); } return false; } protected static Optional<Tag> get(Class<? extends Tag> clazz, String name) { String type = clazz.getSimpleName(); try { Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + type); ResultSet result = statement.executeQuery(); while (result.next()) { String uuid = result.getString("Name"); if (uuid.equals(name)) { connection.close(); return Optional.of(new Tag(uuid, clazz, result.getString("Tag"))); } } connection.close(); } catch (SQLException e) { e.printStackTrace(); } return Optional.empty(); } protected static List<Tag> getAll(Class<? extends Tag> clazz) { String type = clazz.getSimpleName(); List<Tag> list = new ArrayList<>(); try { Connection connection = getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + type); ResultSet result = statement.executeQuery(); while (result.next()) { String name = result.getString("Name"); String tag = result.getString("Tag"); list.add(new Tag(name, clazz, tag)); } connection.close(); } catch (SQLException e) { e.printStackTrace(); } return list; } }
package org.TexasTorque.TexasTorque2013.io; import edu.wpi.first.wpilibj.AnalogChannel; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Gyro; import org.TexasTorque.TexasTorque2013.constants.Ports; public class SensorInput { private static SensorInput instance; private Encoder leftDriveEncoder; private Encoder rightDriveEncoder; private AnalogChannel gyroChannel; private Gyro gyro; public SensorInput() { leftDriveEncoder = new Encoder(Ports.SIDECAR_ONE, Ports.LEFT_DRIVE_ENCODER_A_PORT, Ports.SIDECAR_ONE, Ports.LEFT_DRIVE_ENCODER_B_PORT, true); rightDriveEncoder = new Encoder(Ports.SIDECAR_ONE, Ports.RIGHT_DRIVE_ENCODER_A_PORT, Ports.SIDECAR_ONE, Ports.RIGHT_DRIVE_ENCODER_B_PORT, false); gyroChannel = new AnalogChannel(Ports.GYRO_PORT); gyro = new Gyro(gyroChannel); leftDriveEncoder.start(); rightDriveEncoder.start(); } public synchronized static SensorInput getInstance() { return (instance == null) ? instance = new SensorInput() : instance; } public synchronized void resetEncoders() { leftDriveEncoder.reset(); rightDriveEncoder.reset(); } public synchronized int getLeftDriveEncoder() { return leftDriveEncoder.get(); } public synchronized int getRightDriveEncoder() { return rightDriveEncoder.get(); } }
package info.limpet.stackedcharts.ui.view; import info.limpet.stackedcharts.model.AbstractAnnotation; import info.limpet.stackedcharts.model.AxisDirection; import info.limpet.stackedcharts.model.AxisType; import info.limpet.stackedcharts.model.Chart; import info.limpet.stackedcharts.model.ChartSet; import info.limpet.stackedcharts.model.DataItem; import info.limpet.stackedcharts.model.Dataset; import info.limpet.stackedcharts.model.Datum; import info.limpet.stackedcharts.model.DependentAxis; import info.limpet.stackedcharts.model.IndependentAxis; import info.limpet.stackedcharts.model.LineType; import info.limpet.stackedcharts.model.MarkerStyle; import info.limpet.stackedcharts.model.Orientation; import info.limpet.stackedcharts.model.PlainStyling; import info.limpet.stackedcharts.model.SelectiveAnnotation; import info.limpet.stackedcharts.model.Styling; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.impl.AdapterImpl; import org.eclipse.emf.common.util.EList; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.general.Series; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.ui.Layer; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RectangleInsets; import org.jfree.ui.TextAnchor; import org.jfree.util.ShapeUtilities; public class ChartBuilder { /** * helper class that can handle either temporal or non-temporal datasets * * @author ian * */ private static interface ChartHelper { /** * add this item to this series * * @param series * @param item */ void addItem(Series series, DataItem item); /** * clear the contents of the series * */ void clear(Series series); /** * create the correct type of axis * * @param name * @return */ ValueAxis createAxis(String name); /** * create a new collection of datasets (seroes) * * @return */ XYDataset createCollection(); /** * create a series with the specified name * * @param name * @return */ Series createSeries(String name); /** * put the series into the collection * * @param collection * @param series */ void storeSeries(XYDataset collection, Series series); } /** * support generation of a stacked chart with a shared time axis * * @author ian * */ private static class DateHelper implements ChartHelper { @Override public void addItem(final Series series, final DataItem item) { final TimeSeries ns = (TimeSeries) series; final long time = (long) item.getIndependentVal(); final Millisecond milli = new Millisecond(new Date(time)); ns.add(milli, item.getDependentVal()); } @Override public void clear(final Series series) { final TimeSeries ns = (TimeSeries) series; ns.clear(); } @Override public ValueAxis createAxis(final String name) { return new DateAxis(name); } @Override public XYDataset createCollection() { return new TimeSeriesCollection(); } @Override public Series createSeries(final String name) { return new TimeSeries(name); } @Override public void storeSeries(final XYDataset collection, final Series series) { final TimeSeriesCollection cc = (TimeSeriesCollection) collection; cc.addSeries((TimeSeries) series); } } /** * support generation of a stacked chart with a shared number axis * * @author ian * */ private static class NumberHelper implements ChartHelper { @Override public void addItem(final Series series, final DataItem item) { final XYSeries ns = (XYSeries) series; ns.add(item.getIndependentVal(), item.getDependentVal()); } @Override public void clear(final Series series) { final XYSeries ns = (XYSeries) series; ns.clear(); } @Override public ValueAxis createAxis(final String name) { return new NumberAxis(name); } @Override public XYDataset createCollection() { return new XYSeriesCollection(); } @Override public Series createSeries(final String name) { return new XYSeries(name); } @Override public void storeSeries(final XYDataset collection, final Series series) { final XYSeriesCollection cc = (XYSeriesCollection) collection; cc.addSeries((XYSeries) series); } } /** * * @param subplot * target plot for annotation * @param annotations * annotation list to be added to plot eg: Marker,Zone * @param isRangeAnnotation * is annotation added to Range or Domain */ private static void addAnnotationToPlot(final XYPlot subplot, final List<AbstractAnnotation> annotations, final boolean isRangeAnnotation) { for (final AbstractAnnotation annotation : annotations) { final Color color = annotation.getColor(); if (annotation instanceof info.limpet.stackedcharts.model.Marker) { // build value Marker final info.limpet.stackedcharts.model.Marker marker = (info.limpet.stackedcharts.model.Marker) annotation; final Marker mrk = new ValueMarker(marker.getValue()); mrk.setLabel(annotation.getName()); mrk.setPaint(color == null ? Color.GRAY : color); // move Text Anchor mrk.setLabelTextAnchor(TextAnchor.TOP_RIGHT); mrk.setLabelAnchor(RectangleAnchor.TOP); mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2)); if (isRangeAnnotation) { subplot.addRangeMarker(mrk, Layer.FOREGROUND); } else { subplot.addDomainMarker(mrk, Layer.FOREGROUND); } } else if (annotation instanceof info.limpet.stackedcharts.model.Zone) { // build Zone final info.limpet.stackedcharts.model.Zone zone = (info.limpet.stackedcharts.model.Zone) annotation; final Marker mrk = new IntervalMarker(zone.getStart(), zone.getEnd()); mrk.setLabel(annotation.getName()); if (color != null) { mrk.setPaint(color); } // move Text & Label Anchor mrk.setLabelTextAnchor(TextAnchor.CENTER); mrk.setLabelAnchor(RectangleAnchor.CENTER); mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2)); if (isRangeAnnotation) { subplot.addRangeMarker(mrk, Layer.FOREGROUND); } else { subplot.addDomainMarker(mrk, Layer.FOREGROUND); } } else if (annotation instanceof info.limpet.stackedcharts.model.ScatterSet) { // build ScatterSet final info.limpet.stackedcharts.model.ScatterSet marker = (info.limpet.stackedcharts.model.ScatterSet) annotation; final EList<Datum> datums = marker.getDatums(); boolean addLabel = true; for (final Datum datum : datums) { final Marker mrk = new ValueMarker(datum.getVal()); // only add label for first Marker if (addLabel) { mrk.setLabel(annotation.getName()); addLabel = false; } final Color thisColor = datum.getColor(); final Color colorToUse = thisColor == null ? color : thisColor; // apply some transparency to the color if (colorToUse != null) { final Color transColor = new Color(colorToUse.getRed(), colorToUse.getGreen(), colorToUse.getBlue(), 120); mrk.setPaint(transColor); } // move Text Anchor mrk.setLabelTextAnchor(TextAnchor.TOP_RIGHT); mrk.setLabelAnchor(RectangleAnchor.TOP); mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2)); if (isRangeAnnotation) { subplot.addRangeMarker(mrk, Layer.FOREGROUND); } else { subplot.addDomainMarker(mrk, Layer.FOREGROUND); } } } } } /** * * @param helper * Helper object to map between axis types * @param datasets * list of datasets to add to this axis * @param collection * XYDataset need to be fill with Series * @param renderer * axis renderer * @param seriesIndex * counter for current series being assigned * * build axis dataset via adding series to Series & config renderer for styles */ private static void addDatasetToAxis(final ChartHelper helper, final EList<Dataset> datasets, final XYDataset collection, final XYLineAndShapeRenderer renderer, int seriesIndex) { for (final Dataset dataset : datasets) { final Series series = helper.createSeries(dataset.getName()); final Styling styling = dataset.getStyling(); if (styling != null) { if (styling instanceof PlainStyling) { final PlainStyling ps = (PlainStyling) styling; renderer.setSeriesPaint(seriesIndex, ps.getColor()); } else { System.err.println("Linear colors not implemented"); } // legend visibility final boolean isInLegend = styling.isIncludeInLegend(); renderer.setSeriesVisibleInLegend(seriesIndex, isInLegend); // line thickness // line style final LineType lineType = styling.getLineStyle(); if (lineType != null) { final float thickness = (float) styling.getLineThickness(); Stroke stroke; float[] pattern; switch (lineType) { case NONE: renderer.setSeriesLinesVisible(seriesIndex, false); break; case SOLID: renderer.setSeriesLinesVisible(seriesIndex, true); stroke = new BasicStroke(thickness); renderer.setSeriesStroke(seriesIndex, stroke); break; case DOTTED: renderer.setSeriesLinesVisible(seriesIndex, true); pattern = new float[] {3f, 3f}; stroke = new BasicStroke(thickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, pattern, 0); renderer.setSeriesStroke(seriesIndex, stroke); break; case DASHED: renderer.setSeriesLinesVisible(seriesIndex, true); pattern = new float[] {8.0f, 4.0f}; stroke = new BasicStroke(thickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, pattern, 0); renderer.setSeriesStroke(seriesIndex, stroke); break; } } // marker size double size = styling.getMarkerSize(); if (size == 0) { size = 2;// default } // marker style final MarkerStyle marker = styling.getMarkerStyle(); if (marker != null) { switch (marker) { case NONE: renderer.setSeriesShapesVisible(seriesIndex, false); break; case SQUARE: renderer.setSeriesShape(seriesIndex, new Rectangle2D.Double(0, 0, size, size)); break; case CIRCLE: renderer.setSeriesShape(seriesIndex, new Ellipse2D.Double(0, 0, size, size)); break; case TRIANGLE: renderer.setSeriesShape(seriesIndex, ShapeUtilities .createUpTriangle((float) size)); break; case CROSS: renderer.setSeriesShape(seriesIndex, ShapeUtilities .createRegularCross((float) size, (float) size)); break; case DIAMOND: renderer.setSeriesShape(seriesIndex, ShapeUtilities .createDiamond((float) size)); break; default: renderer.setSeriesShapesVisible(seriesIndex, false); } } seriesIndex++; } helper.storeSeries(collection, series); // store the data in the collection populateCollection(helper, dataset, series); // also register as a listener final Adapter adapter = new AdapterImpl() { @Override public void notifyChanged(final Notification notification) { populateCollection(helper, dataset, series); } }; dataset.eAdapters().add(adapter); } } /** * create a chart from chart object for preview * * @param chart * * @return */ public static JFreeChart build(final Chart chart) { final IndependentAxis sharedAxisModel = chart.getParent().getSharedAxis(); final ChartHelper helper; final ValueAxis sharedAxis; if (sharedAxisModel == null) { sharedAxis = new DateAxis("Time"); helper = new NumberHelper(); } else { final AxisType axisType = sharedAxisModel.getAxisType(); if (axisType instanceof info.limpet.stackedcharts.model.NumberAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.AngleAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.DateAxis) { helper = new DateHelper(); } else { System.err.println("UNEXPECTED AXIS TYPE RECEIVED"); helper = new NumberHelper(); } sharedAxis = helper.createAxis(sharedAxisModel.getName()); if (sharedAxisModel.getDirection() == AxisDirection.DESCENDING) { sharedAxis.setInverted(true); } } sharedAxis.setVisible(false); final CombinedDomainXYPlot plot = new TimeBarPlot(sharedAxis); // create this chart final XYPlot subplot = createChart(sharedAxisModel, chart); // add chart to stack plot.add(subplot); final JFreeChart jFreeChart = new JFreeChart(plot); jFreeChart.getLegend().setVisible(false); return jFreeChart; } /** * create a chart from our dataset * * @param chartsSet * * @return */ public static JFreeChart build(final ChartSet chartsSet) { final IndependentAxis sharedAxisModel = chartsSet.getSharedAxis(); final ChartHelper helper; final ValueAxis sharedAxis; if (sharedAxisModel == null) { sharedAxis = new DateAxis("Time"); helper = new NumberHelper(); } else { final AxisType axisType = sharedAxisModel.getAxisType(); if (axisType instanceof info.limpet.stackedcharts.model.NumberAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.AngleAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.DateAxis) { helper = new DateHelper(); } else { System.err.println("UNEXPECTED AXIS TYPE RECEIVED"); helper = new NumberHelper(); } sharedAxis = helper.createAxis(sharedAxisModel.getName()); if (sharedAxisModel.getDirection() == AxisDirection.DESCENDING) { sharedAxis.setInverted(true); } } final CombinedDomainXYPlot plot = new TimeBarPlot(sharedAxis); // now loop through the charts final EList<Chart> charts = chartsSet.getCharts(); for (final Chart chart : charts) { // create this chart final XYPlot subplot = createChart(sharedAxisModel, chart); // add chart to stack plot.add(subplot); } plot.setGap(5.0); plot.setOrientation(chartsSet.getOrientation() == Orientation.VERTICAL ? PlotOrientation.VERTICAL : PlotOrientation.HORIZONTAL); return new JFreeChart(plot); } protected static XYPlot createChart(final IndependentAxis sharedAxisModel, final Chart chart) { final XYPlot subplot = new XYPlot(null, null, null, null); // keep track of how many axes we create int indexAxis = 0; // min axis create on bottom or left final EList<DependentAxis> minAxes = chart.getMinAxes(); for (final DependentAxis axis : minAxes) { createDependentAxis(subplot, indexAxis, axis); subplot.setRangeAxisLocation(indexAxis, AxisLocation.BOTTOM_OR_LEFT); indexAxis++; } // max axis create on top or right final EList<DependentAxis> maxAxes = chart.getMaxAxes(); for (final DependentAxis axis : maxAxes) { createDependentAxis(subplot, indexAxis, axis); subplot.setRangeAxisLocation(indexAxis, AxisLocation.TOP_OR_RIGHT); indexAxis++; } if (sharedAxisModel != null) { // build selective annotations to plot final EList<SelectiveAnnotation> selectiveAnnotations = sharedAxisModel.getAnnotations(); final List<AbstractAnnotation> annotations = new ArrayList<>(); for (final SelectiveAnnotation selectiveAnnotation : selectiveAnnotations) { final EList<Chart> appearsIn = selectiveAnnotation.getAppearsIn(); // check selective option to see is this applicable to current chart if (appearsIn == null || appearsIn.isEmpty() || appearsIn.contains(chart)) { annotations.add(selectiveAnnotation.getAnnotation()); } } addAnnotationToPlot(subplot, annotations, false); } // TODO: sort out how to position this title // XYTitleAnnotation title = new XYTitleAnnotation(0, 0, new TextTitle(chart.getName())); // subplot.addAnnotation(title); return subplot; } /** * * @param subplot * target plot for index * @param indexAxis * index of new axis * @param dependentAxis * model object of DependentAxis */ private static void createDependentAxis(final XYPlot subplot, final int indexAxis, final DependentAxis dependentAxis) { final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setDrawSeriesLineAsPath(true); final int indexSeries = 0; final ChartHelper axeshelper; final AxisType axisType = dependentAxis.getAxisType(); if (axisType instanceof info.limpet.stackedcharts.model.NumberAxis) { axeshelper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.AngleAxis) { axeshelper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.DateAxis) { axeshelper = new DateHelper(); } else { System.err.println("UNEXPECTED AXIS TYPE RECEIVED"); axeshelper = new NumberHelper(); } final XYDataset collection = axeshelper.createCollection(); final ValueAxis chartAxis = new NumberAxis(dependentAxis.getName()); if (dependentAxis.getDirection() == AxisDirection.DESCENDING) { chartAxis.setInverted(true); } addDatasetToAxis(axeshelper, dependentAxis.getDatasets(), collection, renderer, indexSeries); final EList<AbstractAnnotation> annotations = dependentAxis.getAnnotations(); addAnnotationToPlot(subplot, annotations, true); subplot.setDataset(indexAxis, collection); subplot.setRangeAxis(indexAxis, chartAxis); subplot.setRenderer(indexAxis, renderer); subplot.mapDatasetToRangeAxis(indexAxis, indexAxis); } protected static void populateCollection(final ChartHelper helper, final Dataset dataset, final Series series) { helper.clear(series); final EList<DataItem> measurements = dataset.getMeasurements(); for (final DataItem dataItem : measurements) { helper.addItem(series, dataItem); } } private ChartBuilder() { } }
package org.nutz.mvc.adaptor.injector; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.lang.Strings; import org.nutz.lang.inject.Injecting; /** * PairUploadAdaptor * getreferMapMapkey * * @author lAndRaxeE(landraxee@gmail.com) * */ public class MapReferInjector extends ObjectPairInjector { public MapReferInjector(String prefix, Class<?> type) { super(prefix, type); } @SuppressWarnings("unchecked") @Override public Object get(ServletContext sc, HttpServletRequest req, HttpServletResponse resp, Object refer) { Object obj = mirror.born(); Map<String, Object> map = null; if (Map.class.isAssignableFrom(refer.getClass())) map = (Map<String, Object>) refer; for (int i = 0; i < injs.length; i++) { Injecting inj = injs[i]; Object s; if (null != map && map.containsKey(names[i])) s = map.get(names[i]); else s = req.getParameter(names[i]); if (null == s) continue; if (s instanceof String && Strings.isBlank((String) s)) s = null; inj.inject(obj, s); } return obj; } }
package arez.integration; import arez.Arez; import arez.ArezContext; import arez.ObservableValue; import arez.annotations.Action; import arez.annotations.ArezComponent; import arez.annotations.Observable; import arez.annotations.ObservableValueRef; import arez.integration.util.SpyEventRecorder; import java.util.concurrent.atomic.AtomicInteger; import org.testng.annotations.Test; import static org.testng.Assert.*; public class ObservableValueRefNoSetterTest extends AbstractArezIntegrationTest { @ArezComponent static abstract class TestComponent { private int _otherID; private String _other; @ObservableValueRef abstract ObservableValue<Integer> getOtherIDObservableValue(); String getOther() { getOtherIDObservableValue().reportObserved(); if ( null == _other ) { // Imagine that this looks up the other in a repository // and other is actually another ArezComponent. This is // the example used in replicant and HL libraries. The // network layer provides the ID and it is resovled locally _other = String.valueOf( _otherID ); } return _other; } @Observable( expectSetter = false ) int getOtherID() { return _otherID; } @Action void setOtherID( final int otherID ) { _other = null; _otherID = otherID; getOtherIDObservableValue().reportChanged(); } } @Test public void observableRef() throws Throwable { final ArezContext context = Arez.context(); final TestComponent component = new ObservableValueRefNoSetterTest_Arez_TestComponent(); component.setOtherID( 1 ); final SpyEventRecorder recorder = SpyEventRecorder.beginRecording(); final AtomicInteger ttCount = new AtomicInteger(); final AtomicInteger rtCount = new AtomicInteger(); context.observer( "TransportType", () -> { observeADependency(); recorder.mark( "TransportType", component.getOtherID() ); ttCount.incrementAndGet(); } ); // This is verifying that the explicit reportObserved occurs context.observer( "ResolvedType", () -> { observeADependency(); recorder.mark( "ResolvedType", component.getOther() ); rtCount.incrementAndGet(); } ); assertEquals( ttCount.get(), 1 ); assertEquals( rtCount.get(), 1 ); // This is verifying that the explicit reportChanged occurs component.setOtherID( 22 ); assertMatchesFixture( recorder ); assertEquals( ttCount.get(), 2 ); assertEquals( rtCount.get(), 2 ); } }
package models; import models.enumeration.Operation; import models.enumeration.Resource; import models.enumeration.RoleType; import org.junit.Test; import org.junit.Ignore; import static org.fest.assertions.Assertions.assertThat; public class PermissionTest extends ModelTest<Permission> { // FIXME after finding travis out of memory error @Ignore public void hasPermission() throws Exception { // Given Long hobi = 2l; Long nForge4java = 1l; Long jindo = 2l; RoleType anonymous = RoleType.ANONYMOUS; // When // Then assertThat(Permission.hasPermission(hobi, nForge4java, Resource.PROJECT_SETTING, Operation.WRITE)).isEqualTo(true); assertThat(Permission.hasPermission(hobi, jindo, Resource.PROJECT_SETTING, Operation.WRITE)).isEqualTo(false); assertThat(Permission.hasPermission(anonymous, Resource.BOARD_POST, Operation.READ)).isEqualTo(true); assertThat(Permission.hasPermission(anonymous, Resource.BOARD_POST, Operation.DELETE)).isEqualTo(false); } @Test public void findPermissionsByRole() throws Exception { // Given // When // Then assertThat(Permission.findPermissionsByRole(1l).size()).isEqualTo(51); } }
package com.keepa.api.backend.structs; import com.keepa.api.backend.KeepaAPI; import java.util.HashMap; import static com.keepa.api.backend.helper.Utility.gson; import static com.keepa.api.backend.helper.Utility.gsonPretty; /** * Common Keepa API Response */ public class Response { /** * Server time when response was sent. */ public long timestamp = System.currentTimeMillis(); /** * States how many ASINs may be requested before the assigned API contingent is depleted. * If the contigent is depleted, HTTP status code 503 will be delivered with the message: * "You are submitting requests too quickly and your requests are being throttled." */ public int tokensLeft = 0; /** * Milliseconds till new tokens are generated. Use this if your contigent is depleted to wait before you try a new request. Tokens are generated every 5 minutes. */ public int refillIn = 0; /** * Token refill rate per minute. */ public int refillRate = 0; /** * time the request took, in milliseconds */ public long requestTime = 0; /** * Status of the request. */ public KeepaAPI.ResponseStatus status = KeepaAPI.ResponseStatus.PENDING; /** * Results of the product request */ public Product[] products = null; /** * Results of the category lookup and search */ public HashMap<Long, Category> categories = null; /** * Results of the category lookup and search includeParents parameter */ public HashMap<Long, Category> categoryParents = null; /** * Results of the deals request */ public DealResponse deals = null; /** * Results of the best sellers request */ public BestSellers bestSellersList = null; /** * Results of the deals request */ public HashMap<String, Seller> sellers = null; /** * Contains information about any error that might have occurred. */ public RequestError error = null; static public Response REQUEST_FAILED = new Response(); static public Response REQUEST_REJECTED = new Response(); static public Response NOT_ENOUGH_TOKEN = new Response(); static { REQUEST_FAILED.status = KeepaAPI.ResponseStatus.FAIL; REQUEST_REJECTED.status = KeepaAPI.ResponseStatus.REQUEST_REJECTED; NOT_ENOUGH_TOKEN.status = KeepaAPI.ResponseStatus.NOT_ENOUGH_TOKEN; } @Override public String toString() { if(status == KeepaAPI.ResponseStatus.OK) return gson.toJson(this); else return gsonPretty.toJson(this); } }
package edu.pdx.cs410J.grader; import edu.pdx.cs410J.ParserException; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; /** * This panel is used to display and edit <code>Assignment</code>s. */ @SuppressWarnings("serial") public class AssignmentPanel extends JPanel { private static final String QUIZ = "Quiz"; private static final String PROJECT = "Project"; private static final String OTHER = "Other"; private static final String OPTIONAL = "Optional"; private static final String POA = "POA"; static final String DATE_TIME_FORMAT_PATTERN = "M/d/yyyy h:mm a"; static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT_PATTERN); // GUI components we care about private JTextField nameField; private JComboBox<String> typeBox; private JTextField pointsField; private JTextField descriptionField; private JTextField dueDateField; private NotesPanel notes; /** * Creates and adds GUI components to a new * <code>AssignmentPanel</code>. */ public AssignmentPanel(boolean canCreate) { this.setLayout(new BorderLayout()); // Panel containing information about an assignment JPanel infoPanel = new JPanel(); infoPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); infoPanel.setLayout(new BorderLayout()); addAssignmentInformationWidgets(infoPanel); this.add(infoPanel, BorderLayout.NORTH); if (!canCreate) { this.nameField.setEditable(false); } // Add a NotePanel this.notes = new NotesPanel(); this.notes.setNotable(new Notable() { private ArrayList<String> notes = new ArrayList<>(); @Override public java.util.List<String> getNotes() { return notes; } @Override public void addNote(String note) { notes.add(note); } @Override public void removeNote(String note) { notes.remove(note); } }); this.add(notes, BorderLayout.CENTER); } private void addAssignmentInformationWidgets(JPanel infoPanel) { JPanel labels = new JPanel(); labels.setLayout(new GridLayout(0, 1)); labels.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2)); labels.add(new JLabel("Name:")); labels.add(new JLabel("Max points:")); labels.add(new JLabel("Type:")); labels.add(new JLabel("Description:")); labels.add(new JLabel("Due date:")); JPanel fields = new JPanel(); fields.setLayout(new GridLayout(0, 1)); this.nameField = new JTextField(8); fields.add(this.nameField); this.pointsField = new JTextField(5); fields.add(this.pointsField); addTypeBox(fields); this.descriptionField = new JTextField(20); fields.add(this.descriptionField); this.dueDateField = new JTextField(22); fields.add(this.dueDateField); infoPanel.add(labels, BorderLayout.WEST); infoPanel.add(fields, BorderLayout.CENTER); } private void addTypeBox(JPanel fields) { this.typeBox = new JComboBox<>(); this.typeBox.addItem(QUIZ); this.typeBox.addItem(PROJECT); this.typeBox.addItem(POA); this.typeBox.addItem(OTHER); this.typeBox.addItem(OPTIONAL); fields.add(this.typeBox); } /** * Creates a new <code>Assignment</code> based on the contents of * this <code>AssignmentPanel</code>. */ public Assignment createAssignment() { // Get the name and max points of the assignment String name = nameField.getText(); if (isNullOrEmpty(name)) { return error("No assignment name specified"); } String points = pointsField.getText(); if (isNullOrEmpty(points)) { return error("No points value specified"); } // Create a new Assignment object try { double d = Double.parseDouble(points); Assignment newAssign = new Assignment(name, d); this.notes.getNotable().getNotes().forEach(newAssign::addNote); updateAssignment(newAssign); this.notes.setNotable(newAssign); return newAssign; } catch (NumberFormatException ex) { return error(points + " is not a number"); } } private boolean isNullOrEmpty(String name) { return name == null || name.equals(""); } private Assignment error(String message) { JOptionPane.showMessageDialog(AssignmentPanel.this, new String[]{message}, "Error", JOptionPane.ERROR_MESSAGE); return null; } /** * Displays the contents of a given <code>Assignment</code> in this * <code>AssignmentPanel</code>. */ public void displayAssignment(Assignment assign) { this.nameField.setText(assign.getName()); this.pointsField.setText(String.valueOf(assign.getPoints())); Assignment.AssignmentType type = assign.getType(); if (type == Assignment.AssignmentType.QUIZ) { this.typeBox.setSelectedItem(QUIZ); } else if (type == Assignment.AssignmentType.PROJECT) { this.typeBox.setSelectedItem(PROJECT); } else if (type == Assignment.AssignmentType.OTHER) { this.typeBox.setSelectedItem(OTHER); } else if (type == Assignment.AssignmentType.OPTIONAL) { this.typeBox.setSelectedItem(OPTIONAL); } else if (type == Assignment.AssignmentType.POA) { this.typeBox.setSelectedItem(POA); } else { String s = "Invalid assignment type: " + type; throw new IllegalArgumentException(s); } String description = assign.getDescription(); if (isNotEmpty(description)) { this.descriptionField.setText(description); } else { this.descriptionField.setText(""); } LocalDateTime dueDate = assign.getDueDate(); if (dueDate != null) { this.dueDateField.setText(DATE_TIME_FORMAT.format(dueDate)); } else { this.dueDateField.setText(""); } this.notes.setNotable(assign); } /** * Fills in the contents of an <code>Assignment</code> based on the * contents of this <code>AssignmentPanel</code>. */ public void updateAssignment(Assignment assign) { String points = pointsField.getText(); if (isNullOrEmpty(points)) { error("No points value specified"); return; } try { double d = Double.parseDouble(points); assign.setPoints(d); } catch (NumberFormatException ex) { error(points + " is not a number"); return; } setAssignmentType(assign); String description = this.descriptionField.getText(); if (isNotEmpty(description)) { assign.setDescription(description); } String dueDate = this.dueDateField.getText(); if (isNotEmpty(dueDate)) { try { assign.setDueDate(LocalDateTime.parse(dueDate.trim(), DATE_TIME_FORMAT)); } catch (DateTimeParseException ex) { error(dueDate + " is not a validate date (" + DATE_TIME_FORMAT_PATTERN + ")"); } } else { assign.setDueDate(null); } // Adding notes is taken care of by the NotesPanel } private void setAssignmentType(Assignment assign) { String type = (String) this.typeBox.getSelectedItem(); switch (type) { case QUIZ: assign.setType(Assignment.AssignmentType.QUIZ); break; case PROJECT: assign.setType(Assignment.AssignmentType.PROJECT); break; case OTHER: assign.setType(Assignment.AssignmentType.OTHER); break; case OPTIONAL: assign.setType(Assignment.AssignmentType.OPTIONAL); break; case POA: assign.setType(Assignment.AssignmentType.POA); break; default: String s = "Unknown assignment type: " + type; throw new IllegalArgumentException(s); } } private boolean isNotEmpty(String description) { return description != null && !description.equals(""); } /** * Test program */ public static void main(String[] args) { String fileName = args[0]; String assignName = args[1]; GradeBook book = null; try { XmlGradeBookParser parser = new XmlGradeBookParser(fileName); book = parser.parse(); } catch (FileNotFoundException ex) { System.err.println("** Could not find file: " + ex.getMessage()); System.exit(1); } catch (IOException ex) { System.err.println("** IOException during parsing: " + ex.getMessage()); System.exit(1); } catch (ParserException ex) { System.err.println("** Error during parsing: " + ex); System.exit(1); } Assignment assign = book.getAssignment(assignName); if (assign == null) { System.err.println("Not such assignment: " + assignName); System.exit(1); } AssignmentPanel assignPanel = new AssignmentPanel(false); assignPanel.displayAssignment(assign); JFrame frame = new JFrame("AssignmentPanel test"); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(1); } }); frame.getContentPane().add(assignPanel); frame.pack(); frame.setVisible(true); } }
package org.intermine.objectstore.intermine; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.WeakHashMap; import org.intermine.metadata.AttributeDescriptor; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ClassConstraint; import org.intermine.objectstore.query.Constraint; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.FromElement; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryCast; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryClassBag; import org.intermine.objectstore.query.QueryCollectionReference; import org.intermine.objectstore.query.QueryEvaluable; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryFieldPathExpression; import org.intermine.objectstore.query.QueryExpression; import org.intermine.objectstore.query.QueryFunction; import org.intermine.objectstore.query.QueryNode; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.QueryPathExpression; import org.intermine.objectstore.query.QueryReference; import org.intermine.objectstore.query.QuerySelectable; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.objectstore.query.SubqueryConstraint; import org.intermine.objectstore.query.SubqueryExistsConstraint; import org.intermine.objectstore.query.UnknownTypeValue; import org.intermine.objectstore.query.ConstraintHelper; import org.intermine.objectstore.query.iql.IqlQuery; import org.intermine.sql.Database; import org.intermine.util.AlwaysMap; import org.intermine.util.CombinedIterator; import org.intermine.util.DatabaseUtil; import org.intermine.util.DynamicUtil; import org.apache.log4j.Logger; import org.apache.torque.engine.database.model.Domain; import org.apache.torque.engine.database.model.SchemaType; import org.apache.torque.engine.platform.Platform; import org.apache.torque.engine.platform.PlatformFactory; /** * Code to generate an sql statement from a Query object. * * @author Matthew Wakeling * @author Andrew Varley * @author Richard Smith */ public class SqlGenerator { private static final Logger LOG = Logger.getLogger(SqlGenerator.class); protected static final int QUERY_NORMAL = 0; protected static final int QUERY_SUBQUERY_FROM = 1; protected static final int QUERY_SUBQUERY_CONSTRAINT = 2; protected static final int ID_ONLY = 2; protected static final int NO_ALIASES_ALL_FIELDS = 3; protected static final int QUERY_FOR_PRECOMP = 4; protected static Map sqlCache = new WeakHashMap(); protected static Map tablenamesCache = new WeakHashMap(); /** * Generates a query to retrieve a single object from the database, by id. * * @param id the id of the object to fetch * @param clazz a Class of the object - if unsure use InterMineObject * @param schema the DatabaseSchema * @return a String suitable for passing to an SQL server * @throws ObjectStoreException if the given class is not in the model */ public static String generateQueryForId(Integer id, Class clazz, DatabaseSchema schema) throws ObjectStoreException { ClassDescriptor tableMaster; // if (schema.isFlatMode()) { // Query q = new Query(); // QueryClass qc = new QueryClass(clazz); // q.addFrom(qc); // q.addToSelect(qc); // q.setConstraint(new SimpleConstraint(new QueryField(qc, "id"), ConstraintOp.EQUALS, // new QueryValue(id))); // q.setDistinct(false); // return generate(q, 0, 2, schema, null, null); if (schema.isMissingNotXml()) { tableMaster = schema.getModel() .getClassDescriptorByName(InterMineObject.class.getName()); } else { ClassDescriptor cld = schema.getModel().getClassDescriptorByName(clazz.getName()); if (cld == null) { throw new ObjectStoreException(clazz.toString() + " is not in the model"); } tableMaster = schema.getTableMaster(cld); } if (schema.isTruncated(tableMaster)) { return "SELECT a1_.OBJECT AS a1_ FROM " + DatabaseUtil.getTableName(tableMaster) + " AS a1_ WHERE a1_.id = " + id.toString() + " AND a1_.class = '" + clazz.getName() + "' LIMIT 2"; } else { return "SELECT a1_.OBJECT AS a1_ FROM " + DatabaseUtil.getTableName(tableMaster) + " AS a1_ WHERE a1_.id = " + id.toString() + " LIMIT 2"; } } /** * Returns the table name used by the ID fetch query. * * @param clazz the Class of the object * @param schema the DatabaseSchema * @return a table name * @throws ObjectStoreException if the given class is not in the model */ public static String tableNameForId(Class clazz, DatabaseSchema schema) throws ObjectStoreException { ClassDescriptor tableMaster; if (schema.isMissingNotXml()) { tableMaster = schema.getModel() .getClassDescriptorByName(InterMineObject.class.getName()); } else { ClassDescriptor cld = schema.getModel().getClassDescriptorByName(clazz.getName()); if (cld == null) { throw new ObjectStoreException(clazz.toString() + " is not in the model"); } tableMaster = schema.getTableMaster(cld); } return DatabaseUtil.getTableName(tableMaster); } /** * Registers an offset for a given query. This is used later on to speed up queries that use * big offsets. * * @param q the Query * @param start the offset * @param schema the DatabaseSchema in which to look up metadata * @param db the Database that the ObjectStore uses * @param value a value, such that adding a WHERE component first_order_field &gt; value with * OFFSET 0 is equivalent to the original query with OFFSET offset * @param bagTableNames a Map from BagConstraints to table names, where the table contains the * contents of the bag that are relevant for the BagConstraint */ public static void registerOffset(Query q, int start, DatabaseSchema schema, Database db, Object value, Map bagTableNames) { LOG.debug("registerOffset() called with offset: " + start); try { if (value.getClass().equals(Boolean.class)) { return; } synchronized (q) { Map schemaCache = getCacheForSchema(schema); CacheEntry cacheEntry = (CacheEntry) schemaCache.get(q); if (cacheEntry != null) { if ((cacheEntry.getLastOffset() - start >= 100000) || (start - cacheEntry.getLastOffset() >= 10000)) { QueryNode firstOrderBy = null; firstOrderBy = (QueryNode) q.getEffectiveOrderBy().iterator().next(); if (firstOrderBy instanceof QueryClass) { firstOrderBy = new QueryField((QueryClass) firstOrderBy, "id"); } // Now we need to work out if this field is a primitive type or a object // type (that can accept null values). Constraint c = getOffsetConstraint(q, firstOrderBy, value, schema); String sql = generate(q, schema, db, c, QUERY_NORMAL, bagTableNames); cacheEntry.setLast(start, sql); } SortedMap headMap = cacheEntry.getCached().headMap(new Integer(start + 1)); Integer lastKey = null; try { lastKey = (Integer) headMap.lastKey(); } catch (NoSuchElementException e) { // ignore } if (lastKey != null) { int offset = lastKey.intValue(); if (start - offset < 100000) { return; } } } QueryNode firstOrderBy = null; firstOrderBy = (QueryNode) q.getEffectiveOrderBy().iterator().next(); if (firstOrderBy instanceof QueryClass) { firstOrderBy = new QueryField((QueryClass) firstOrderBy, "id"); } // Now we need to work out if this field is a primitive type or a object // type (that can accept null values). Constraint offsetConstraint = getOffsetConstraint(q, firstOrderBy, value, schema); String sql = generate(q, schema, db, offsetConstraint, QUERY_NORMAL, bagTableNames); if (cacheEntry == null) { cacheEntry = new CacheEntry(start, sql); schemaCache.put(q, cacheEntry); } cacheEntry.getCached().put(new Integer(start), sql); //LOG.info("Created cache entry for offset " + start + " (cache contains " // + cacheEntry.getCached().keySet() + ") for query " + q + ", sql = " + sql); } } catch (ObjectStoreException e) { LOG.error("Error while registering offset for query " + q + ": " + e); } } /** * Create a constraint to add to the main query to deal with offset - this is based on * the first element in the order by (field) and a given value (x). If the order by * element cannot have null values this is: 'field > x'. If field can have null values * *and* it has not already been constrained as 'NOT NULL' in the main query it is: * '(field > x or field IS NULL'. * @param q the Query * @param firstOrderBy the offset element of the query's order by list * @param value a value, such that adding a WHERE component first_order_field &gt; value with * OFFSET 0 is equivalent to the original query with OFFSET offset * @param schema the DatabaseSchema in which to look up metadata * @return the constraint(s) to add to the main query */ protected static Constraint getOffsetConstraint(Query q, QueryNode firstOrderBy, Object value, DatabaseSchema schema) { boolean hasNulls = true; if (firstOrderBy instanceof QueryField) { FromElement qc = ((QueryField) firstOrderBy).getFromElement(); if (qc instanceof QueryClass) { if ("id".equals(((QueryField) firstOrderBy).getFieldName())) { hasNulls = false; } else { AttributeDescriptor desc = (AttributeDescriptor) schema .getModel().getFieldDescriptorsForClass(((QueryClass) qc) .getType()).get(((QueryField) firstOrderBy) .getFieldName()); if (desc.isPrimitive()) { hasNulls = false; } } } } SimpleConstraint sc = new SimpleConstraint((QueryEvaluable) firstOrderBy, ConstraintOp.GREATER_THAN, new QueryValue(value)); if (hasNulls) { // if the query aready constrains the first order by field to be // not null it doesn't make sense to add a costraint to null CheckForIsNotNullConstraint check = new CheckForIsNotNullConstraint(firstOrderBy); ConstraintHelper.traverseConstraints(q.getConstraint(), check); if (!check.exists()) { ConstraintSet cs = new ConstraintSet(ConstraintOp.OR); cs.addConstraint(sc); cs.addConstraint(new SimpleConstraint((QueryEvaluable) firstOrderBy, ConstraintOp.IS_NULL)); return cs; } } return sc; } /** * Converts a Query object into an SQL String. To produce an SQL query that does not have * OFFSET and LIMIT clauses, set start to 0, and limit to Integer.MAX_VALUE. * * @param q the Query to convert * @param start the number of the first row for the query to return, numbered from zero * @param limit the maximum number of rows for the query to return * @param schema the DatabaseSchema in which to look up metadata * @param db the Database that the ObjectStore uses * @param bagTableNames a Map from BagConstraints to table names, where the table contains the * contents of the bag that are relevant for the BagConstraint * @return a String suitable for passing to an SQL server * @throws ObjectStoreException if something goes wrong */ public static String generate(Query q, int start, int limit, DatabaseSchema schema, Database db, Map bagTableNames) throws ObjectStoreException { synchronized (q) { Map schemaCache = getCacheForSchema(schema); CacheEntry cacheEntry = (CacheEntry) schemaCache.get(q); if (cacheEntry != null) { SortedMap headMap = cacheEntry.getCached().headMap(new Integer(start + 1)); Integer lastKey = null; try { lastKey = (Integer) headMap.lastKey(); } catch (NoSuchElementException e) { // ignore } if (lastKey != null) { int offset = lastKey.intValue(); if ((offset > cacheEntry.getLastOffset()) || (cacheEntry.getLastOffset() > start)) { return cacheEntry.getCached().get(lastKey) + ((limit == Integer.MAX_VALUE ? "" : " LIMIT " + limit) + (start == offset ? "" : " OFFSET " + (start - offset))); } else { return cacheEntry.getLastSQL() + ((limit == Integer.MAX_VALUE ? "" : " LIMIT " + limit) + (start == cacheEntry.getLastOffset() ? "" : " OFFSET " + (start - cacheEntry.getLastOffset()))); } } } String sql = generate(q, schema, db, null, QUERY_NORMAL, bagTableNames); /*if (cached == null) { cached = new TreeMap(); schemaCache.put(q, cached); } cached.put(new Integer(0), sql); */ return sql + ((limit == Integer.MAX_VALUE ? "" : " LIMIT " + limit) + (start == 0 ? "" : " OFFSET " + start)); } } /** * Returns a cache specific to a particular DatabaseSchema. * * @param schema the DatabaseSchema * @return a Map */ private static Map getCacheForSchema(DatabaseSchema schema) { synchronized (sqlCache) { Map retval = (Map) sqlCache.get(schema); if (retval == null) { retval = Collections.synchronizedMap(new WeakHashMap()); sqlCache.put(schema, retval); } return retval; } } /** * Converts a Query object into an SQL String. * * @param q the Query to convert * @param schema the DatabaseSchema in which to look up metadata * @param db the Database that the ObjectStore uses * @param offsetCon an additional constraint for improving the speed of large offsets * @param kind Query type * @param bagTableNames a Map from BagConstraints to table names, where the table contains the * contents of the bag that are relevant for the BagConstraint * @return a String suitable for passing to an SQL server * @throws ObjectStoreException if something goes wrong */ public static String generate(Query q, DatabaseSchema schema, Database db, Constraint offsetCon, int kind, Map bagTableNames) throws ObjectStoreException { State state = new State(); state.setDb(db); state.setBagTableNames(bagTableNames); buildFromComponent(state, q, schema, bagTableNames); buildWhereClause(state, q, q.getConstraint(), schema); buildWhereClause(state, q, offsetCon, schema); String orderBy = ((kind == QUERY_NORMAL) || (kind == QUERY_FOR_PRECOMP) ? buildOrderBy(state, q, schema) : ""); StringBuffer retval = new StringBuffer("SELECT ") .append(needsDistinct(q) ? "DISTINCT " : "") .append(buildSelectComponent(state, q, schema, kind)) .append(state.getFrom()) .append(state.getWhere()) .append(buildGroupBy(q, schema, state)) .append(orderBy); return retval.toString(); } /** * Returns true if this query requires a DISTINCT keyword in the generated SQL. * * @param q the Query * @return a boolean */ protected static boolean needsDistinct(Query q) { if (!q.isDistinct()) { return false; } Set selectClasses = new HashSet(); Iterator selectIter = q.getSelect().iterator(); while (selectIter.hasNext()) { QuerySelectable n = (QuerySelectable) selectIter.next(); if (n instanceof QueryClass) { selectClasses.add(n); } else if (n instanceof QueryField) { QueryField f = (QueryField) n; if ("id".equals(f.getFieldName())) { FromElement qc = f.getFromElement(); if (qc instanceof QueryClass) { selectClasses.add(qc); } } } } boolean allPresent = true; Iterator fromIter = q.getFrom().iterator(); while (fromIter.hasNext() && allPresent) { FromElement qc = (FromElement) fromIter.next(); allPresent = selectClasses.contains(qc); } return !allPresent; } /** * Builds a Set of all table names that are touched by a given query. * * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @return a Set of table names * @throws ObjectStoreException if something goes wrong */ public static Set findTableNames(Query q, DatabaseSchema schema) throws ObjectStoreException { synchronized (q) { Map schemaCache = getTablenamesCacheForSchema(schema); Set tablenames = (Set) schemaCache.get(q); if (tablenames == null) { tablenames = new HashSet(); findTableNames(tablenames, q, schema, true); schemaCache.put(q, tablenames); } return tablenames; } } /** * Returns a cache for table names specific to a particular DatabaseSchema. * * @param schema the DatabaseSchema * @return a Map */ private static Map getTablenamesCacheForSchema(DatabaseSchema schema) { synchronized (tablenamesCache) { Map retval = (Map) tablenamesCache.get(schema); if (retval == null) { retval = Collections.synchronizedMap(new WeakHashMap()); tablenamesCache.put(schema, retval); } return retval; } } /** * Adds table names to a Set of table names, from a given Query. * * @param tablenames a Set of table names - new names will be added here * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param addInterMineObject true if this method should normally add the InterMineObject * table to the Set * @throws ObjectStoreException if something goes wrong */ private static void findTableNames(Set tablenames, Query q, DatabaseSchema schema, boolean addInterMineObject) throws ObjectStoreException { findTableNamesInConstraint(tablenames, q.getConstraint(), schema); Set fromElements = q.getFrom(); Iterator fromIter = fromElements.iterator(); while (fromIter.hasNext()) { FromElement fromElement = (FromElement) fromIter.next(); if (fromElement instanceof QueryClass) { QueryClass qc = (QueryClass) fromElement; Set classes = DynamicUtil.decomposeClass(qc.getType()); Iterator classIter = classes.iterator(); while (classIter.hasNext()) { Class cls = (Class) classIter.next(); ClassDescriptor cld = schema.getModel().getClassDescriptorByName(cls.getName()); if (cld == null) { throw new ObjectStoreException(cls.toString() + " is not in the model"); } ClassDescriptor tableMaster = schema.getTableMaster(cld); tablenames.add(DatabaseUtil.getTableName(tableMaster)); } } else if (fromElement instanceof Query) { Query subQ = (Query) fromElement; findTableNames(tablenames, subQ, schema, false); } else if (fromElement instanceof QueryClassBag) { // Do nothing } else { throw new ObjectStoreException("Unknown FromElement: " + fromElement.getClass()); } } String interMineObject = DatabaseUtil.getTableName(schema.getModel() .getClassDescriptorByName(InterMineObject.class.getName())); Iterator selectIter = q.getSelect().iterator(); while (selectIter.hasNext()) { QuerySelectable selectable = (QuerySelectable) selectIter.next(); if (selectable instanceof QueryClass) { if (addInterMineObject && schema.isMissingNotXml()) { tablenames.add(interMineObject); } } else if (selectable instanceof QueryEvaluable) { // Do nothing } else if ((selectable instanceof QueryFieldPathExpression) && ("id".equals(((QueryFieldPathExpression) selectable).getFieldName()))) { // Do nothing } else { throw new ObjectStoreException("Illegal entry in SELECT list: " + selectable.getClass()); } } } /** * Adds table names to a Set of table names, from a given constraint. * * @param tablenames a Set of table names - new names will be added here * @param c the Constraint * @param schema the DatabaseSchema in which to look up metadata * @throws ObjectStoreException if something goes wrong */ private static void findTableNamesInConstraint(Set tablenames, Constraint c, DatabaseSchema schema) throws ObjectStoreException { if (c instanceof ConstraintSet) { Iterator conIter = ((ConstraintSet) c).getConstraints().iterator(); while (conIter.hasNext()) { Constraint subC = (Constraint) conIter.next(); findTableNamesInConstraint(tablenames, subC, schema); } } else if (c instanceof SubqueryConstraint) { findTableNames(tablenames, ((SubqueryConstraint) c).getQuery(), schema, false); } else if (c instanceof SubqueryExistsConstraint) { findTableNames(tablenames, ((SubqueryExistsConstraint) c).getQuery(), schema, false); } else if (c instanceof ContainsConstraint) { ContainsConstraint cc = (ContainsConstraint) c; QueryReference ref = cc.getReference(); if (ref instanceof QueryCollectionReference) { ReferenceDescriptor refDesc = (ReferenceDescriptor) schema.getModel() .getFieldDescriptorsForClass(ref.getQcType()).get(ref.getFieldName()); if (refDesc.relationType() == FieldDescriptor.M_N_RELATION) { tablenames.add(DatabaseUtil.getIndirectionTableName((CollectionDescriptor) refDesc)); } else if (cc.getQueryClass() == null) { tablenames.add(DatabaseUtil.getTableName(schema.getTableMaster( refDesc.getReferencedClassDescriptor()))); } } } else if (!((c == null) || (c instanceof SimpleConstraint) || (c instanceof ClassConstraint) || (c instanceof BagConstraint))) { throw new ObjectStoreException("Unknown constraint type: " + c.getClass()); } } /** * Builds the FROM list for the SQL query. * * @param state the current Sql Query state * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param bagTableNames a Map from BagConstraint to temporary table name * @throws ObjectStoreException if something goes wrong */ protected static void buildFromComponent(State state, Query q, DatabaseSchema schema, Map bagTableNames) throws ObjectStoreException { Set fromElements = q.getFrom(); Iterator fromIter = fromElements.iterator(); while (fromIter.hasNext()) { FromElement fromElement = (FromElement) fromIter.next(); if (fromElement instanceof QueryClass) { QueryClass qc = (QueryClass) fromElement; String baseAlias = DatabaseUtil.generateSqlCompatibleName((String) q.getAliases() .get(qc)); Set classes = DynamicUtil.decomposeClass(qc.getType()); Map aliases = new LinkedHashMap(); int sequence = 0; String lastAlias = ""; Iterator classIter = classes.iterator(); while (classIter.hasNext()) { Class cls = (Class) classIter.next(); ClassDescriptor cld = schema.getModel().getClassDescriptorByName(cls.getName()); if (cld == null) { throw new ObjectStoreException(cls.toString() + " is not in the model"); } ClassDescriptor tableMaster = schema.getTableMaster(cld); if (sequence == 0) { aliases.put(cld, baseAlias); state.addToFrom(DatabaseUtil.getTableName(tableMaster) + " AS " + baseAlias); if (schema.isTruncated(tableMaster)) { if (state.getWhereBuffer().length() > 0) { state.addToWhere(" AND "); } state.addToWhere(baseAlias + ".class = '" + cls.getName() + "'"); } } else { aliases.put(cld, baseAlias + "_" + sequence); state.addToFrom(DatabaseUtil.getTableName(tableMaster) + " AS " + baseAlias + "_" + sequence); if (state.getWhereBuffer().length() > 0) { state.addToWhere(" AND "); } state.addToWhere(baseAlias + lastAlias + ".id = " + baseAlias + "_" + sequence + ".id"); lastAlias = "_" + sequence; if (schema.isTruncated(tableMaster)) { state.addToWhere(" AND " + baseAlias + "_" + sequence + ".class = '" + cls.getName() + "'"); } } sequence++; } Map fields = schema.getModel().getFieldDescriptorsForClass(qc.getType()); Map fieldToAlias = state.getFieldToAlias(qc); Iterator fieldIter = null; if (schema.isFlatMode()) { List iterators = new ArrayList(); ClassDescriptor cld = schema.getTableMaster((ClassDescriptor) schema.getModel() .getClassDescriptorsForClass(qc.getType()).iterator().next()); DatabaseSchema.Fields dbsFields = schema.getTableFields(schema .getTableMaster(cld)); iterators.add(dbsFields.getAttributes().iterator()); iterators.add(dbsFields.getReferences().iterator()); fieldIter = new CombinedIterator(iterators); } else { fieldIter = fields.values().iterator(); } while (fieldIter.hasNext()) { FieldDescriptor field = (FieldDescriptor) fieldIter.next(); String name = field.getName(); Iterator aliasIter = aliases.entrySet().iterator(); while (aliasIter.hasNext()) { Map.Entry aliasEntry = (Map.Entry) aliasIter.next(); ClassDescriptor cld = (ClassDescriptor) aliasEntry.getKey(); String alias = (String) aliasEntry.getValue(); if (cld.getAllFieldDescriptors().contains(field) || schema.isFlatMode()) { fieldToAlias.put(name, alias + "." + DatabaseUtil.getColumnName(field)); break; } } } // Deal with OBJECT column if (schema.isMissingNotXml()) { Iterator aliasIter = aliases.entrySet().iterator(); while (aliasIter.hasNext()) { Map.Entry aliasEntry = (Map.Entry) aliasIter.next(); ClassDescriptor cld = (ClassDescriptor) aliasEntry.getKey(); String alias = (String) aliasEntry.getValue(); ClassDescriptor tableMaster = schema.getTableMaster(cld); if (InterMineObject.class.equals(tableMaster.getType())) { fieldToAlias.put("OBJECT", alias + ".OBJECT"); break; } } } else if (schema.isFlatMode()) { // We never want an OBJECT column in this case. However, we may want an // objectclass column. fieldToAlias.put("objectclass", baseAlias + ".objectclass"); } else { fieldToAlias.put("OBJECT", baseAlias + ".OBJECT"); } } else if (fromElement instanceof Query) { state.addToFrom("(" + generate((Query) fromElement, schema, state.getDb(), null, QUERY_SUBQUERY_FROM, bagTableNames) + ") AS " + DatabaseUtil.generateSqlCompatibleName((String) q.getAliases() .get(fromElement))); state.setFieldToAlias(fromElement, new AlwaysMap(DatabaseUtil .generateSqlCompatibleName((String) (q.getAliases() .get(fromElement))))); } else if (fromElement instanceof QueryClassBag) { // The problem here is: // We do not know the column name for the "id" field, because this will use a // table like an indirection table or other class table. We need to have this id // column name available for QueryFields and for extra tables added to the query // that need to be tied to the original copy via the id column. This id column // name must be filled in by the ContainsConstraint code. // Therefore, we do nothing here. } else { throw new ObjectStoreException("Unknown FromElement: " + fromElement.getClass()); } } } /** * Builds the WHERE clause for the SQL query. * * @param state the current Sql Query state * @param q the Query * @param c the Constraint * @param schema the DatabaseSchema in which to look up metadata * @throws ObjectStoreException if something goes wrong */ protected static void buildWhereClause(State state, Query q, Constraint c, DatabaseSchema schema) throws ObjectStoreException { if (c != null) { if (state.getWhereBuffer().length() > 0) { state.addToWhere(" AND "); } constraintToString(state, c, q, schema, SAFENESS_SAFE, true); } } /** Safeness value indicating a situation safe for ContainsConstraint CONTAINS */ public static final int SAFENESS_SAFE = 1; /** Safeness value indicating a situation safe for ContainsConstraint DOES NOT CONTAIN */ public static final int SAFENESS_ANTISAFE = -1; /** Safeness value indicating a situation unsafe for ContainsConstraint */ public static final int SAFENESS_UNSAFE = 0; /** * Converts a Constraint object into a String suitable for putting in an SQL query. * * @param state the object to place text into * @param c the Constraint object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param safeness the ContainsConstraint safeness parameter * @param loseBrackets true if an AND ConstraintSet can be represented safely without * surrounding parentheses * @throws ObjectStoreException if something goes wrong */ protected static void constraintToString(State state, Constraint c, Query q, DatabaseSchema schema, int safeness, boolean loseBrackets) throws ObjectStoreException { if ((safeness != SAFENESS_SAFE) && (safeness != SAFENESS_ANTISAFE) & (safeness != SAFENESS_UNSAFE)) { throw new ObjectStoreException("Unknown ContainsConstraint safeness: " + safeness); } if (c instanceof ConstraintSet) { constraintSetToString(state, (ConstraintSet) c, q, schema, safeness, loseBrackets); } else if (c instanceof SimpleConstraint) { simpleConstraintToString(state, (SimpleConstraint) c, q); } else if (c instanceof SubqueryConstraint) { subqueryConstraintToString(state, (SubqueryConstraint) c, q, schema); } else if (c instanceof SubqueryExistsConstraint) { subqueryExistsConstraintToString(state, (SubqueryExistsConstraint) c, q, schema); } else if (c instanceof ClassConstraint) { classConstraintToString(state, (ClassConstraint) c, q, schema); } else if (c instanceof ContainsConstraint) { containsConstraintToString(state, (ContainsConstraint) c, q, schema, safeness, loseBrackets); } else if (c instanceof BagConstraint) { bagConstraintToString(state, (BagConstraint) c, q, schema); } else { throw (new ObjectStoreException("Unknown constraint type: " + c)); } } /** * Converts a ConstraintSet object into a String suitable for putting in an SQL query. * * @param state the object to place text into * @param c the ConstraintSet object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param safeness the ContainsConstraint safeness parameter * @param loseBrackets true if an AND ConstraintSet can be represented safely without * surrounding parentheses * @throws ObjectStoreException if something goes wrong */ protected static void constraintSetToString(State state, ConstraintSet c, Query q, DatabaseSchema schema, int safeness, boolean loseBrackets) throws ObjectStoreException { if ((safeness != SAFENESS_SAFE) && (safeness != SAFENESS_ANTISAFE) & (safeness != SAFENESS_UNSAFE)) { throw new ObjectStoreException("Unknown ContainsConstraint safeness: " + safeness); } ConstraintOp op = c.getOp(); boolean negate = (op == ConstraintOp.NAND) || (op == ConstraintOp.NOR); boolean disjunctive = (op == ConstraintOp.OR) || (op == ConstraintOp.NOR); boolean andOrNor = (op == ConstraintOp.AND) || (op == ConstraintOp.NOR); int newSafeness; if (safeness == SAFENESS_UNSAFE) { newSafeness = SAFENESS_UNSAFE; } else if (c.getConstraints().size() == 1) { newSafeness = negate ? -safeness : safeness; } else if (safeness == (andOrNor ? SAFENESS_SAFE : SAFENESS_ANTISAFE)) { newSafeness = negate ? -safeness : safeness; } else { newSafeness = SAFENESS_UNSAFE; } if (c.getConstraints().isEmpty()) { state.addToWhere((disjunctive ? negate : !negate) ? "true" : "false"); } else { state.addToWhere(negate ? "(NOT (" : (loseBrackets && (!disjunctive) ? "" : "(")); boolean needComma = false; Set constraints = c.getConstraints(); Iterator constraintIter = constraints.iterator(); while (constraintIter.hasNext()) { Constraint subC = (Constraint) constraintIter.next(); if (needComma) { state.addToWhere(disjunctive ? " OR " : " AND "); } needComma = true; constraintToString(state, subC, q, schema, newSafeness, (!negate) && (!disjunctive)); } state.addToWhere(negate ? "))" : (loseBrackets && (!disjunctive) ? "" : ")")); } } /** * Converts a SimpleConstraint object into a String suitable for putting in an SQL query. * * @param state the object to place text into * @param c the SimpleConstraint object * @param q the Query * @throws ObjectStoreException if something goes wrong */ protected static void simpleConstraintToString(State state, SimpleConstraint c, Query q) throws ObjectStoreException { queryEvaluableToString(state.getWhereBuffer(), c.getArg1(), q, state); state.addToWhere(" " + c.getOp().toString()); if (c.getArg2() != null) { state.addToWhere(" "); queryEvaluableToString(state.getWhereBuffer(), c.getArg2(), q, state); } } /** * Converts a SubqueryConstraint object into a String suitable for putting in an SQL query. * * @param state the object to place text into * @param c the SubqueryConstraint object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @throws ObjectStoreException if something goes wrong */ protected static void subqueryConstraintToString(State state, SubqueryConstraint c, Query q, DatabaseSchema schema) throws ObjectStoreException { Query subQ = c.getQuery(); QueryEvaluable qe = c.getQueryEvaluable(); QueryClass cls = c.getQueryClass(); if (qe != null) { queryEvaluableToString(state.getWhereBuffer(), qe, q, state); } else { queryClassToString(state.getWhereBuffer(), cls, q, schema, QUERY_SUBQUERY_CONSTRAINT, state); } state.addToWhere(" " + c.getOp().toString() + " (" + generate(subQ, schema, state.getDb(), null, QUERY_SUBQUERY_CONSTRAINT, state.getBagTableNames()) + ")"); } /** * Converts a SubqueryExistsConstraint object into a String suitable for putting in an SQL * query. * * @param state the object to place text into * @param c the SubqueryExistsConstraint object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @throws ObjectStoreException if something goes wrong */ protected static void subqueryExistsConstraintToString(State state, SubqueryExistsConstraint c, Query q, DatabaseSchema schema) throws ObjectStoreException { Query subQ = c.getQuery(); state.addToWhere((c.getOp() == ConstraintOp.EXISTS ? "EXISTS(" : "(NOT EXISTS(") + generate(subQ, schema, state.getDb(), null, QUERY_SUBQUERY_CONSTRAINT, state.getBagTableNames()) + (c.getOp() == ConstraintOp.EXISTS ? ")" : "))")); } /** * Converts a ClassConstraint object into a String suitable for putting in an SQL query. * * @param state the object to place text into * @param c the ClassConstraint object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @throws ObjectStoreException if something goes wrong */ protected static void classConstraintToString(State state, ClassConstraint c, Query q, DatabaseSchema schema) throws ObjectStoreException { QueryClass arg1 = c.getArg1(); QueryClass arg2QC = c.getArg2QueryClass(); InterMineObject arg2O = c.getArg2Object(); queryClassToString(state.getWhereBuffer(), arg1, q, schema, ID_ONLY, state); state.addToWhere(" " + c.getOp().toString() + " "); if (arg2QC != null) { queryClassToString(state.getWhereBuffer(), arg2QC, q, schema, ID_ONLY, state); } else if (arg2O.getId() != null) { objectToString(state.getWhereBuffer(), arg2O); } else { throw new ObjectStoreException("ClassConstraint cannot contain an InterMineObject" + " without an ID set"); } } /** * Converts a ContainsConstraint object into a String suitable for putting in an SQL query. * * @param state the object to place text into * @param c the ContainsConstraint object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param safeness the ContainsConstraint safeness parameter * @param loseBrackets true if an AND ConstraintSet can be represented safely without * surrounding parentheses * @throws ObjectStoreException if something goes wrong */ protected static void containsConstraintToString(State state, ContainsConstraint c, Query q, DatabaseSchema schema, int safeness, boolean loseBrackets) throws ObjectStoreException { if ((safeness != SAFENESS_SAFE) && (safeness != SAFENESS_ANTISAFE) & (safeness != SAFENESS_UNSAFE)) { throw new ObjectStoreException("Unknown ContainsConstraint safeness: " + safeness); } QueryReference arg1 = c.getReference(); QueryClass arg2 = c.getQueryClass(); InterMineObject arg2Obj = c.getObject(); Map fieldNameToFieldDescriptor = schema.getModel().getFieldDescriptorsForClass(arg1 .getQcType()); ReferenceDescriptor arg1Desc = (ReferenceDescriptor) fieldNameToFieldDescriptor.get(arg1.getFieldName()); if (arg1Desc == null) { throw new ObjectStoreException("Reference " + IqlQuery.queryReferenceToString(q, arg1, new ArrayList()) + "." + arg1.getFieldName() + " is not in the model"); } if (arg1 instanceof QueryObjectReference) { String arg1Alias = (String) state.getFieldToAlias(arg1.getQueryClass()).get(arg1Desc .getName()); if (c.getOp().equals(ConstraintOp.IS_NULL) || c.getOp().equals(ConstraintOp .IS_NOT_NULL)) { state.addToWhere(arg1Alias + " " + c.getOp().toString()); } else { state.addToWhere(arg1Alias + (c.getOp() == ConstraintOp.CONTAINS ? " = " : " != ")); if (arg2 == null) { objectToString(state.getWhereBuffer(), arg2Obj); } else { queryClassToString(state.getWhereBuffer(), arg2, q, schema, ID_ONLY, state); } } } else if (arg1 instanceof QueryCollectionReference) { InterMineObject arg1Obj = ((QueryCollectionReference) arg1).getQcObject(); QueryClass arg1Qc = arg1.getQueryClass(); QueryClassBag arg1Qcb = ((QueryCollectionReference) arg1).getQcb(); if ((arg1Qcb != null) && (safeness != (c.getOp().equals(ConstraintOp.CONTAINS) ? SAFENESS_SAFE : SAFENESS_ANTISAFE))) { throw new ObjectStoreException(safeness == SAFENESS_UNSAFE ? "Invalid constraint: QueryClassBag ContainsConstraint cannot be inside" + " an OR ConstraintSet" : "Invalid constraint: DOES NOT CONTAINS cannot be applied to a" + " QueryClassBag"); } if (arg1Desc.relationType() == FieldDescriptor.ONE_N_RELATION) { if (arg2 == null) { ReferenceDescriptor reverse = arg1Desc.getReverseReferenceDescriptor(); String indirectTableAlias = state.getIndirectAlias(); // Not really indirection Map fieldToAlias = state.getFieldToAlias(arg1Qcb); String arg2Alias = indirectTableAlias + "." + DatabaseUtil.getColumnName(reverse); ClassDescriptor tableMaster = schema.getTableMaster(reverse .getClassDescriptor()); state.addToFrom(DatabaseUtil.getTableName(tableMaster) + " AS " + indirectTableAlias); state.addToWhere(loseBrackets ? "" : "("); if (schema.isTruncated(tableMaster)) { state.addToWhere(indirectTableAlias + ".class = '" + reverse.getClassDescriptor().getType().getName() + "' AND "); } if (arg1Qc != null) { queryClassToString(state.getWhereBuffer(), arg1Qc, q, schema, ID_ONLY, state); state.addToWhere((c.getOp() == ConstraintOp.CONTAINS ? " = " : " != ") + arg2Alias); } else if (arg1Qcb != null) { if (fieldToAlias.containsKey("id")) { state.addToWhere(arg2Alias + " = " + fieldToAlias.get("id")); } else { fieldToAlias.put("id", arg2Alias); bagConstraintToString(state, new BagConstraint(new QueryField(arg1Qcb), (c.getOp() == ConstraintOp.CONTAINS ? ConstraintOp.IN : ConstraintOp.NOT_IN), arg1Qcb.getIds()), q, schema); } } else { state.addToWhere(arg1Obj.getId() + (c.getOp() == ConstraintOp.CONTAINS ? " = " : " != ") + arg2Alias); } state.addToWhere(" AND " + indirectTableAlias + ".id = " + arg2Obj.getId()); state.addToWhere(loseBrackets ? "" : ")"); } else { String arg2Alias = (String) state.getFieldToAlias(arg2) .get(arg1Desc.getReverseReferenceDescriptor().getName()); if (arg1Qc != null) { queryClassToString(state.getWhereBuffer(), arg1Qc, q, schema, ID_ONLY, state); state.addToWhere((c.getOp() == ConstraintOp.CONTAINS ? " = " : " != ") + arg2Alias); } else if (arg1Qcb != null) { Map fieldToAlias = state.getFieldToAlias(arg1Qcb); if (fieldToAlias.containsKey("id")) { state.addToWhere(arg2Alias + " = " + fieldToAlias.get("id")); } else { fieldToAlias.put("id", arg2Alias); bagConstraintToString(state, new BagConstraint(new QueryField(arg1Qcb), (c.getOp() == ConstraintOp.CONTAINS ? ConstraintOp.IN : ConstraintOp.NOT_IN), arg1Qcb.getIds()), q, schema); } } else { state.addToWhere("" + arg1Obj.getId() + (c.getOp() == ConstraintOp.CONTAINS ? " = " : " != ") + arg2Alias); } } } else { if (safeness != (c.getOp().equals(ConstraintOp.CONTAINS) ? SAFENESS_SAFE : SAFENESS_ANTISAFE)) { throw new ObjectStoreException(safeness == SAFENESS_UNSAFE ? "Cannot represent a many-to-many collection inside an OR" + " ConstraintSet in SQL" : "Cannot represent many-to-many collection DOES NOT CONTAIN in SQL"); } CollectionDescriptor arg1ColDesc = (CollectionDescriptor) arg1Desc; String indirectTableAlias = state.getIndirectAlias(); String arg2Alias = indirectTableAlias + "." + DatabaseUtil.getInwardIndirectionColumnName(arg1ColDesc); state.addToFrom(DatabaseUtil.getIndirectionTableName(arg1ColDesc) + " AS " + indirectTableAlias); state.addToWhere(loseBrackets ? "" : "("); if (arg1Qc != null) { queryClassToString(state.getWhereBuffer(), arg1Qc, q, schema, ID_ONLY, state); state.addToWhere(" = " + arg2Alias); } else if (arg1Qcb != null) { Map fieldToAlias = state.getFieldToAlias(arg1Qcb); if (fieldToAlias.containsKey("id")) { state.addToWhere(arg2Alias + " = " + fieldToAlias.get("id")); } else { fieldToAlias.put("id", arg2Alias); bagConstraintToString(state, new BagConstraint(new QueryField(arg1Qcb), (c.getOp() == ConstraintOp.CONTAINS ? ConstraintOp.IN : ConstraintOp.NOT_IN), arg1Qcb.getIds()), q, schema); } } else { state.addToWhere(arg1Obj.getId() + " = " + arg2Alias); } state.addToWhere(" AND " + indirectTableAlias + "." + DatabaseUtil.getOutwardIndirectionColumnName(arg1ColDesc) + " = "); if (arg2 == null) { state.addToWhere("" + arg2Obj.getId()); } else { queryClassToString(state.getWhereBuffer(), arg2, q, schema, ID_ONLY, state); } state.addToWhere(loseBrackets ? "" : ")"); } } } /** * The maximum size a bag in a BagConstraint can be before we consider using a temporary table * instead. */ public static final int MAX_BAG_INLINE_SIZE = 100; /** * Converts a BagConstraint object into a String suitable for putting on an SQL query. * * @param state the object to place text into * @param c the BagConstraint object * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @throws ObjectStoreException if something goes wrong */ protected static void bagConstraintToString(State state, BagConstraint c, Query q, DatabaseSchema schema) throws ObjectStoreException { Class type = c.getQueryNode().getType(); String leftHandSide; if (c.getQueryNode() instanceof QueryEvaluable) { StringBuffer lhsBuffer = new StringBuffer(); queryEvaluableToString(lhsBuffer, (QueryEvaluable) c.getQueryNode(), q, state); leftHandSide = lhsBuffer.toString() + " IN ("; } else { StringBuffer lhsBuffer = new StringBuffer(); queryClassToString(lhsBuffer, (QueryClass) c.getQueryNode(), q, schema, ID_ONLY, state); leftHandSide = lhsBuffer.toString() + " IN ("; } SortedSet filteredBag = new TreeSet(); Iterator bagIter = c.getBag().iterator(); while (bagIter.hasNext()) { Object bagItem = bagIter.next(); if (type.isInstance(bagItem)) { if (bagItem instanceof InterMineObject) { filteredBag.add(((InterMineObject) bagItem).getId()); } else { filteredBag.add(bagItem); } } } if (filteredBag.isEmpty()) { state.addToWhere(c.getOp() == ConstraintOp.IN ? "false" : "true"); } else { if (filteredBag.size () < MAX_BAG_INLINE_SIZE || state.getBagTableNames().get(c) == null) { int needComma = 0; Iterator orIter = filteredBag.iterator(); while (orIter.hasNext()) { if (needComma == 0) { state.addToWhere((c.getOp() == ConstraintOp.IN ? (filteredBag.size() > 9000 ? "(" : "") : "(NOT (") + leftHandSide); } else if (needComma % 9000 == 0) { state.addToWhere(") OR " + leftHandSide); } else { state.addToWhere(", "); } needComma++; StringBuffer constraint = new StringBuffer(); objectToString(state.getWhereBuffer(), orIter.next()); } state.addToWhere(c.getOp() == ConstraintOp.IN ? (filteredBag.size() > 9000 ? "))" : ")") : ")))"); } else { if (c.getOp() == ConstraintOp.IN) { state.addToWhere(leftHandSide); } else { state.addToWhere("(NOT ("); state.addToWhere(leftHandSide); } state.addToWhere("SELECT value FROM "); state.addToWhere((String) state.getBagTableNames().get(c)); if (c.getOp() == ConstraintOp.IN) { state.addToWhere(")"); } else { state.addToWhere(")))"); } } } } /** * Converts an Object to a String, in a form suitable for SQL. * * @param buffer a StringBuffer to add text to * @param value the Object to convert * @throws ObjectStoreException if something goes wrong */ public static void objectToString(StringBuffer buffer, Object value) throws ObjectStoreException { if (value instanceof UnknownTypeValue) { buffer.append(value.toString()); } else if (value instanceof InterMineObject) { Integer id = ((InterMineObject) value).getId(); if (id == null) { throw new ObjectStoreException("InterMineObject found" + " without an ID set"); } buffer.append(id.toString()); } else if (value instanceof Date) { buffer.append(DatabaseUtil.objectToString(new Long(((Date) value).getTime()))); } else { buffer.append(DatabaseUtil.objectToString(value)); } } /** * Converts a QueryClass to a String. * * @param buffer the StringBuffer to add text to * @param qc the QueryClass to convert * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param kind the type of the output requested * @param state a State object * @throws ObjectStoreException if the model is internally inconsistent */ protected static void queryClassToString(StringBuffer buffer, QueryClass qc, Query q, DatabaseSchema schema, int kind, State state) throws ObjectStoreException { String alias = (String) q.getAliases().get(qc); Map fieldToAlias = state.getFieldToAlias(qc); if (alias == null) { throw new NullPointerException("A QueryClass is referenced by elements of a query," + " but the QueryClass is not in the FROM list of that query. QueryClass: " + qc + ", aliases: " + q.getAliases()); } if (kind == QUERY_SUBQUERY_CONSTRAINT) { buffer.append(DatabaseUtil.generateSqlCompatibleName(alias)) .append(".id"); } else { boolean needComma = false; String objectAlias = (String) state.getFieldToAlias(qc).get("OBJECT"); if ((kind != QUERY_SUBQUERY_FROM) && (objectAlias != null)) { buffer.append(objectAlias); if ((kind == QUERY_NORMAL) || (kind == QUERY_FOR_PRECOMP)) { buffer.append(" AS ") .append(alias.equals(alias.toLowerCase()) ? DatabaseUtil.generateSqlCompatibleName(alias) : "\"" + DatabaseUtil.generateSqlCompatibleName(alias) + "\""); } needComma = true; } if ((kind == QUERY_SUBQUERY_FROM) || (kind == NO_ALIASES_ALL_FIELDS) || ((kind == QUERY_NORMAL) && schema.isFlatMode()) || (kind == QUERY_FOR_PRECOMP)) { Iterator fieldIter = null; ClassDescriptor cld = schema.getModel().getClassDescriptorByName(qc.getType() .getName()); if (schema.isFlatMode() && (kind == QUERY_NORMAL)) { List iterators = new ArrayList(); DatabaseSchema.Fields fields = schema.getTableFields(schema .getTableMaster(cld)); iterators.add(fields.getAttributes().iterator()); iterators.add(fields.getReferences().iterator()); fieldIter = new CombinedIterator(iterators); } else { fieldIter = cld.getAllFieldDescriptors().iterator(); } Map fieldMap = new TreeMap(); while (fieldIter.hasNext()) { FieldDescriptor field = (FieldDescriptor) fieldIter.next(); String columnName = DatabaseUtil.getColumnName(field); if (columnName != null) { fieldMap.put(columnName, field); } } Iterator fieldMapIter = fieldMap.entrySet().iterator(); while (fieldMapIter.hasNext()) { Map.Entry fieldEntry = (Map.Entry) fieldMapIter.next(); FieldDescriptor field = (FieldDescriptor) fieldEntry.getValue(); String columnName = DatabaseUtil.getColumnName(field); if (needComma) { buffer.append(", "); } needComma = true; buffer.append((String) fieldToAlias.get(field.getName())); if (kind == QUERY_SUBQUERY_FROM) { buffer.append(" AS ") .append(DatabaseUtil.generateSqlCompatibleName(alias) + columnName); } else if ((kind == QUERY_NORMAL) || (kind == QUERY_FOR_PRECOMP)) { buffer.append(" AS ") .append(alias.equals(alias.toLowerCase()) ? DatabaseUtil.generateSqlCompatibleName(alias) + columnName : "\"" + DatabaseUtil.generateSqlCompatibleName(alias) + columnName.toLowerCase() + "\""); } } if (schema.isFlatMode() && schema.isTruncated(schema.getTableMaster(cld))) { buffer.append(", ") .append((String) fieldToAlias.get("objectclass")) .append(" AS ") .append(alias.equals(alias.toLowerCase()) ? DatabaseUtil.generateSqlCompatibleName(alias) + "objectclass" : "\"" + DatabaseUtil.generateSqlCompatibleName(alias) + "objectclass\""); } } else { if (needComma) { buffer.append(", "); } buffer.append(DatabaseUtil.generateSqlCompatibleName(alias)) .append(".id AS ") .append(alias.equals(alias.toLowerCase()) ? DatabaseUtil.generateSqlCompatibleName(alias) + "id" : "\"" + DatabaseUtil.generateSqlCompatibleName(alias) + "id" + "\""); } } } /** * Converts a QueryEvaluable into a String suitable for an SQL query String. * * @param buffer the StringBuffer to add text to * @param node the QueryEvaluable * @param q the Query * @param state a State object * @throws ObjectStoreException if something goes wrong */ protected static void queryEvaluableToString(StringBuffer buffer, QueryEvaluable node, Query q, State state) throws ObjectStoreException { if (node instanceof QueryField) { QueryField nodeF = (QueryField) node; FromElement nodeClass = nodeF.getFromElement(); Map aliasMap = state.getFieldToAlias(nodeClass); String classAlias = (String) aliasMap.get(nodeF.getFieldName()); buffer.append(classAlias); if (aliasMap instanceof AlwaysMap) { buffer.append(".") .append(DatabaseUtil.generateSqlCompatibleName(nodeF.getFieldName())) .append(nodeF.getSecondFieldName() == null ? "" : DatabaseUtil.generateSqlCompatibleName(nodeF .getSecondFieldName())); } } else if (node instanceof QueryExpression) { QueryExpression nodeE = (QueryExpression) node; if (nodeE.getOperation() == QueryExpression.SUBSTRING) { QueryEvaluable arg1 = nodeE.getArg1(); QueryEvaluable arg2 = nodeE.getArg2(); QueryEvaluable arg3 = nodeE.getArg3(); buffer.append("SUBSTR("); queryEvaluableToString(buffer, arg1, q, state); buffer.append(", "); queryEvaluableToString(buffer, arg2, q, state); if (arg3 != null) { buffer.append(", "); queryEvaluableToString(buffer, arg3, q, state); } buffer.append(")"); } else if (nodeE.getOperation() == QueryExpression.INDEX_OF) { QueryEvaluable arg1 = nodeE.getArg1(); QueryEvaluable arg2 = nodeE.getArg2(); buffer.append("STRPOS("); queryEvaluableToString(buffer, arg1, q, state); buffer.append(", "); queryEvaluableToString(buffer, arg2, q, state); buffer.append(")"); } else { QueryEvaluable arg1 = nodeE.getArg1(); QueryEvaluable arg2 = nodeE.getArg2(); String op = null; switch (nodeE.getOperation()) { case QueryExpression.ADD: op = " + "; break; case QueryExpression.SUBTRACT: op = " - "; break; case QueryExpression.MULTIPLY: op = " * "; break; case QueryExpression.DIVIDE: op = " / "; break; default: throw (new ObjectStoreException("Invalid QueryExpression operation: " + nodeE.getOperation())); } buffer.append("("); queryEvaluableToString(buffer, arg1, q, state); buffer.append(op); queryEvaluableToString(buffer, arg2, q, state); buffer.append(")"); } } else if (node instanceof QueryFunction) { QueryFunction nodeF = (QueryFunction) node; switch (nodeF.getOperation()) { case QueryFunction.COUNT: buffer.append("COUNT(*)"); break; case QueryFunction.SUM: buffer.append("SUM("); queryEvaluableToString(buffer, nodeF.getParam(), q, state); buffer.append(")"); break; case QueryFunction.AVERAGE: buffer.append("AVG("); queryEvaluableToString(buffer, nodeF.getParam(), q, state); buffer.append(")"); break; case QueryFunction.MIN: buffer.append("MIN("); queryEvaluableToString(buffer, nodeF.getParam(), q, state); buffer.append(")"); break; case QueryFunction.MAX: buffer.append("MAX("); queryEvaluableToString(buffer, nodeF.getParam(), q, state); buffer.append(")"); break; case QueryFunction.LOWER: buffer.append("LOWER("); queryEvaluableToString(buffer, nodeF.getParam(), q, state); buffer.append(")"); break; case QueryFunction.UPPER: buffer.append("UPPER("); queryEvaluableToString(buffer, nodeF.getParam(), q, state); buffer.append(")"); break; default: throw (new ObjectStoreException("Invalid QueryFunction operation: " + nodeF.getOperation())); } } else if (node instanceof QueryValue) { QueryValue nodeV = (QueryValue) node; Object value = nodeV.getValue(); objectToString(buffer, value); } else if (node instanceof QueryCast) { buffer.append("("); queryEvaluableToString(buffer, ((QueryCast) node).getValue(), q, state); buffer.append(")::"); String torqueTypeName = TorqueModelOutput.generateJdbcType(node.getType() .getName()); SchemaType torqueType = SchemaType.getEnum(torqueTypeName); Platform torquePlatform = PlatformFactory.getPlatformFor(state.getDb().getPlatform() .toLowerCase()); Domain torqueDomain = torquePlatform.getDomainForSchemaType(torqueType); buffer.append(torqueDomain.getSqlType()); } else { throw (new ObjectStoreException("Invalid QueryEvaluable: " + node)); } } /** * Builds a String representing the SELECT component of the Sql query. * * @param state the current Sql Query state * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param kind the kind of output requested * @return a String * @throws ObjectStoreException if something goes wrong */ protected static String buildSelectComponent(State state, Query q, DatabaseSchema schema, int kind) throws ObjectStoreException { boolean needComma = false; StringBuffer retval = new StringBuffer(); Iterator iter = q.getSelect().iterator(); while (iter.hasNext()) { QuerySelectable node = (QuerySelectable) iter.next(); String alias = (String) q.getAliases().get(node); if (node instanceof QueryClass) { if (needComma) { retval.append(", "); } needComma = true; queryClassToString(retval, (QueryClass) node, q, schema, kind, state); } else if (node instanceof QueryEvaluable) { if (needComma) { retval.append(", "); } needComma = true; queryEvaluableToString(retval, (QueryEvaluable) node, q, state); if ((kind == QUERY_NORMAL) || (kind == QUERY_FOR_PRECOMP)) { retval.append(" AS " + (alias.equals(alias.toLowerCase()) ? DatabaseUtil.generateSqlCompatibleName(alias) : "\"" + DatabaseUtil.generateSqlCompatibleName(alias) + "\"")); } else if (kind == QUERY_SUBQUERY_FROM) { retval.append(" AS " + DatabaseUtil.generateSqlCompatibleName(alias)); } } else if ((node instanceof QueryFieldPathExpression) && ("id".equals(((QueryFieldPathExpression) node).getFieldName()))) { QueryFieldPathExpression pe = (QueryFieldPathExpression) node; if (needComma) { retval.append(", "); } needComma = true; // This is effectively a foreign key. Because we don't add this SELECT item to the // artificial ORDER BY list, we must assert that the QueryClass or its ID already // exists on the SELECT list - a weaker assertion than that we make for all // other QueryFieldPathExpressions anyway. if (!q.getSelect().contains(pe.getQueryClass())) { throw new ObjectStoreException("Foreign key specified by" + " QueryFieldPathExpression on SELECT list, but parent QueryClass not" + " present on SELECT list"); } retval.append((String) state.getFieldToAlias(pe.getQueryClass()) .get(pe.getReferenceName())) .append(" AS ") .append(DatabaseUtil.generateSqlCompatibleName(alias)); } else if (node instanceof QueryPathExpression) { // Do nothing } else { throw new ObjectStoreException("Unknown object in SELECT list: " + node.getClass()); } } iter = state.getOrderBy().iterator(); while (iter.hasNext()) { String orderByField = (String) iter.next(); if (needComma) { retval.append(", "); } needComma = true; retval.append(orderByField); } return retval.toString(); } /** * Builds a String representing the GROUP BY component of the Sql query. * * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @param state a State object * @return a String * @throws ObjectStoreException if something goes wrong */ protected static String buildGroupBy(Query q, DatabaseSchema schema, State state) throws ObjectStoreException { StringBuffer retval = new StringBuffer(); boolean needComma = false; Iterator groupByIter = q.getGroupBy().iterator(); while (groupByIter.hasNext()) { QueryNode node = (QueryNode) groupByIter.next(); retval.append(needComma ? ", " : " GROUP BY "); needComma = true; if (node instanceof QueryClass) { queryClassToString(retval, (QueryClass) node, q, schema, NO_ALIASES_ALL_FIELDS, state); } else { queryEvaluableToString(retval, (QueryEvaluable) node, q, state); } } return retval.toString(); } /** * Builds a String representing the ORDER BY component of the Sql query. * * @param state the current Sql Query state * @param q the Query * @param schema the DatabaseSchema in which to look up metadata * @return a String * @throws ObjectStoreException if something goes wrong */ protected static String buildOrderBy(State state, Query q, DatabaseSchema schema) throws ObjectStoreException { StringBuffer retval = new StringBuffer(); boolean needComma = false; Iterator orderByIter = q.getEffectiveOrderBy().iterator(); while (orderByIter.hasNext()) { Object node = orderByIter.next(); if (!((node instanceof QueryValue) || (node instanceof QueryPathExpression))) { retval.append(needComma ? ", " : " ORDER BY "); needComma = true; if (node instanceof QueryClass) { queryClassToString(retval, (QueryClass) node, q, schema, ID_ONLY, state); } else if (node instanceof QueryObjectReference) { QueryObjectReference ref = (QueryObjectReference) node; StringBuffer buffer = new StringBuffer(); buffer.append((String) state.getFieldToAlias(ref.getQueryClass()) .get(ref.getFieldName())); retval.append(buffer.toString()); if (q.isDistinct()) { if (q.getSelect().contains(ref.getQueryClass())) { // This means that the field's QueryClass is present in the SELECT list, // so adding the field artificially will not alter the number of rows // of a DISTINCT query. if (!schema.isFlatMode()) { buffer.append(" AS ") .append(state.getOrderByAlias()); state.addToOrderBy(buffer.toString()); } } else { throw new ObjectStoreException("Reference " + buffer.toString() + " in the ORDER BY list must be in the SELECT list, or the" + " whole QueryClass must be in the SELECT list, or the" + " query made non-distinct"); } } } else { queryEvaluableToString(retval, (QueryEvaluable) node, q, state); if ((!q.getSelect().contains(node)) && q.isDistinct() && (node instanceof QueryField)) { FromElement fe = ((QueryField) node).getFromElement(); StringBuffer buffer = new StringBuffer(); queryEvaluableToString(buffer, (QueryEvaluable) node, q, state); if (q.getSelect().contains(fe)) { // This means that this field is not in the SELECT list, but its // FromElement is, therefore adding it artificially to the SELECT // list will not alter the number of rows of a DISTINCT query. if (!schema.isFlatMode()) { buffer.append(" AS ") .append(state.getOrderByAlias()); state.addToOrderBy(buffer.toString()); } } else if (fe instanceof QueryClass) { throw new ObjectStoreException("Field " + buffer.toString() + " in the ORDER BY list must be in the SELECT list, or the" + " whole QueryClass " + fe.toString() + " must be in the" + " SELECT list, or the query made non-distinct"); } else { throw new ObjectStoreException("Field " + buffer.toString() + " in the ORDER BY list must be in the SELECT list, or the" + " query made non-distinct"); } } } } } return retval.toString(); } private static class State { private StringBuffer whereText = new StringBuffer(); private StringBuffer fromText = new StringBuffer(); private Set orderBy = new LinkedHashSet(); private int number = 0; private Map fromToFieldToAlias = new HashMap(); private Database db; // a Map from BagConstraints to table names, where the table contains the contents of the // bag that are relevant for the BagConstraint private Map bagTableNames = new HashMap(); public State() { // empty } public String getWhere() { // a hacky fix for #731: String where = whereText.toString(); //if (where.startsWith("(") && where.endsWith(")")) { // where = where.substring(1, where.length() - 1); return (where.length() == 0 ? "" : " WHERE " + where); } public StringBuffer getWhereBuffer() { return whereText; } public String getFrom() { return fromText.toString(); } public void addToWhere(String text) { whereText.append(text); } public void addToFrom(String text) { if (fromText.length() == 0) { fromText.append(" FROM ").append(text); } else { fromText.append(", ").append(text); } } public String getIndirectAlias() { return "indirect" + (number++); } public String getOrderByAlias() { return "orderbyfield" + (number++); } public void addToOrderBy(String s) { orderBy.add(s); } public Set getOrderBy() { return orderBy; } public Map getFieldToAlias(FromElement from) { Map retval = (Map) fromToFieldToAlias.get(from); if (retval == null) { retval = new HashMap(); fromToFieldToAlias.put(from, retval); } return retval; } public void setFieldToAlias(FromElement from, Map map) { fromToFieldToAlias.put(from, map); } public void setBagTableNames(Map bagTableNames) { if (bagTableNames != null) { this.bagTableNames = bagTableNames; } } public Map getBagTableNames() { return bagTableNames; } public void setDb(Database db) { this.db = db; } public Database getDb() { return db; } } private static class CacheEntry { private TreeMap cached = new TreeMap(); private int lastOffset; private String lastSQL; public CacheEntry(int lastOffset, String lastSQL) { this.lastOffset = lastOffset; this.lastSQL = lastSQL; } public TreeMap getCached() { return cached; } public void setLast(int lastOffset, String lastSQL) { this.lastOffset = lastOffset; this.lastSQL = lastSQL; } public int getLastOffset() { return lastOffset; } public String getLastSQL() { return lastSQL; } } }
package com.exedio.copernica; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; public class DataServletTest extends AbstractWebTest { public void testError() throws Exception { final String prefix = "http://localhost:8080/copetest-hsqldb/data/"; final long textLastModified = assertURL(new URL(prefix + "HttpEntityItem/file/0.txt")); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/0.zick"))); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/0."))); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/0"))); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/0"), textLastModified-1, false)); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/0"), textLastModified, true)); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/0"), textLastModified+5000, true)); assertEquals(textLastModified, assertURL(new URL(prefix + "HttpEntityItem/file/2.unknownma.unknownmi"), "unknownma/unknownmi")); final HttpURLConnection conn = (HttpURLConnection)((new URL(prefix + "statistics")).openConnection()); conn.connect(); assertEquals(200, conn.getResponseCode()); } private long assertURL(final URL url) throws IOException { return assertURL(url, -1, false); } private long assertURL(final URL url, final String contentType) throws IOException { return assertURL(url, contentType, -1, false); } private long assertURL(final URL url, final long ifModifiedSince, final boolean expectNotModified) throws IOException { return assertURL(url, "text/plain", ifModifiedSince, expectNotModified); } private long assertURL(final URL url, final String contentType, final long ifModifiedSince, final boolean expectNotModified) throws IOException { final Date before = new Date(); final HttpURLConnection conn = (HttpURLConnection)url.openConnection(); if(ifModifiedSince>=0) conn.setIfModifiedSince(ifModifiedSince); conn.connect(); assertEquals(expectNotModified ? 304 : 200, conn.getResponseCode()); final long date = conn.getDate(); final Date after = new Date(); assertWithin(3000, before, after, new Date(date)); final long lastModified = conn.getLastModified(); //System.out.println("LastModified: "+new Date(lastModified)); assertTrue((date+1000)>=lastModified); assertEquals(expectNotModified ? null : contentType, conn.getContentType()); // TODO: content type should be set on 304 //System.out.println("Expires: "+new Date(textConn.getExpiration())); assertWithin(new Date(date+4000), new Date(date+6000), new Date(conn.getExpiration())); assertEquals(expectNotModified ? -1 : 66, conn.getContentLength()); final BufferedReader is = new BufferedReader(new InputStreamReader((InputStream)conn.getInputStream())); if(!expectNotModified) { assertEquals("This is an example file", is.readLine()); assertEquals("for testing data", is.readLine()); assertEquals("attributes in copernica.", is.readLine()); } assertEquals(null, is.readLine()); is.close(); //textConn.setIfModifiedSince(); return lastModified; } }
package org.opencms.main; import org.opencms.workplace.CmsWorkplace; /** * Contains the settings to handle HTTP basic authentication.<p> * * These settings control whether a browser-based pop-up dialog should be used for * authentication, or of the user should be redirected to an OpenCms URI for a * form-based authentication.<p> * * Since the URI for the form-based authentication is a system wide setting, users * are able to specify different authentication forms in a property "login-form" on * resources that require authentication.<p> * * @author Thomas Weckert * @author Carsten Weinholz * * @version $Revision: 1.3 $ * * @since 6.0.0 */ public class CmsHttpAuthenticationSettings { /** The mechanism name for basic HTTP authentication. */ public static final String AUTHENTICATION_BASIC = "BASIC"; /** The mechanism name for form based authentication. */ public static final String AUTHENTICATION_FORM = "FORM"; /** The URI of the default authentication form. */ public static final String DEFAULT_AUTHENTICATION_URI = CmsWorkplace.VFS_PATH_WORKPLACE + "action/authenticate.html"; /** The URI of the system wide login form if browser-based HTTP basic authentication is disabled. */ private String m_formBasedHttpAuthenticationUri; /** The mechanism used in browser-based HTTP authentication. */ private String m_browserBasedAuthenticationMechanism; /** Boolean flag to enable or disable browser-based HTTP basic authentication. */ private boolean m_useBrowserBasedHttpAuthentication; /** * Default constructor.<p> */ public CmsHttpAuthenticationSettings() { super(); m_useBrowserBasedHttpAuthentication = true; m_browserBasedAuthenticationMechanism = null; m_formBasedHttpAuthenticationUri = null; } /** * Returns the browser based authentication mechanism or <code>null</code> if unused. * * @return "BASIC" in case of browser based basic authentication, "FORM" in case of form based authentication or the alternative mechanism or <code>null</code> if unused. */ public String getBrowserBasedAuthenticationMechanism() { if (m_useBrowserBasedHttpAuthentication) { return AUTHENTICATION_BASIC; } else if (m_browserBasedAuthenticationMechanism != null) { return m_browserBasedAuthenticationMechanism; } else if (m_formBasedHttpAuthenticationUri != null) { return AUTHENTICATION_FORM; } else { return null; } } /** * Returns the URI of the system wide login form if browser-based HTTP basic authentication is disabled.<p> * * @return the URI of the system wide login form if browser-based HTTP basic authentication is disabled */ public String getFormBasedHttpAuthenticationUri() { return m_formBasedHttpAuthenticationUri; } /** * Sets the URI of the system wide login form if browser-based HTTP basic authentication is disabled.<p> * * @param uri the URI of the system wide login form if browser-based HTTP basic authentication is disabled to set */ public void setFormBasedHttpAuthenticationUri(String uri) { m_formBasedHttpAuthenticationUri = uri; } /** * Sets if browser-based HTTP basic authentication is enabled or disabled.<p> * * @param value a boolean value to specifiy if browser-based HTTP basic authentication should be enabled */ public void setUseBrowserBasedHttpAuthentication(boolean value) { m_useBrowserBasedHttpAuthentication = value; m_browserBasedAuthenticationMechanism = null; } /** * Sets if browser-based HTTP basic authentication is enabled or disabled.<p> * * @param value a string {<code>"true"</code>|<code>"false"</code>} to specify if browser-based HTTP basic authentication should be enabled; * if another string is provided, the flag for browser based basic authentication is disabled and the value is stored as authentication mechanism. */ public void setUseBrowserBasedHttpAuthentication(String value) { m_useBrowserBasedHttpAuthentication = Boolean.valueOf(value).booleanValue(); if (!m_useBrowserBasedHttpAuthentication && !value.equalsIgnoreCase(Boolean.FALSE.toString())) { if (value.equalsIgnoreCase(AUTHENTICATION_BASIC)) { m_useBrowserBasedHttpAuthentication = true; } else { m_browserBasedAuthenticationMechanism = value; m_useBrowserBasedHttpAuthentication = false; } } } /** * Tests if browser-based HTTP basic authentication is enabled or disabled.<p> * * @return true if browser-based HTTP basic authentication is enabled */ public boolean useBrowserBasedHttpAuthentication() { return m_useBrowserBasedHttpAuthentication; } }
package dr.app.beauti.generator; import dr.app.beauti.components.ComponentFactory; import dr.app.beauti.options.*; import dr.app.beauti.types.PriorType; import dr.app.beauti.types.TreePriorType; import dr.app.beauti.util.XMLWriter; import dr.evolution.util.Taxa; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.MSSD.CTMCScalePriorParser; import dr.evomodelxml.tree.MonophylyStatisticParser; import dr.inference.model.ParameterParser; import dr.inferencexml.distribution.CachedDistributionLikelihoodParser; import dr.inferencexml.distribution.PriorParsers; import dr.inferencexml.model.BooleanLikelihoodParser; import dr.inferencexml.model.OneOnXPriorParser; import dr.util.Attribute; import java.util.ArrayList; import java.util.Map; /** * @author Alexei Drummond * @author Walter Xie */ public class ParameterPriorGenerator extends Generator { public ParameterPriorGenerator(BeautiOptions options, ComponentFactory[] components) { super(options, components); } /** * Write the priors for each parameter * * @param writer the writer */ void writeParameterPriors(XMLWriter writer) { boolean first = true; for (Map.Entry<Taxa, Boolean> taxaBooleanEntry : options.taxonSetsMono.entrySet()) { if (taxaBooleanEntry.getValue()) { if (first) { writer.writeOpenTag(BooleanLikelihoodParser.BOOLEAN_LIKELIHOOD); first = false; } final String taxaRef = "monophyly(" + taxaBooleanEntry.getKey().getId() + ")"; writer.writeIDref(MonophylyStatisticParser.MONOPHYLY_STATISTIC, taxaRef); } } if (!first) { writer.writeCloseTag(BooleanLikelihoodParser.BOOLEAN_LIKELIHOOD); } ArrayList<Parameter> parameters = options.selectParameters(); for (Parameter parameter : parameters) { if (!(parameter.priorType == PriorType.NONE_TREE_PRIOR || parameter.priorType == PriorType.NONE_STATISTIC)) { if (parameter.isCached) { writeCachedParameterPrior(parameter, writer); } else {//if (parameter.priorType != PriorType.UNIFORM_PRIOR || parameter.isNodeHeight) { if (options.clockModelOptions.isNodeCalibrated(parameter) // not treeModel.rootHeight && options.getPartitionTreePriors().get(0).getNodeHeightPrior() == TreePriorType.YULE) { if (parameter.taxaId != null) { for (Taxa taxa : options.taxonSets) { if (taxa.getId().equalsIgnoreCase(parameter.getBaseName())) { PartitionTreeModel model = options.taxonSetsTreeModel.get(taxa); if (!(options.getKeysFromValue(options.taxonSetsTreeModel, model).size() == 1 && options.taxonSetsMono.get((Taxa) options.getKeysFromValue(options.taxonSetsTreeModel, model).get(0)))) { writeParameterPrior(parameter, writer); } } } } } else { writeParameterPrior(parameter, writer); } } } } } private void writeCachedParameterPrior(Parameter parameter, XMLWriter writer) { writer.writeOpenTag(CachedDistributionLikelihoodParser.CACHED_PRIOR); writeParameterPrior(parameter, writer); writeParameterIdref(writer, parameter); writer.writeCloseTag(CachedDistributionLikelihoodParser.CACHED_PRIOR); } /** * Write the priors for each parameter * * @param parameter the parameter * @param writer the writer */ public void writeParameterPrior(Parameter parameter, XMLWriter writer) { // if there is a truncation then put it at the top so it short-circuits any other prior // calculations if (parameter.priorType == PriorType.UNIFORM_PRIOR || parameter.isTruncated) { writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.getLowerBound()), new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.getUpperBound()) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR); } switch (parameter.priorType) { case UNIFORM_PRIOR: // already handled, above // writer.writeOpenTag(PriorParsers.UNIFORM_PRIOR, // new Attribute[]{ // new Attribute.Default<String>(PriorParsers.LOWER, "" + parameter.truncationLower), // new Attribute.Default<String>(PriorParsers.UPPER, "" + parameter.truncationUpper) // writeParameterIdref(writer, parameter); // writer.writeCloseTag(PriorParsers.UNIFORM_PRIOR); break; case EXPONENTIAL_PRIOR: writer.writeOpenTag(PriorParsers.EXPONENTIAL_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.mean), new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.offset) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.EXPONENTIAL_PRIOR); break; case LAPLACE_PRIOR: writer.writeOpenTag(PriorParsers.LAPLACE_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.mean), new Attribute.Default<String>(PriorParsers.SCALE, "" + parameter.scale) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.LAPLACE_PRIOR); break; case TRUNC_NORMAL_PRIOR: // this will be removed - can add a truncation to any prior case NORMAL_PRIOR: writer.writeOpenTag(PriorParsers.NORMAL_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.mean), new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.stdev) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.NORMAL_PRIOR); break; case LOGNORMAL_PRIOR: writer.writeOpenTag(PriorParsers.LOG_NORMAL_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.mean), new Attribute.Default<String>(PriorParsers.STDEV, "" + parameter.stdev), new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.offset), new Attribute.Default<Boolean>(PriorParsers.MEAN_IN_REAL_SPACE, parameter.isMeanInRealSpace()) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.LOG_NORMAL_PRIOR); break; case GAMMA_PRIOR: writer.writeOpenTag(PriorParsers.GAMMA_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.SHAPE, "" + parameter.shape), new Attribute.Default<String>(PriorParsers.SCALE, "" + parameter.scale), new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.offset) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.GAMMA_PRIOR); break; case INVERSE_GAMMA_PRIOR: writer.writeOpenTag(PriorParsers.INVGAMMA_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.SHAPE, "" + parameter.shape), new Attribute.Default<String>(PriorParsers.SCALE, "" + parameter.scale), new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.offset) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.INVGAMMA_PRIOR); break; case ONE_OVER_X_PRIOR: writer.writeOpenTag(OneOnXPriorParser.ONE_ONE_X_PRIOR); writeParameterIdref(writer, parameter); writer.writeCloseTag(OneOnXPriorParser.ONE_ONE_X_PRIOR); break; case POISSON_PRIOR: writer.writeOpenTag(PriorParsers.POISSON_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.MEAN, "" + parameter.mean), new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.offset) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.POISSON_PRIOR); break; case BETA_PRIOR: writer.writeOpenTag(PriorParsers.BETA_PRIOR, new Attribute[]{ new Attribute.Default<String>(PriorParsers.SHAPE, "" + parameter.shape), new Attribute.Default<String>(PriorParsers.SHAPEB, "" + parameter.shapeB), new Attribute.Default<String>(PriorParsers.OFFSET, "" + parameter.offset) }); writeParameterIdref(writer, parameter); writer.writeCloseTag(PriorParsers.BETA_PRIOR); break; case CMTC_RATE_REFERENCE_PRIOR: writer.writeOpenTag(CTMCScalePriorParser.MODEL_NAME); writer.writeOpenTag(CTMCScalePriorParser.SCALEPARAMETER); writeParameterIdref(writer, parameter); writer.writeCloseTag(CTMCScalePriorParser.SCALEPARAMETER); // Find correct tree for this rate parameter PartitionTreeModel treeModel = null; for (int i = 0; i < options.getPartitionClockModels().size(); ++i) { PartitionClockModel pcm = options.getPartitionClockModels().get(i); if (pcm.getClockRateParam() == parameter) { treeModel = options.getPartitionTreeModels().get(i); break; } } writer.writeIDref(TreeModel.TREE_MODEL, treeModel.getPrefix() + TreeModel.TREE_MODEL); writer.writeCloseTag(CTMCScalePriorParser.MODEL_NAME); break; case NORMAL_HPM_PRIOR: case LOGNORMAL_HPM_PRIOR: // Do nothing, densities are already in a distributionLikelihood break; default: throw new IllegalArgumentException("Unknown priorType"); } } private void writeParameterIdref(XMLWriter writer, Parameter parameter) { if (parameter.isStatistic) { writer.writeIDref("statistic", parameter.getName()); } else { writer.writeIDref(ParameterParser.PARAMETER, parameter.getName()); } } }
package org.pentaho.di.trans.steps.xmloutput; import java.io.File; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Converts input rows to one or more XML files. * * @author Matt * @since 14-jan-2006 */ public class XMLOutput extends BaseStep implements StepInterface { private XMLOutputMeta meta; private XMLOutputData data; public XMLOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (XMLOutputMeta) smi; data = (XMLOutputData) sdi; Object[] r; boolean result = true; r = getRow(); // This also waits for a row to be finished. if(first && meta.isDoNotOpenNewFileInit()) { // no more input to be expected... // In this case, no file was opened. if (r == null) { setOutputDone(); return false; } if (openNewFile()) { data.OpenedNewFile=true; } else { logError("Couldn't open file " + meta.getFileName()); //$NON-NLS-1$ setErrors(1L); return false; } } if ((r != null && getLinesOutput() > 0 && meta.getSplitEvery() > 0 && (getLinesOutput() % meta.getSplitEvery()) == 0)) { // Done with this part or with everything. closeFile(); // Not finished: open another file... if (r != null) { if (!openNewFile()) { logError("Unable to open new file (split #" + data.splitnr + "..."); //$NON-NLS-1$ //$NON-NLS-2$ setErrors(1); return false; } } } if (r == null) // no more input to be expected... { setOutputDone(); return false; } writeRowToFile(getInputRowMeta(), r); data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); putRow(data.outputRowMeta, r); // in case we want it to go further... if (checkFeedback(getLinesOutput())) logBasic("linenr " + getLinesOutput()); //$NON-NLS-1$ return result; } private void writeRowToFile(RowMetaInterface rowMeta, Object[] r) throws KettleException { try { if (first) { data.formatRowMeta = rowMeta.clone(); first = false; data.fieldnrs = new int[meta.getOutputFields().length]; for (int i = 0; i < meta.getOutputFields().length; i++) { data.fieldnrs[i] = data.formatRowMeta.indexOfValue(meta.getOutputFields()[i].getFieldName()); if (data.fieldnrs[i] < 0) { throw new KettleException("Field [" + meta.getOutputFields()[i].getFieldName()+ "] couldn't be found in the input stream!"); //$NON-NLS-1$ //$NON-NLS-2$ } // Apply the formatting settings to the valueMeta object... ValueMetaInterface valueMeta = data.formatRowMeta.getValueMeta(data.fieldnrs[i]); XMLField field = meta.getOutputFields()[i]; valueMeta.setConversionMask(field.getFormat()); valueMeta.setLength(field.getLength(), field.getPrecision()); valueMeta.setDecimalSymbol(field.getDecimalSymbol()); valueMeta.setGroupingSymbol(field.getGroupingSymbol()); valueMeta.setCurrencySymbol(field.getCurrencySymbol()); } } if (meta.getOutputFields() == null || meta.getOutputFields().length == 0) { /* * Write all values in stream to text file. */ // OK, write a new row to the XML file: data.writer.write((" <" + meta.getRepeatElement() + ">").toCharArray()); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < data.formatRowMeta.size(); i++) { // Put a space between the XML elements of the row if (i > 0) data.writer.write(' '); ValueMetaInterface valueMeta = data.formatRowMeta.getValueMeta(i); Object valueData = r[i]; writeField(valueMeta, valueData, valueMeta.getName()); } } else { /* * Only write the fields specified! */ // Write a new row to the XML file: data.writer.write((" <" + meta.getRepeatElement() + ">").toCharArray()); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < meta.getOutputFields().length; i++) { XMLField outputField = meta.getOutputFields()[i]; if (i > 0) data.writer.write(' '); // a space between // elements ValueMetaInterface valueMeta = data.formatRowMeta.getValueMeta(data.fieldnrs[i]); Object valueData = r[data.fieldnrs[i]]; String elementName = outputField.getElementName(); if ( Const.isEmpty(elementName) ) { elementName = outputField.getFieldName(); } if (!(valueMeta.isNull(valueData) && meta.isOmitNullValues())) { writeField(valueMeta, valueData, elementName); } } } data.writer.write((" </" + meta.getRepeatElement() + ">").toCharArray()); //$NON-NLS-1$ //$NON-NLS-2$ data.writer.write(Const.CR.toCharArray()); } catch (Exception e) { throw new KettleException("Error writing XML row :" + e.toString() + Const.CR + "Row: " + getInputRowMeta().getString(r), e); //$NON-NLS-1$ //$NON-NLS-2$ } incrementLinesOutput(); } private void writeField(ValueMetaInterface valueMeta, Object valueData, String element) throws KettleStepException { try { String str = XMLHandler.addTagValue(element, valueMeta.getString(valueData), false); if (str != null) data.writer.write(str.toCharArray()); } catch (Exception e) { throw new KettleStepException("Error writing line :", e); //$NON-NLS-1$ } } public String buildFilename(boolean ziparchive) { return meta.buildFilename(this, getCopy(), data.splitnr, ziparchive); } public boolean openNewFile() { boolean retval = false; data.writer = null; try { if (meta.isServletOutput()) { data.writer = getTrans().getServletPrintWriter(); if (meta.getEncoding() != null && meta.getEncoding().length() > 0) { data.writer.write(XMLHandler.getXMLHeader(meta.getEncoding()).toCharArray()); } else { data.writer.write(XMLHandler.getXMLHeader(Const.XML_ENCODING).toCharArray()); } } else { FileObject file = KettleVFS.getFileObject(buildFilename(true), getTransMeta()); if(meta.isAddToResultFiles()) { // Add this to the result file names... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname()); resultFile.setComment("This file was created with a xml output step"); //$NON-NLS-1$ addResultFile(resultFile); } OutputStream outputStream; if (meta.isZipped()) { OutputStream fos = KettleVFS.getOutputStream(file, false); data.zip = new ZipOutputStream(fos); File entry = new File(buildFilename(false)); ZipEntry zipentry = new ZipEntry(entry.getName()); zipentry.setComment("Compressed by Kettle"); //$NON-NLS-1$ data.zip.putNextEntry(zipentry); outputStream = data.zip; } else { OutputStream fos = KettleVFS.getOutputStream(file, false); outputStream = fos; } if (meta.getEncoding() != null && meta.getEncoding().length() > 0) { logBasic("Opening output stream in encoding: " + meta.getEncoding()); //$NON-NLS-1$ data.writer = new OutputStreamWriter(outputStream, meta.getEncoding()); data.writer.write(XMLHandler.getXMLHeader(meta.getEncoding()).toCharArray()); } else { logBasic("Opening output stream in default encoding : " + Const.XML_ENCODING); //$NON-NLS-1$ data.writer = new OutputStreamWriter(outputStream); data.writer.write(XMLHandler.getXMLHeader(Const.XML_ENCODING).toCharArray()); } } // Add the name space if defined StringBuffer nameSpace = new StringBuffer(); if ((meta.getNameSpace() != null) && (!"".equals(meta.getNameSpace()))) { //$NON-NLS-1$ nameSpace.append(" xmlns=\""); //$NON-NLS-1$ nameSpace.append(meta.getNameSpace()); nameSpace.append("\""); //$NON-NLS-1$ } // OK, write the header & the parent element: data.writer.write(("<" + meta.getMainElement() + nameSpace.toString() + ">" + Const.CR).toCharArray()); //$NON-NLS-1$//$NON-NLS-2$ retval = true; } catch (Exception e) { logError("Error opening new file : " + e.toString()); //$NON-NLS-1$ } // System.out.println("end of newFile(), splitnr="+splitnr); data.splitnr++; return retval; } private boolean closeFile() { boolean retval = false; if(data.OpenedNewFile) { try { // Close the parent element data.writer.write(("</" + meta.getMainElement() + ">" + Const.CR).toCharArray()); //$NON-NLS-1$ //$NON-NLS-2$ // System.out.println("Closed xml file..."); data.writer.close(); if (meta.isZipped()) { // System.out.println("close zip entry "); data.zip.closeEntry(); // System.out.println("finish file..."); data.zip.finish(); data.zip.close(); } retval = true; } catch (Exception e) { } } return retval; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (XMLOutputMeta) smi; data = (XMLOutputData) sdi; if (super.init(smi, sdi)) { data.splitnr = 0; if(!meta.isDoNotOpenNewFileInit()) { if (openNewFile()) { data.OpenedNewFile=true; return true; } else { logError("Couldn't open file " + meta.getFileName()); //$NON-NLS-1$ setErrors(1L); stopAll(); } }else return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (XMLOutputMeta) smi; data = (XMLOutputData) sdi; closeFile(); super.dispose(smi, sdi); } }
package com.metacodestudio.hotsuploader; import com.metacodestudio.hotsuploader.controllers.HomeController; import com.metacodestudio.hotsuploader.files.FileHandler; import io.datafx.controller.flow.Flow; import io.datafx.controller.flow.FlowHandler; import io.datafx.controller.flow.container.DefaultFlowContainer; import io.datafx.controller.flow.context.ViewFlowContext; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import java.io.File; import java.net.URL; public class Client extends Application { private static File hotsRoot; public static File getHotsRoot() { return hotsRoot; } public static void main(String[] args) { hotsRoot = getRootDirectory(); Application.launch(Client.class, args); } private static File getRootDirectory() { StringBuilder builder = new StringBuilder(System.getProperty("user.home")); if (isWindows()) { builder.append("\\Documents\\Heroes of the Storm\\Accounts\\"); } else if (isMacintosh()) { builder.append("/Library/Application Support/Blizzard/Heroes of the Storm/Accounts/"); } else { throw new UnsupportedOperationException("This application requires Windows or Macintosh OSX to run"); } return new File(builder.toString()); } private static boolean isMacintosh() { String osName = System.getProperty("os.name"); return osName.contains("Mac"); } private static boolean isWindows() { String osName = System.getProperty("os.name"); return osName.contains("Windows"); } @Override public void start(final Stage primaryStage) throws Exception { ClassLoader loader = ClassLoader.getSystemClassLoader(); URL logo = loader.getResource("images/logo.png"); assert logo != null; primaryStage.getIcons().add(new Image(logo.toString())); Flow flow = new Flow(HomeController.class); FlowHandler flowHandler = flow.createHandler(new ViewFlowContext()); flowHandler.getFlowContext().register(new FileHandler(getRootDirectory())); DefaultFlowContainer container = new DefaultFlowContainer(); StackPane pane = flowHandler.start(container); primaryStage.setScene(new Scene(pane)); primaryStage.setOnCloseRequest(event -> System.exit(0)); primaryStage.show(); } }