List of usage examples for java.util.concurrent.atomic AtomicBoolean get
public final boolean get()
From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java
/** * Update the given items for the given workspace. * <p>//from w w w. j ava 2 s .c o m * <!-- Event Origination Info --> * <p> * This method is an <b>core event origination point</b>. The * {@link EventSource} object that accompanies each event fired by this * method describes the execution context (current thread, etc.) when and * where this method was invoked. * * @param requests * the request items to process (must not be null; items in array * must not be null). To update all items in this workspace, pass a * single {@link GetRequest} with a null itemSpec. * @param options * options for the get operation (must not be <code>null</code>) * @param itemPropertyFilters * a list of versioned item properties to return with each get * operation (may be <code>null</code>) * @param alwaysQueryConflicts * true to always query conflicts, false if we may omit this step * @param conflicts * a reference to a list of conflicts to return (must not be * <code>null</code>) * @return a GetStatus instance with the results of the get operation. */ public GetStatus get(final GetRequest[] requests, final GetOptions options, String[] itemPropertyFilters, final boolean alwaysQueryConflicts, final AtomicReference<Conflict[]> conflicts) { Check.notNull(requests, "requests"); //$NON-NLS-1$ Check.notNull(options, "options"); //$NON-NLS-1$ Check.notNull(conflicts, "conflicts"); //$NON-NLS-1$ // Using web service directly so merge filters configured on client itemPropertyFilters = client.mergeWithDefaultItemPropertyFilters(itemPropertyFilters); client.getEventEngine() .fireOperationStarted(new GetOperationStartedEvent(EventSource.newFromHere(), this, requests)); /* * Always work toward 100 work units. The progress indicator will only * be accurate for gets that fit in one page (result set). If we have to * process more than one set we'll fill up the task monitor prematurely, * which is not an error. Pages are huge so almost all requests will fit * inside one. */ final TaskMonitor taskMonitor = TaskMonitorService.getTaskMonitor(); taskMonitor.begin("", 100); //$NON-NLS-1$ taskMonitor.setCurrentWorkDescription( Messages.getString("Workspace.ContactingServertoGetListOfItemsToUpdate")); //$NON-NLS-1$ /* * Specify a limit to number of Get operation results that server may * return from a single call. This is to guard against client running * out of memory, and also to guard against Http runtime timeout on * server when streaming a large result set back to the client. This * "paging" technique relies on the page advancing once we process the * results from the previous call. This is incompatible with force * option. */ final boolean getAll = options.contains(GetOptions.GET_ALL); final int maxResults = getAll ? 0 : VersionControlConstants.MAX_GET_RESULTS; final GetStatus getStatus = new GetStatus(); try { String[] sourceWritableConflicts; final WritableConflictOnSourcePathListener conflictListener = new WritableConflictOnSourcePathListener(); try { client.getEventEngine().addGetListener(conflictListener); GetStatus latestStatus = null; final GetEngine getEngine = new GetEngine(client); int resultCount; /* * Call the server. If we specify a page limit, call repeatedly * as long as we keep getting a full page back. * * Paging like this makes progress monitoring hard, because we * don't know the total amount of work up front. */ do { log.debug("Call server for GetOperations."); //$NON-NLS-1$ final GetOperation[][] results = client.getWebServiceLayer().get(getName(), getOwnerName(), requests, maxResults, options, null, itemPropertyFilters, false); // Web service call always gets 5 taskMonitor.worked(5); // How many results were returned? Is it a full page (see // loop // terminating condition)? resultCount = 0; for (final GetOperation[] result : results) { resultCount += result.length; } log.debug("Process GetOperations"); //$NON-NLS-1$ // Use 95 for the processing. TaskMonitorService.pushTaskMonitor(taskMonitor.newSubTaskMonitor(95)); try { latestStatus = getEngine.processGetOperations(this, ProcessType.GET, RequestType.NONE, results, options, false, true, ChangePendedFlags.UNKNOWN); } catch (final Exception e) { log.error("Error processing GET operations", e); //$NON-NLS-1$ if (e instanceof VersionControlException) { throw (VersionControlException) e; } else { throw new VersionControlException(e); } } finally { TaskMonitorService.popTaskMonitor(true); } log.debug("Latest GetOperations status:"); //$NON-NLS-1$ log.debug(" NumOperations = " + latestStatus.getNumOperations()); //$NON-NLS-1$ log.debug(" NumUpdated = " + latestStatus.getNumUpdated()); //$NON-NLS-1$ log.debug(" NumWarnings = " + latestStatus.getNumWarnings()); //$NON-NLS-1$ log.debug(" NumFailures = " + latestStatus.getNumFailures()); //$NON-NLS-1$ log.debug(" NumConflicts = " + latestStatus.getNumConflicts()); //$NON-NLS-1$ log.debug(" NumResolvedConflicts = " + latestStatus.getNumResolvedConflicts()); //$NON-NLS-1$ getStatus.combine(latestStatus); } while (VersionControlConstants.MAX_GET_RESULTS > 0 && resultCount == VersionControlConstants.MAX_GET_RESULTS && latestStatus.getNumUpdated() >= 1); sourceWritableConflicts = conflictListener.getMovedPaths(); } finally { client.getEventEngine().removeGetListener(conflictListener); } final boolean attemptAutoResolve = (!options.contains(GetOptions.NO_AUTO_RESOLVE)); if (getStatus.getNumConflicts() > 0 || getStatus.haveResolvableWarnings() && (alwaysQueryConflicts || attemptAutoResolve)) { log.debug("Querying conflicts."); //$NON-NLS-1$ taskMonitor.setCurrentWorkDescription(Messages.getString("Workspace.QueryingConflicts")); //$NON-NLS-1$ final AtomicBoolean recursive = new AtomicBoolean(); final String[] conflictScope = calculateConflictScope(requests, sourceWritableConflicts, recursive); Conflict[] unresolvedConflicts = queryConflicts(conflictScope, recursive.get()); if (attemptAutoResolve) { log.debug("Resolving conflicts."); //$NON-NLS-1$ taskMonitor.setCurrentWorkDescription(Messages.getString("Workspace.ResolvingConflicts")); //$NON-NLS-1$ /* Auto resolve the conflicts */ unresolvedConflicts = client.autoResolveValidConflicts(this, unresolvedConflicts, AutoResolveOptions.ALL_SILENT); /* * Update the get status information about conflicts. We * don't change the value of HaveResolvableWarnings because * we won't auto resolve local conflicts. */ getStatus.setNumConflicts(unresolvedConflicts.length); } log.debug("Unresolved conflicts: " + unresolvedConflicts.length); //$NON-NLS-1$ conflicts.set(unresolvedConflicts); } } finally { /* * Event handlers may run a while but not update the work * description, so set a generic message so the user knows things * are wrapping up. */ taskMonitor.setCurrentWorkDescription(Messages.getString("Workspace.FinishingGetOperation")); //$NON-NLS-1$ client.getEventEngine().fireOperationCompleted( new GetOperationCompletedEvent(EventSource.newFromHere(), this, requests, getStatus)); Workstation.getCurrent(getClient().getConnection().getPersistenceStoreProvider()) .notifyForWorkspace(this, Notification.VERSION_CONTROL_GET_COMPLETED); taskMonitor.done(); } return getStatus; }
From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java
/** * Undoes pending changes for matching items in this workspace. Items in * working folders are immediately updated. If <code>updateDisk</code> is * <code>false</code>, then the files on disk will not be updated in * response to the server commands to do so. Passing <code>false</code> for * <code>updateDisk</code> is not common and should only be needed in rare * situations.//from www . j a va 2 s .c o m * <p> * <!-- Event Origination Info --> * <p> * This method is an <b>core event origination point</b>. The * {@link EventSource} object that accompanies each event fired by this * method describes the execution context (current thread, etc.) when and * where this method was invoked. * * @param items * the items to undo (must not be <code>null</code>) * @param getOptions * the {@link GetOptions} to use (must not be <code>null</code>) * @param deleteAdds * determines if adds should be deleted * @param itemPropertyFilters * a list of versioned item properties to return with each get * operation (may be <code>null</code>) * @return the number of items successfully undone. */ public int undo(final ItemSpec[] items, final GetOptions getOptions, final boolean deleteAdds, String[] itemPropertyFilters) { Check.notNull(items, "items"); //$NON-NLS-1$ // Using web service directly so merge filters configured on client itemPropertyFilters = client.mergeWithDefaultItemPropertyFilters(itemPropertyFilters); client.getEventEngine() .fireOperationStarted(new UndoOperationStartedEvent(EventSource.newFromHere(), this, items)); int ret = 0; try { if (items.length == 0) { return 0; } final AtomicReference<Failure[]> failuresHolder = new AtomicReference<Failure[]>(); final AtomicBoolean onlineOperationHolder = new AtomicBoolean(); final AtomicReference<ChangePendedFlags> changePendedFlagsHolder = new AtomicReference<ChangePendedFlags>(); final GetOperation[] operations = client.getWebServiceLayer().undoPendingChanges(getName(), getOwnerName(), items, failuresHolder, null, itemPropertyFilters, onlineOperationHolder, false, changePendedFlagsHolder); if (operations != null && operations.length > 0) { if (isLocal()) { final GetEngine getEngine = new GetEngine(client); getEngine.processGetOperations(this, ProcessType.UNDO, RequestType.NONE, new GetOperation[][] { operations }, getOptions, deleteAdds, onlineOperationHolder.get(), changePendedFlagsHolder.get()); ret = operations.length; } else { final String messageFormat = Messages .getString("Workspace.OperationCompletedForRemoteWorkspaceButGetRequiredFormat"); //$NON-NLS-1$ final String message = MessageFormat.format(messageFormat, getDisplayName()); client.getEventEngine().fireNonFatalError( new NonFatalErrorEvent(EventSource.newFromHere(), this, new Exception(message))); } } if (changePendedFlagsHolder.get().contains(ChangePendedFlags.WORKING_FOLDER_MAPPINGS_UPDATED)) { invalidateMappings(); } client.reportFailures(this, failuresHolder.get()); } finally { client.getEventEngine().fireOperationCompleted( new UndoOperationCompletedEvent(EventSource.newFromHere(), this, items)); Workstation.getCurrent(getClient().getConnection().getPersistenceStoreProvider()) .notifyForWorkspace(this, Notification.VERSION_CONTROL_PENDING_CHANGES_CHANGED); } return ret; }
From source file:com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace.java
/** * Pend these changes for this workspace on the server. * * @param requests/*from www. j a v a 2 s .c o m*/ * the requested changes to pend (must not be <code>null</code>) * @param getOptions * options that affect how files on disk are treated during * processing (must not be <code>null</code>) * @param pendOptions * options that affect how items are pended (must not be * <code>null</code>) * @param itemPropertyFilters * a list of versioned item properties to return with each get * operation (may be <code>null</code>) * @return the number of changes that were successfully processed by the * server. */ private int pendChanges(final ChangeRequest[] requests, final GetOptions getOptions, final PendChangesOptions pendOptions, String[] itemPropertyFilters) { Check.notNull(requests, "requests"); //$NON-NLS-1$ Check.notNull(getOptions, "getOptions"); //$NON-NLS-1$ Check.notNull(pendOptions, "pendOptions"); //$NON-NLS-1$ // Using web service directly so merge filters configured on client itemPropertyFilters = client.mergeWithDefaultItemPropertyFilters(itemPropertyFilters); client.getEventEngine() .fireOperationStarted(new PendOperationStartedEvent(EventSource.newFromHere(), this, requests)); if (getClient().getServiceLevel().getValue() < WebServiceLevel.TFS_2012.getValue()) { if (hasPropertyChange(requests)) { client.getEventEngine().fireNonFatalError(new NonFatalErrorEvent(EventSource.newFromHere(), this, new VersionControlException(Messages.getString("Workspace.PropertyNotSupportedText")))); //$NON-NLS-1$ } } int ret = 0; try { SupportedFeatures features = SupportedFeatures.ALL; /* * If the get operation "Force Checkout Local Version" is set, we do * not advertise to the server that we support get latest on * checkout. Presumably, there may be a state where the server * wishes to update us to the local version and this explicitly * stops that. */ if (pendOptions.contains(PendChangesOptions.FORCE_CHECK_OUT_LOCAL_VERSION)) { features = features.remove(SupportedFeatures.GET_LATEST_ON_CHECKOUT); } final AtomicReference<Failure[]> failures = new AtomicReference<Failure[]>(); final AtomicBoolean onlineOperation = new AtomicBoolean(); final AtomicReference<ChangePendedFlags> changePendedFlags = new AtomicReference<ChangePendedFlags>(); final GetOperation[] operations = client.getWebServiceLayer().pendChanges(getName(), getOwnerName(), requests, pendOptions, features, failures, itemPropertyFilters, null, true, onlineOperation, changePendedFlags); // Get any required files. if (operations.length > 0) { /* * The TFS server (as of TFS 2013 QU1) provides in the response * only properties saved in the server's database, i.e. already * checked in. Thus, to process the executable bit and symlinks * using properties mechanism correctly in the client file * system, we have to merge properties received in the response * with those submitted in the change request. * * Note that for the local workspaces it's already done in the * LocalDataAccessLayer class. */ if (WorkspaceLocation.SERVER == this.getLocation() && getClient().getServiceLevel().getValue() >= WebServiceLevel.TFS_2012.getValue()) { for (final ChangeRequest request : requests) { final PropertyValue[] requestProperties = request.getProperties(); if (requestProperties != null) { final GetOperation operation = findMatchingOperation(operations, request); if (operation != null) { final PropertyValue[] operationProperties = operation.getPropertyValues(); if (operationProperties != null) { operation.setPropertyValues(PropertyUtils .mergePendingValues(operationProperties, requestProperties)); } } } } } final GetEngine getEngine = new GetEngine(client); getEngine.processGetOperations(this, ProcessType.PEND, requests[0].getRequestType(), new GetOperation[][] { operations }, getOptions, false, onlineOperation.get(), changePendedFlags.get()); // Return the number of operations that were successful. ret = operations.length; } if (changePendedFlags.get().contains(ChangePendedFlags.WORKING_FOLDER_MAPPINGS_UPDATED)) { invalidateMappings(); } /* * If it was requested by the caller, strip out any Failure objects * from the failure set which are of type ItemNotFoundException. */ if (failures.get() != null && failures.get().length > 0 && pendOptions.contains(PendChangesOptions.SUPPRESS_ITEM_NOT_FOUND_FAILURES)) { final List<Failure> otherFailures = new ArrayList<Failure>(); for (final Failure f : failures.get()) { if (f.getCode() == null || !f.getCode().equals(FailureCodes.ITEM_EXISTS_EXCEPTION)) { otherFailures.add(f); } } failures.set(otherFailures.toArray(new Failure[otherFailures.size()])); } client.reportFailures(this, failures.get()); } finally { client.getEventEngine().fireOperationCompleted( new PendOperationCompletedEvent(EventSource.newFromHere(), this, requests)); Workstation.getCurrent(getClient().getConnection().getPersistenceStoreProvider()) .notifyForWorkspace(this, Notification.VERSION_CONTROL_PENDING_CHANGES_CHANGED); } return ret; }
From source file:com.tascape.qa.th.android.driver.App.java
/** * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction. * * @param timeoutMinutes timeout in minutes to fail the manual steps * * @throws Exception if case of error/* ww w . j a v a2 s .c om*/ */ public void interactManually(int timeoutMinutes) throws Exception { LOG.info("Start manual UI interaction"); long end = System.currentTimeMillis() + timeoutMinutes * 60000L; AtomicBoolean visible = new AtomicBoolean(true); AtomicBoolean pass = new AtomicBoolean(false); String tName = Thread.currentThread().getName() + "m"; SwingUtilities.invokeLater(() -> { JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail()); jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); JPanel jpContent = new JPanel(new BorderLayout()); jd.setContentPane(jpContent); jpContent.setPreferredSize(new Dimension(1088, 828)); jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel jpInfo = new JPanel(); jpContent.add(jpInfo, BorderLayout.PAGE_START); jpInfo.setLayout(new BorderLayout()); { JButton jb = new JButton("PASS"); jb.setForeground(Color.green.darker()); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_START); jb.addActionListener(event -> { pass.set(true); jd.dispose(); visible.set(false); }); } { JButton jb = new JButton("FAIL"); jb.setForeground(Color.red); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_END); jb.addActionListener(event -> { pass.set(false); jd.dispose(); visible.set(false); }); } JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); new SwingWorker<Long, Long>() { @Override protected Long doInBackground() throws Exception { while (System.currentTimeMillis() < end) { Thread.sleep(1000); long left = (end - System.currentTimeMillis()) / 1000; this.publish(left); } return 0L; } @Override protected void process(List<Long> chunks) { Long l = chunks.get(chunks.size() - 1); jlTimeout.setText(l + " seconds left"); if (l < 850) { jlTimeout.setForeground(Color.red); } } }.execute(); JPanel jpResponse = new JPanel(new BorderLayout()); JPanel jpProgress = new JPanel(new BorderLayout()); jpResponse.add(jpProgress, BorderLayout.PAGE_START); JTextArea jtaJson = new JTextArea(); jtaJson.setEditable(false); jtaJson.setTabSize(4); Font font = jtaJson.getFont(); jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize())); JTree jtView = new JTree(); JTabbedPane jtp = new JTabbedPane(); jtp.add("tree", new JScrollPane(jtView)); jtp.add("json", new JScrollPane(jtaJson)); jpResponse.add(jtp, BorderLayout.CENTER); JPanel jpScreen = new JPanel(); jpScreen.setMinimumSize(new Dimension(200, 200)); jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS)); JScrollPane jsp1 = new JScrollPane(jpScreen); jpResponse.add(jsp1, BorderLayout.LINE_START); JPanel jpJs = new JPanel(new BorderLayout()); JTextArea jtaJs = new JTextArea(); jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER); JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs); jSplitPane.setResizeWeight(0.88); jpContent.add(jSplitPane, BorderLayout.CENTER); JPanel jpLog = new JPanel(); jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS)); JCheckBox jcbTap = new JCheckBox("Enable Click", null, false); jpLog.add(jcbTap); jpLog.add(Box.createHorizontalStrut(8)); JButton jbLogUi = new JButton("Log Screen"); jpResponse.add(jpLog, BorderLayout.PAGE_END); { jpLog.add(jbLogUi); jbLogUi.addActionListener((ActionEvent event) -> { jtaJson.setText("waiting for screenshot..."); Thread t = new Thread(tName) { @Override public void run() { LOG.debug("\n\n"); try { WindowHierarchy wh = device.loadWindowHierarchy(); jtView.setModel(getModel(wh)); jtaJson.setText(""); jtaJson.append(wh.root.toJson().toString(2)); jtaJson.append("\n"); File png = device.takeDeviceScreenshot(); BufferedImage image = ImageIO.read(png); int w = device.getDisplayWidth(); int h = device.getDisplayHeight(); BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, w, h, null); g2.dispose(); JLabel jLabel = new JLabel(new ImageIcon(resizedImg)); jpScreen.removeAll(); jsp1.setPreferredSize(new Dimension(w + 30, h)); jpScreen.add(jLabel); jLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY()); if (jcbTap.isSelected()) { device.click(e.getPoint().x, e.getPoint().y); device.waitForIdle(); jbLogUi.doClick(); } } }); } catch (Exception ex) { LOG.error("Cannot log screen", ex); jtaJson.append("Cannot log screen"); } jtaJson.append("\n\n\n"); LOG.debug("\n\n"); jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1); jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1); } }; t.start(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbLogMsg = new JButton("Log Message"); jpLog.add(jbLogMsg); JTextField jtMsg = new JTextField(10); jpLog.add(jtMsg); jtMsg.addFocusListener(new FocusListener() { @Override public void focusLost(final FocusEvent pE) { } @Override public void focusGained(final FocusEvent pE) { jtMsg.selectAll(); } }); jtMsg.addKeyListener(new KeyAdapter() { @Override public void keyPressed(java.awt.event.KeyEvent e) { if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { jbLogMsg.doClick(); } } }); jbLogMsg.addActionListener(event -> { Thread t = new Thread(tName) { @Override public void run() { String msg = jtMsg.getText(); if (StringUtils.isNotBlank(msg)) { LOG.info("{}", msg); jtMsg.selectAll(); } } }; t.start(); try { t.join(); } catch (InterruptedException ex) { LOG.error("Cannot take screenshot", ex); } jtMsg.requestFocus(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbClear = new JButton("Clear"); jpLog.add(jbClear); jbClear.addActionListener(event -> { jtaJson.setText(""); }); } JPanel jpAction = new JPanel(); jpContent.add(jpAction, BorderLayout.PAGE_END); jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS)); jpJs.add(jpAction, BorderLayout.PAGE_END); jd.pack(); jd.setVisible(true); jd.setLocationRelativeTo(null); jbLogUi.doClick(); }); while (visible.get()) { if (System.currentTimeMillis() > end) { LOG.error("Manual UI interaction timeout"); break; } Thread.sleep(500); } if (pass.get()) { LOG.info("Manual UI Interaction returns PASS"); } else { Assert.fail("Manual UI Interaction returns FAIL"); } }
From source file:org.apache.hadoop.hive.metastore.ObjectStore.java
protected boolean getPartitionsByExprInternal(String dbName, String tblName, final byte[] expr, final String defaultPartitionName, final short maxParts, List<Partition> result, boolean allowSql, boolean allowJdo) throws TException { assert result != null; final ExpressionTree exprTree = PartFilterExprUtil.makeExpressionTree(expressionProxy, expr); final AtomicBoolean hasUnknownPartitions = new AtomicBoolean(false); result.addAll(new GetListHelper<Partition>(dbName, tblName, allowSql, allowJdo) { @Override// w w w. j a v a 2s . c om protected List<Partition> getSqlResult(GetHelper<List<Partition>> ctx) throws MetaException { // If we have some sort of expression tree, try SQL filter pushdown. List<Partition> result = null; if (exprTree != null) { SqlFilterForPushdown filter = new SqlFilterForPushdown(); if (directSql.generateSqlFilterForPushdown(ctx.getTable(), exprTree, filter)) { return directSql.getPartitionsViaSqlFilter(filter, null); } } // We couldn't do SQL filter pushdown. Get names via normal means. List<String> partNames = new LinkedList<String>(); hasUnknownPartitions.set(getPartitionNamesPrunedByExprNoTxn(ctx.getTable(), expr, defaultPartitionName, maxParts, partNames)); return directSql.getPartitionsViaSqlFilter(dbName, tblName, partNames); } @Override protected List<Partition> getJdoResult(GetHelper<List<Partition>> ctx) throws MetaException, NoSuchObjectException { // If we have some sort of expression tree, try JDOQL filter pushdown. List<Partition> result = null; if (exprTree != null) { result = getPartitionsViaOrmFilter(ctx.getTable(), exprTree, maxParts, false); } if (result == null) { // We couldn't do JDOQL filter pushdown. Get names via normal means. List<String> partNames = new ArrayList<String>(); hasUnknownPartitions.set(getPartitionNamesPrunedByExprNoTxn(ctx.getTable(), expr, defaultPartitionName, maxParts, partNames)); result = getPartitionsViaOrmFilter(dbName, tblName, partNames); } return result; } }.run(true)); return hasUnknownPartitions.get(); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.LocalDataAccessLayer.java
/** * * * * @param workspace//www . ja va 2 s . co m * @param lv * @param pc * @param changeRequests * @param silent * @param failures * @param onlineOperationRequired * @param invalidateWorkspaceAfterServerCall * @return */ public static GetOperation[] pendRename(final Workspace workspace, final LocalWorkspaceProperties wp, final WorkspaceVersionTable lv, final LocalPendingChangesTable pc, final ChangeRequest[] changeRequests, final boolean silent, final AtomicReference<Failure[]> failures, final AtomicBoolean onlineOperationRequired, final String[] itemPropertyFilters) { Check.notNull(workspace, "workspace"); //$NON-NLS-1$ Check.notNull(changeRequests, "changeRequests"); //$NON-NLS-1$ workspace.getWorkspaceWatcher().scan(wp, lv, pc); final List<Failure> failureList = new ArrayList<Failure>(); final List<GetOperation> getOps = new ArrayList<GetOperation>(); failures.set(null); final WorkingFolder[] workspaceMappings = wp.getWorkingFolders(); for (int i = 0; i < changeRequests.length; i++) { if (null == changeRequests[i]) { continue; } final ParsedItemSpec parsedItemSpec = ParsedItemSpec.fromItemSpec(changeRequests[i].getItemSpec(), wp, lv, pc, ParsedItemSpecOptions.NONE, failureList); if (null == parsedItemSpec) { continue; } final String sourceRoot = parsedItemSpec.getTargetItem(); String targetRoot = changeRequests[i].getTargetItem(); final String sourceServerRoot = tryGetServerItem(sourceRoot, wp, lv, pc); String targetServerRoot = null; boolean isCloaked = false; if (ServerPath.isServerPath(targetRoot)) { targetServerRoot = targetRoot; } else { final PathTranslation translation = WorkingFolder.translateLocalItemToServerItem(targetRoot, workspaceMappings); if (translation != null) { targetServerRoot = translation.getTranslatedPath(); isCloaked = translation.isCloaked(); } } if (isCloaked) { failureList.add(createItemCloakedFailure(targetRoot)); continue; } else if (targetServerRoot == null) { // Error is consistent with server workspaces when target path // is non-server and unmapped, but not cloaked failureList.add(createItemNotMappedFailure(targetRoot)); continue; } final String targetLocalRoot = ServerPath.isServerPath(targetRoot) ? WorkingFolder.getLocalItemForServerItem(targetRoot, workspaceMappings) : targetRoot; final int maxServerPathLength = workspace.getClient().getMaxServerPathLength(); // For consistency in error messages with server workspaces, check // the provided itemspec first, then the translated path. final AtomicReference<String> outTargetRoot = new AtomicReference<String>(targetRoot); ItemPath.checkItem(outTargetRoot, "changeRequest.ItemSpec.Item", //$NON-NLS-1$ false, false, false, true, maxServerPathLength); targetRoot = outTargetRoot.get(); if (ServerPath.isServerPath(targetRoot)) { if (targetLocalRoot != null && targetLocalRoot.length() > 0) { LocalPath.checkLocalItem(targetLocalRoot, "TargetItem", false, false, false, true); //$NON-NLS-1$ } } else { final AtomicReference<String> outTargetServerRoot = new AtomicReference<String>(targetServerRoot); ServerPath.checkServerItem(outTargetServerRoot, "TargetItem", //$NON-NLS-1$ false, false, false, true, maxServerPathLength); targetServerRoot = outTargetServerRoot.get(); } // server path minus all renames that exists on its parents final String targetUnrenamedServerRoot = pc.getCommittedServerItemForTargetServerItem(targetServerRoot); if (ItemPath.isWildcard(targetRoot)) { failureList.add( new Failure(Messages.getString("LocalDataAccessLayer.WildcardNotAllowedForRenameTarget"), //$NON-NLS-1$ FailureCodes.WILDCARD_NOT_ALLOWED_EXCEPTION, SeverityType.ERROR, targetRoot)); continue; } final ItemType targetItemType = changeRequests[i].getTargetItemType(); final boolean isMove = isMove(targetUnrenamedServerRoot, targetItemType, lv); final boolean targetIsFolder = targetItemType == ItemType.ANY ? isDirectory(lv, pc, targetServerRoot) : targetItemType == ItemType.FOLDER; // if we move dir\*.cs, root (dir will not be included), if we move // dir, root is included final boolean rootIncludedInRename = parsedItemSpec.getPattern() == null; if (parsedItemSpec.getPattern() != null && ItemPath.isWildcard(parsedItemSpec.getPattern()) && !isMove) { failureList.add( new Failure(Messages.getString("LocalDataAccessLayer.WildcardNotAllowedForRenameSource"), //$NON-NLS-1$ FailureCodes.WILDCARD_NOT_ALLOWED_EXCEPTION, SeverityType.ERROR, sourceRoot)); continue; } if (ServerPath.isRootFolder(targetServerRoot)) { failureList .add(new Failure(Messages.getString("LocalDataAccessLayer.CanNotChangeRootFolderException"), //$NON-NLS-1$ FailureCodes.CANNOT_CHANGE_ROOT_FOLDER_EXCEPTION, SeverityType.ERROR, parsedItemSpec.getTargetItem())); continue; } if (!targetIsFolder) { // we validate if target is a team project only if it doesn't // exist in local workspace - if it does, we will move files // under it final Failure teamProjectValidationFailure = TeamProject.validateChange(targetServerRoot, ItemType.FOLDER); if (teamProjectValidationFailure != null) { failureList.add(teamProjectValidationFailure); continue; } } for (final WorkspaceLocalItem lvEntry : parsedItemSpec.expandFrom(lv, pc, failureList)) { final String sourceCommittedServerItem = lvEntry.getServerItem(); String sourceCurrentServerItem = sourceCommittedServerItem; if (lvEntry.isCommitted()) { sourceCurrentServerItem = pc .getTargetServerItemForCommittedServerItem(sourceCommittedServerItem); } final String targetServerItem = calculateTargetServerItem(sourceServerRoot, sourceCurrentServerItem, targetServerRoot, targetIsFolder, rootIncludedInRename); // targetLocalItem may be null if we move file into not mapped // location final String targetLocalItem = WorkingFolder.getLocalItemForServerItem(targetServerItem, wp.getWorkingFolders()); final boolean caseOnlyRename = ServerPath.equals(sourceCurrentServerItem, targetServerItem) && !ServerPath.equals(sourceCurrentServerItem, targetServerItem, false); if (ServerPath.isRootFolder(sourceCurrentServerItem)) { failureList.add( new Failure(Messages.getString("LocalDataAccessLayer.CanNotChangeRootFolderException"), //$NON-NLS-1$ FailureCodes.CANNOT_CHANGE_ROOT_FOLDER_EXCEPTION, SeverityType.ERROR, sourceCurrentServerItem)); continue; } final Failure teamProjectValidationFailure = TeamProject.validateChange(sourceCommittedServerItem, lvEntry.isDirectory() ? ItemType.FOLDER : ItemType.FILE); if (teamProjectValidationFailure != null) { failureList.add(teamProjectValidationFailure); continue; } if (targetServerItem.length() > VersionControlConstants.MAX_SERVER_PATH_SIZE) { failureList.add(createPathTooLongFailure(targetServerItem)); continue; } // validate mappings boolean workspaceMappingFailure = false; for (final WorkingFolder mapping : workspaceMappings) { if (ServerPath.equals(mapping.getServerItem(), sourceCurrentServerItem)) { final String format = Messages .getString("LocalDataAccessLayer.RenameWorkingFolderExceptionFormat"); //$NON-NLS-1$ failureList.add(new Failure(MessageFormat.format(format, sourceCurrentServerItem), FailureCodes.RENAME_WORKING_FOLDER_EXCEPTION, SeverityType.ERROR, sourceCurrentServerItem)); workspaceMappingFailure = true; break; } if (ServerPath.isChild(sourceCurrentServerItem, mapping.getServerItem())) { return sendToServer(failures, onlineOperationRequired); } } if (workspaceMappingFailure) { continue; } if (!caseOnlyRename && pc.getByTargetServerItem(targetServerItem) != null) { final String format = Messages .getString("LocalDataAccessLayer.ChangeAlreadyPendingExceptionFormat"); //$NON-NLS-1$ failureList.add(new Failure(MessageFormat.format(format, targetServerItem), FailureCodes.CHANGE_ALREADY_PENDING_EXCEPTION, SeverityType.ERROR, sourceCurrentServerItem)); continue; } if (pc.getRecursiveChangeTypeForTargetServerItem(targetServerItem).contains(ChangeType.DELETE)) { failureList.add(createPendingParentDeleteFailure(targetServerItem)); continue; } LocalPendingChange mainPendingChange = pc.getByLocalVersion(lvEntry); if (null != mainPendingChange) { if (mainPendingChange.isLock()) { // Cannot offline rename a pending lock. return sendToServer(failures, onlineOperationRequired); } if (mainPendingChange.isDelete()) { final String format = Messages .getString("LocalDataAccessLayer.IncompatibleChangeExceptionFormat"); //$NON-NLS-1$ failureList.add(new Failure(MessageFormat.format(format, targetServerItem), FailureCodes.INCOMPATIBLE_CHANGE_EXCEPTION, SeverityType.ERROR, changeRequests[i].getItemSpec().getItem())); continue; } // target server item minus all parent renames // if we have both parent renamed (folder->folder2) and item // renamed(a->b), renaming folder2\a to folder2\b // should undo rename on bar final String targetParent = ServerPath.getParent(targetServerItem); final String committedParent = pc.getCommittedServerItemForTargetServerItem(targetParent); String targetUnrenamedParent = null; if (committedParent != null && committedParent.length() > 0) { targetUnrenamedParent = committedParent + targetServerItem.substring(targetParent.length()); } if ((targetUnrenamedParent != null && ServerPath.equals(targetUnrenamedParent, sourceCommittedServerItem, false)) || ServerPath.equals(sourceCommittedServerItem, targetServerItem, false)) { // Selective undo final AtomicReference<Failure[]> undoFailures = new AtomicReference<Failure[]>(); final List<LocalPendingChange> changes = new ArrayList<LocalPendingChange>(); changes.add(mainPendingChange); final GetOperation[] undoOps = undoPendingChanges(workspace, wp, lv, pc, changes, ChangeType.RENAME, undoFailures, onlineOperationRequired); if (onlineOperationRequired.get()) { return sendToServer(failures, onlineOperationRequired); } failureList.addAll(Arrays.asList(undoFailures.get())); getOps.addAll(Arrays.asList(undoOps)); continue; } } WorkspaceLocalItem conflictingItem = (targetLocalItem == null || targetLocalItem.length() == 0) ? null : lv.getByLocalItem(targetLocalItem); if (conflictingItem != null && !caseOnlyRename) { final String format = Messages.getString("LocalDataAccessLayer.ItemExistsExceptionFormat"); //$NON-NLS-1$ failureList.add(new Failure(MessageFormat.format(format, targetServerItem), FailureCodes.ITEM_EXISTS_EXCEPTION, SeverityType.ERROR, conflictingItem.getLocalItem())); continue; } final List<GetOperation> affectedItems = new ArrayList<GetOperation>(); final Map<String, LocalPendingChange> affectedCommittedPendingChanges = new HashMap<String, LocalPendingChange>(); final Map<String, LocalPendingChange> affectedNotCommittedPendingChanges = new HashMap<String, LocalPendingChange>(); // we should not updated pending changes in the main loop, since // we use them to calculate target path for each item // we need to do that afterwards final List<KeyValuePair<String, LocalPendingChange>> updatedPendingChanges = new ArrayList<KeyValuePair<String, LocalPendingChange>>(); // Create or update main pending change (on the item itself) if (mainPendingChange == null) { mainPendingChange = new LocalPendingChange(lvEntry, targetServerItem, ChangeType.RENAME); affectedCommittedPendingChanges.put(mainPendingChange.getCommittedServerItem(), mainPendingChange); } else { if (mainPendingChange.isAdd() || mainPendingChange.isBranch()) { affectedNotCommittedPendingChanges.put(mainPendingChange.getTargetServerItem(), mainPendingChange); } else { mainPendingChange .setChangeType(mainPendingChange.getChangeType().combine(ChangeType.RENAME)); affectedCommittedPendingChanges.put(mainPendingChange.getCommittedServerItem(), mainPendingChange); } } boolean abort = false; if (lvEntry.isDirectory()) { // build lookup of pending changes, so we can update them // and populate GetOps with the right change for (final LocalPendingChange lpEntry : pc.queryByTargetServerItem(sourceCurrentServerItem, RecursionType.FULL, "*")) //$NON-NLS-1$ { if (lpEntry.isAdd() || lpEntry.isBranch()) { affectedNotCommittedPendingChanges.put(lpEntry.getTargetServerItem(), lpEntry); } else { affectedCommittedPendingChanges.put(lpEntry.getCommittedServerItem(), lpEntry); } } } for (final WorkspaceLocalItem childEntry : ParsedItemSpec.queryLocalVersionsByTargetServerItem(lv, pc, sourceCurrentServerItem, RecursionType.FULL, null, ParsedItemSpecOptions.INCLUDE_DELETED)) { String childTargetServerItem; GetOperation childGetOp; LocalPendingChange associatedPendingChange = null; if (childEntry.isCommitted()) { associatedPendingChange = affectedCommittedPendingChanges.get(childEntry.getServerItem()); } else if (!childEntry.isCommitted()) { associatedPendingChange = affectedNotCommittedPendingChanges .get(childEntry.getServerItem()); } if (associatedPendingChange != null) { if (associatedPendingChange.isLock()) { // Cannot offline rename a pending lock. return sendToServer(failures, onlineOperationRequired); } if (!ServerPath.equals(targetServerItem, associatedPendingChange.getTargetServerItem(), false)) { // do not update if this is new pending change we // just created (mainPendingChange) childTargetServerItem = calculateTargetServerItem(sourceServerRoot, associatedPendingChange.getTargetServerItem(), targetServerRoot, targetIsFolder, rootIncludedInRename); } else { childTargetServerItem = associatedPendingChange.getTargetServerItem(); } updatedPendingChanges.add(new KeyValuePair<String, LocalPendingChange>( childTargetServerItem, associatedPendingChange)); childGetOp = childEntry.toGetOperation(associatedPendingChange, itemPropertyFilters); // SourceServerItem should be identical with // TargetServerItem for not committed changes (add and // branch) childGetOp.setSourceServerItem(childEntry.isCommitted() ? childGetOp.getSourceServerItem() : childTargetServerItem); childGetOp.setTargetServerItem(childTargetServerItem); childGetOp.setChangeType(childEntry.isCommitted() ? associatedPendingChange.getChangeType().combine(ChangeType.RENAME) : childGetOp.getChangeType()); } else { final String currentServerItem = childEntry.isCommitted() ? pc.getTargetServerItemForCommittedServerItem(childEntry.getServerItem()) : childEntry.getServerItem(); childTargetServerItem = calculateTargetServerItem(sourceServerRoot, currentServerItem, targetServerRoot, targetIsFolder, rootIncludedInRename); childGetOp = childEntry.toGetOperation(itemPropertyFilters); childGetOp.setTargetServerItem(childTargetServerItem); childGetOp.setChangeType(ChangeType.RENAME); } // TODO we include deletes only to add entry to // updatedPendingChanges and update them later. We should // check how costly it is when we rename folder that // contains big deletes subfolder if (childEntry.isDeleted()) { continue; } if (childTargetServerItem.length() > VersionControlConstants.MAX_SERVER_PATH_SIZE) { abort = true; failureList.add(createPathTooLongFailure(childTargetServerItem)); break; } final String childTargetLocalItem = WorkingFolder .getLocalItemForServerItem(childTargetServerItem, wp.getWorkingFolders()); conflictingItem = (childTargetLocalItem == null || childTargetLocalItem.length() == 0) ? null : lv.getByLocalItem(childTargetLocalItem); if (conflictingItem != null && !ServerPath.equals(conflictingItem.getServerItem(), childEntry.getServerItem())) { abort = true; final String format = Messages.getString("LocalDataAccessLayer.ItemExistsExceptionFormat"); //$NON-NLS-1$ failureList.add(new Failure(MessageFormat.format(format, targetServerItem), FailureCodes.ITEM_EXISTS_EXCEPTION, SeverityType.ERROR, conflictingItem.getLocalItem())); break; } if ((childTargetLocalItem == null || childTargetLocalItem.length() == 0) && childGetOp.getChangeType().contains(ChangeType.EDIT)) { abort = true; final String format = Messages .getString("LocalDataAccessLayer.TargetCloakedExceptionFormat"); //$NON-NLS-1$ failureList.add(new Failure(MessageFormat.format(format, sourceCurrentServerItem), FailureCodes.TARGET_CLOAKED_EXCEPTION, SeverityType.ERROR, sourceCurrentServerItem)); break; } if (silent) { // we generated all possible warnings, now bail since // it's a silent operation continue; } childGetOp.setTargetLocalItem(childTargetLocalItem); affectedItems.add(childGetOp); } if (abort) { continue; } // update pending changes for (final KeyValuePair<String, LocalPendingChange> updatedPendingChangeInfo : updatedPendingChanges) { final String updateServerPath = updatedPendingChangeInfo.getKey(); final LocalPendingChange updatedPendingChange = updatedPendingChangeInfo.getValue(); pc.remove(updatedPendingChange); updatedPendingChange.setTargetServerItem(updateServerPath); pc.pendChange(updatedPendingChange); } if (!silent) { // update local versions of not committed items (adds and // branches) for (final String originalServerItem : affectedNotCommittedPendingChanges.keySet()) { final LocalPendingChange pendingChange = affectedNotCommittedPendingChanges .get(originalServerItem); final WorkspaceLocalItem addEntry = lv.getByServerItem(originalServerItem, false); if (addEntry != null) { lv.removeByServerItem(originalServerItem, false, true); addEntry.setServerItem(pendingChange.getTargetServerItem()); // TODO what about renaming pending branch into not // mapped location? // TODO we already calculated this local path once, // we should store it in // affectedNotCommittedPendingChanges and reuse it addEntry.setLocalItem(WorkingFolder.getLocalItemForServerItem( pendingChange.getTargetServerItem(), wp.getWorkingFolders())); lv.add(addEntry); } } } getOps.addAll(affectedItems); } } for (final Failure failure : failureList) { failure.setRequestType(RequestType.RENAME); } onlineOperationRequired.set(false); failures.set(failureList.toArray(new Failure[failureList.size()])); return getOps.toArray(new GetOperation[getOps.size()]); }
From source file:Distortions.java
/** * Calculate each sensor correction increment for geometry and photometry contributed by all images selected in a series * @param selectedImages process only selected images * @param showIndividual show per-image intermediate results * @param threadsMax maximal number of concurrent threads * @param updateStatus update IJ status/progress * @param debugLevel debug level/*from ww w. ja v a2 s .c o m*/ * @return [sensor]{dpX,dpY,alpha,R,G,B}[pixelIndex] . dpX, dpY - correction to previous, RGB - total FF, not increment! */ public double[][][] allImagesCorrectionMapped(final boolean[] selectedImages, final boolean showIndividual, final int showIndividualNumber, final int threadsMax, final boolean updateStatus, final int debugLevel) { int numChannels = fittingStrategy.distortionCalibrationData.getNumChannels(); // number of used channels final double[][][] gridPCorr = new double[numChannels][][]; for (int chnNum = 0; chnNum < gridPCorr.length; chnNum++) gridPCorr[chnNum] = null; int numSelected = 0; for (int imgNum = 0; imgNum < selectedImages.length; imgNum++) if (selectedImages[imgNum]) numSelected++; final int finalSelected = numSelected; if (updateStatus) IJ.showStatus("Calculating sensor corrections..."); final AtomicInteger imageNumberAtomic = new AtomicInteger(0); final AtomicInteger imageFinishedAtomic = new AtomicInteger(0); final Thread[] threads = newThreadArray(threadsMax); final AtomicInteger stopRequested = this.stopRequested; final AtomicBoolean interruptedAtomic = new AtomicBoolean(); final int alphaIndex = 2; for (int ithread = 0; ithread < threads.length; ithread++) { threads[ithread] = new Thread() { public void run() { for (int imgNum = imageNumberAtomic.getAndIncrement(); (imgNum < selectedImages.length) && !interruptedAtomic.get(); imgNum = imageNumberAtomic.getAndIncrement()) { if (selectedImages[imgNum]) { int chnNum = fittingStrategy.distortionCalibrationData.gIP[imgNum].channel; // number of sub-camera double[][] singleCorr = singleImageCorrectionMapped(imgNum, // image number showIndividual && ((showIndividualNumber < 0) || (showIndividualNumber == chnNum)), debugLevel); combineImageCorrection(chnNum, gridPCorr, singleCorr); final int numFinished = imageFinishedAtomic.getAndIncrement(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (updateStatus) IJ.showProgress(numFinished, finalSelected); } }); if (stopRequested.get() == 1) { // ASAP interruptedAtomic.set(true); } } //if (selectedImages[numImage]){ } // for (int numImage=imageNumberAtomic.getAndIncrement(); ... } // public void run() { }; } startAndJoin(threads); // divide by weight; for (int nChn = 0; nChn < gridPCorr.length; nChn++) if (gridPCorr[nChn] != null) { for (int i = 0; i < gridPCorr[nChn].length; i++) { if (i != alphaIndex) { for (int j = 0; j < gridPCorr[nChn][i].length; j++) { if (gridPCorr[nChn][alphaIndex][j] > 0) gridPCorr[nChn][i][j] /= gridPCorr[nChn][alphaIndex][j]; } } } } if (updateStatus) IJ.showProgress(0); if (interruptedAtomic.get()) { System.out.println("allImagesCorrection() aborted by user request"); return null; } return gridPCorr; }
From source file:Distortions.java
public LMAArrays calculateJacobianArrays(final boolean[] selectedImages, // selected images to process final double[] Y, // should be initialized final double[] fX, // should be initialized to correct length, data is not needed final double[] vector, // parameters vector final int[] imageStartIndex, // index of the first point of each image (including extra element in the end so n+1 is always valid) final double[][] patternXYZ, // this.targetXYZ final double[] weightFunction, // may be null - make it twice smaller? - same for X and Y? final LensDistortionParameters lensDistortionParametersProto, // final double lambda, int threadsMax, boolean updateStatus) { // calculate JtJ // double [] diff=calcYminusFx(fX); // int numPars=this.jacobian.length; // number of parameters to be adjusted final int numPars = vector.length; // number of parameters to be adjusted // int length=diff.length; // should be the same as this.jacobian[0].length // final int length=fX.length; // should be the same as this.jacobian[0].length final double[][] JtByJmod = new double[numPars][numPars]; //Transposed Jacobian multiplied by Jacobian final double[] JtByDiff = new double[numPars]; for (int i = 0; i < numPars; i++) { JtByDiff[i] = 0.0;//ww w. j a v a2s .co m for (int j = 0; j < numPars; j++) JtByJmod[i][j] = 0.0; } final int debugLevel = this.debugLevel; final Thread[] threads = newThreadArray(threadsMax); final AtomicInteger imageNumberAtomic = new AtomicInteger(0); final AtomicInteger imageFinishedAtomic = new AtomicInteger(0); final double[] progressValues = new double[selectedImages.length]; int numSelectedImages = 0; for (int i = 0; i < selectedImages.length; i++) if (selectedImages[i]) numSelectedImages++; int selectedIndex = 0; for (int i = 0; i < selectedImages.length; i++) { progressValues[i] = (selectedIndex + 1.0) / numSelectedImages; if (selectedImages[i]) selectedIndex++; if (selectedIndex >= numSelectedImages) selectedIndex--; } final AtomicInteger stopRequested = this.stopRequested; final AtomicBoolean interruptedAtomic = new AtomicBoolean(); for (int ithread = 0; ithread < threads.length; ithread++) { threads[ithread] = new Thread() { public void run() { LensDistortionParameters lensDistortionParameters = lensDistortionParametersProto.clone(); // see - if that is needed - maybe new is OK // LensDistortionParameters lensDistortionParameters= new LensDistortionParameters(); for (int numImage = imageNumberAtomic.getAndIncrement(); (numImage < selectedImages.length) && !interruptedAtomic.get(); numImage = imageNumberAtomic.getAndIncrement()) { double[][] partialJacobian = calculatePartialFxAndJacobian(numImage, // number of grid image vector, // parameters vector patternXYZ, // this.targetXYZ fX, // non-overlapping segments will be filled imageStartIndex, // start index in patternXYZ array (length - difference to the next, includes extra last element) lensDistortionParameters, // initialize one per each tread? Or for each call? true); // when false, modifies only this.lensDistortionParameters.* int length = 2 * (imageStartIndex[numImage + 1] - imageStartIndex[numImage]); int start = 2 * imageStartIndex[numImage]; double[][] partialJtByJmod = new double[numPars][numPars]; // out of heap space double[] partialJtByDiff = new double[numPars]; for (int i = 0; i < numPars; i++) if (partialJacobian[i] != null) { for (int j = i; j < numPars; j++) if (partialJacobian[j] != null) { partialJtByJmod[i][j] = 0.0; if (weightFunction != null) { for (int k = 0; k < length; k++) partialJtByJmod[i][j] += partialJacobian[i][k] * partialJacobian[j][k] * weightFunction[start + k]; } else { for (int k = 0; k < length; k++) partialJtByJmod[i][j] += partialJacobian[i][k] * partialJacobian[j][k]; } } } double[] partialDiff = new double[length]; for (int k = 0; k < length; k++) partialDiff[k] = Y[start + k] - fX[start + k]; for (int i = 0; i < numPars; i++) if (partialJacobian[i] != null) { partialJtByDiff[i] = 0.0; if (weightFunction != null) for (int k = 0; k < length; k++) partialJtByDiff[i] += partialJacobian[i][k] * partialDiff[k] * weightFunction[start + k]; else for (int k = 0; k < length; k++) partialJtByDiff[i] += partialJacobian[i][k] * partialDiff[k]; } // wrong! fix it /* synchronized(this){ for (int i=0;i<numPars;i++) if (partialJacobian[i]!=null){ JtByDiff[i]+=partialJtByDiff[i]; for (int j=i;j<numPars;j++) JtByJmod[i][j]+=partialJtByJmod[i][j]; } } */ synchronizedCombinePartialJacobians(JtByJmod, //Transposed Jacobian multiplied by Jacobian JtByDiff, partialJacobian, partialJtByDiff, partialJtByJmod, numPars); final int numFinished = imageFinishedAtomic.getAndIncrement(); // IJ.showProgress(progressValues[numFinished]); SwingUtilities.invokeLater(new Runnable() { public void run() { // Here, we can safely update the GUI // because we'll be called from the // event dispatch thread IJ.showProgress(progressValues[numFinished]); } }); if (stopRequested.get() == 1) { // ASAP interruptedAtomic.set(true); } // if (debugLevel>1) System.out.println("IJ.showProgress("+progressValues[numImage]+")"); // if (debugLevel>1) IJ.showStatus("Progress "+IJ.d2s(100*progressValues[numImage],2)+"%"); } } }; } startAndJoin(threads); if (interruptedAtomic.get()) { System.out.println("calculateJacobianArrays() aborted by user request"); return null; } if (debugLevel > 3) { String msg = "calculateJacobianArrays() ALL_trace="; for (int ii = 0; ii < numPars; ii++) msg += IJ.d2s(JtByJmod[ii][ii], 5); System.out.println(msg); } for (int i = 0; i < numPars; i++) { // subtract lambda*diagonal , fill the symmetrical half below the diagonal for (int j = 0; j < i; j++) JtByJmod[i][j] = JtByJmod[j][i]; // it is symmetrical matrix, just copy } LMAArrays lMAArrays = new LMAArrays(); lMAArrays.jTByJ = JtByJmod; lMAArrays.jTByDiff = JtByDiff; if (debugLevel > 3) { String msg = "calculateJacobianArrays() lMAArrays.jTByJ trace="; for (int ii = 0; ii < numPars; ii++) msg += IJ.d2s(lMAArrays.jTByJ[ii][ii], 5); System.out.println(msg); } return lMAArrays; }
From source file:Distortions.java
public void allSensorsExtrapolationMapped(final int stationNumber, // has to be selected final double[][][] gridPCorr, final double shrinkBlurComboSigma, final double shrinkBlurComboLevel, final double alphaThreshold, final double step, final double interpolationSigma, final double tangentialRadius, final int scanDistance, final int resultDistance, final int interpolationDegree, final int threadsMax, final boolean updateStatus, final boolean showDebugImages, final int debugLevel) { if (updateStatus) IJ.showStatus("Extrapolating sensor corrections..."); final AtomicInteger sensorNumberAtomic = new AtomicInteger(0); final AtomicInteger sensorFinishedAtomic = new AtomicInteger(0); final Thread[] threads = newThreadArray(threadsMax); final AtomicInteger stopRequested = this.stopRequested; final AtomicBoolean interruptedAtomic = new AtomicBoolean(); final EyesisSubCameraParameters[] eyesisSubCameras = this.fittingStrategy.distortionCalibrationData.eyesisCameraParameters.eyesisSubCameras[stationNumber]; final double[][] sensorMasks = this.fittingStrategy.distortionCalibrationData.sensorMasks; final int alphaIndex = 2; final int sensorWidth = fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorWidth; final int sensorHeight = fittingStrategy.distortionCalibrationData.eyesisCameraParameters.sensorHeight; final int decimation = fittingStrategy.distortionCalibrationData.eyesisCameraParameters.decimateMasks; final int width = (sensorWidth - 1) / decimation + 1; // decimated width (648) final int height = (sensorHeight - 1) / decimation + 1; // decimated width (648) final boolean extraShowDebug = showDebugImages && (debugLevel > 2); for (int ithread = 0; ithread < threads.length; ithread++) { threads[ithread] = new Thread() { public void run() { DoubleGaussianBlur gb = null; double[][] debugMasks1 = null; double[][] debugMasks2 = null; String[] debugMaskTitles = { "original", "blured" }; if (extraShowDebug) { debugMasks1 = new double[2][]; debugMasks2 = new double[2][]; }//from ww w. java2 s. co m if (shrinkBlurComboSigma > 0.0) gb = new DoubleGaussianBlur(); for (int sensorNum = sensorNumberAtomic.getAndIncrement(); (sensorNum < gridPCorr.length) && !interruptedAtomic.get(); sensorNum = sensorNumberAtomic.getAndIncrement()) { if (gridPCorr[sensorNum] != null) { final double[] centerPXY = { eyesisSubCameras[sensorNum].px0, eyesisSubCameras[sensorNum].py0 }; if (shrinkBlurComboSigma > 0.0) { double sigma = shrinkBlurComboSigma / decimation; int margin = (int) (2 * sigma); int width1 = width + 2 * margin; int height1 = height + 2 * margin; if (extraShowDebug) debugMasks2[0] = gridPCorr[sensorNum][alphaIndex].clone(); double[] mask = addMarginsThreshold(gridPCorr[sensorNum][alphaIndex], // double [] data, 0.0, // double threshold, width, height, margin); if (extraShowDebug) debugMasks1[0] = mask.clone(); gb.blurDouble(mask, width1, height1, sigma, sigma, 0.01); double k = 1.0 / (1.0 - shrinkBlurComboLevel); for (int i = 0; i < mask.length; i++) { mask[i] = k * (mask[i] - shrinkBlurComboLevel); mask[i] = (mask[i] > 0.0) ? (mask[i] * mask[i]) : 0.0; } if (extraShowDebug) debugMasks1[1] = mask.clone(); gridPCorr[sensorNum][alphaIndex] = removeMargins(mask, //double [] data, width, // w/o margins height, margin); //mask; // replace with 0.0 .. 1.0 mask if (extraShowDebug) debugMasks2[1] = gridPCorr[sensorNum][alphaIndex].clone(); if (extraShowDebug) { (new showDoubleFloatArrays()).showArrays(debugMasks1, width1, height1, true, "M1-" + sensorNum, debugMaskTitles); (new showDoubleFloatArrays()).showArrays(debugMasks2, width, height, true, "M2-" + sensorNum, debugMaskTitles); } } singleSensorExtrapolationMapped(sensorNum, gridPCorr[sensorNum], sensorMasks[sensorNum], width, decimation, alphaThreshold, step, centerPXY, interpolationSigma, tangentialRadius, scanDistance, resultDistance, interpolationDegree, (shrinkBlurComboSigma > 0.0), showDebugImages, debugLevel); final int numFinished = sensorFinishedAtomic.getAndIncrement(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (updateStatus) IJ.showProgress(numFinished, gridPCorr.length); } }); if (stopRequested.get() == 1) { // ASAP interruptedAtomic.set(true); } } //if (selectedImages[numImage]){ } // for (int numImage=imageNumberAtomic.getAndIncrement(); ... } // public void run() { }; } startAndJoin(threads); if (updateStatus) IJ.showProgress(0); return; }