private synchronized void setWatchRoots( List<String> recursive, List<String> flat, boolean restart) { if (myProcessHandler == null || myProcessHandler.isProcessTerminated()) return; if (ApplicationManager.getApplication().isDisposeInProgress()) { recursive = flat = Collections.emptyList(); } if (!restart && myRecursiveWatchRoots.equals(recursive) && myFlatWatchRoots.equals(flat)) { return; } mySettingRoots.incrementAndGet(); myMapping = emptyList(); myRecursiveWatchRoots = recursive; myFlatWatchRoots = flat; try { writeLine(ROOTS_COMMAND); for (String path : recursive) { writeLine(path); } for (String path : flat) { writeLine("|" + path); } writeLine("#"); } catch (IOException e) { LOG.warn(e); } }
@Override public InputStream sendXmlRpc(byte[] request) throws IOException { // Create a trust manager that does not validate certificate for this connection TrustManager[] trustAllCerts = new TrustManager[] {new PyPITrustManager()}; try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new SecureRandom()); final HttpConfigurable settings = HttpConfigurable.getInstance(); con = settings.openConnection(PYPI_LIST_URL); if (con instanceof HttpsURLConnection) { ((HttpsURLConnection) con).setSSLSocketFactory(sslContext.getSocketFactory()); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); if (auth != null) { con.setRequestProperty("Authorization", "Basic " + auth); } OutputStream out = con.getOutputStream(); out.write(request); out.flush(); out.close(); return con.getInputStream(); } catch (NoSuchAlgorithmException e) { LOG.warn(e.getMessage()); } catch (KeyManagementException e) { LOG.warn(e.getMessage()); } return super.sendXmlRpc(request); }
@NotNull public static <CommitInfo> List<CommitInfo> getCommitRecords( @NotNull Project project, @Nullable HgCommandResult result, @NotNull Function<String, CommitInfo> converter, boolean silent) { final List<CommitInfo> revisions = new LinkedList<CommitInfo>(); if (result == null) { return revisions; } List<String> errors = result.getErrorLines(); if (errors != null && !errors.isEmpty()) { if (result.getExitValue() != 0) { if (silent) { LOG.warn(errors.toString()); } else { VcsNotifier.getInstance(project) .notifyError( HgVcsMessages.message("hg4idea.error.log.command.execution"), errors.toString()); } return Collections.emptyList(); } LOG.warn(errors.toString()); } String output = result.getRawOutput(); List<String> changeSets = StringUtil.split(output, HgChangesetUtil.CHANGESET_SEPARATOR); return ContainerUtil.mapNotNull(changeSets, converter); }
private void deleteInstance(@NotNull final VmwareCloudInstance instance) { if (instance.getErrorInfo() == null) { LOG.info("Will delete instance " + instance.getName()); final VmwareInstance vmInstance; try { vmInstance = myApiConnector.getInstanceDetails(instance.getName()); myAsyncTaskExecutor.executeAsync( vmInstance.deleteInstance(), new ImageStatusTaskWrapper(instance) { @Override public void onSuccess() { removeInstance(instance.getName()); } }); } catch (VmwareCheckedCloudException e) { LOG.warn("An exception during deleting instance " + instance.getName(), e); instance.updateErrors(TypedCloudErrorInfo.fromException(e)); } } else { LOG.warn( String.format( "Won't delete instance %s with error: %s (%s)", instance.getName(), instance.getErrorInfo().getMessage(), instance.getErrorInfo().getDetailedMessage())); } }
public Process createProcess() throws ExecutionException { if (LOG.isDebugEnabled()) { LOG.debug("Executing [" + getCommandLineString() + "]"); } List<String> commands; try { checkWorkingDirectory(); if (StringUtil.isEmptyOrSpaces(myExePath)) { throw new ExecutionException( IdeBundle.message("run.configuration.error.executable.not.specified")); } commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList()); } catch (ExecutionException e) { LOG.warn(e); throw e; } try { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); } catch (IOException e) { LOG.warn(e); throw new ProcessNotCreatedException(e.getMessage(), e, this); } }
@CalledInAwt private void reopenWithTool(@NotNull MergeTool tool) { if (myConflictResolved) { LOG.warn("Can't reopen with " + tool + " - conflict already resolved"); return; } if (!tool.canShow(myContext, myRequest)) { LOG.warn("Can't reopen with " + tool + " - " + myRequest); return; } MergeTool.MergeViewer newViewer; try { newViewer = tool.createComponent(myContext, myRequest); } catch (Throwable e) { LOG.error(e); return; } boolean wasFocused = isFocused(); destroyViewer(); myViewer = newViewer; updateBottomActions(); rebuildSouthPanel(); initViewer(); if (wasFocused) requestFocusInternal(); }
public static Set<String> getPackageNames(final String url) throws IOException { final TreeSet<String> names = new TreeSet<String>(); final HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback() { HTML.Tag myTag; @Override public void handleStartTag(HTML.Tag tag, MutableAttributeSet set, int i) { myTag = tag; } public void handleText(char[] data, int pos) { if (myTag != null && "a".equals(myTag.toString())) { names.add(String.valueOf(data)); } } }; try { final URL repositoryUrl = new URL(url); final InputStream is = repositoryUrl.openStream(); final Reader reader = new InputStreamReader(is); try { new ParserDelegator().parse(reader, callback, true); } catch (IOException e) { LOG.warn(e); } finally { reader.close(); } } catch (MalformedURLException e) { LOG.warn(e); } return names; }
@Nullable private static JsonElement request( @NotNull String host, @Nullable String login, @Nullable String password, @NotNull String path, @Nullable String requestBody, boolean post) { HttpMethod method = null; try { method = doREST(host, login, password, path, requestBody, post); String resp = method.getResponseBodyAsString(); if (method.getStatusCode() != 200) { String message = String.format( "Request not successful. Status-Code: %s, Message: %s.", method.getStatusCode(), method.getStatusText()); LOG.warn(message); throw new HttpStatusException(method.getStatusCode(), method.getStatusText(), message); } if (resp == null) { String message = String.format("Unexpectedly empty response: %s.", resp); LOG.warn(message); throw new RuntimeException(message); } return parseResponse(resp); } catch (IOException e) { LOG.warn(String.format("Request failed: %s", e.getMessage()), e); throw Throwables.propagate(e); } finally { if (method != null) { method.releaseConnection(); } } }
public static SQLRefReference getAnnoRefIdFromMethodCallExpressionElement(PsiElement psiElement) { if (psiElement instanceof PsiMethodCallExpression) { final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression) psiElement).getMethodExpression(); if (methodExpression != null && methodExpression.getQualifierExpression() != null && methodExpression.getQualifierExpression().getType() != null) { final PsiType type = methodExpression.getQualifierExpression().getType(); final PsiClassReferenceType classReferenceType = (PsiClassReferenceType) type; if (type instanceof PsiClassReferenceType && classReferenceType.getReference() != null) { final Project project = psiElement.getProject(); if (AnnoRefConfigSettings.getInstance(project) .getAnnoRefState() .ANNOREF_UTIL_CLASS_FQN .equals(classReferenceType.getReference().getQualifiedName())) { if (((PsiCall) psiElement).getArgumentList().getExpressions().length == 1) { final PsiExpression psiExpression = ((PsiCall) psiElement).getArgumentList().getExpressions()[0]; final String refId = String.valueOf(((PsiLiteral) psiExpression).getValue()); final SQLRefReference refReference = ServiceManager.getService(project, SQLRefRepository.class) .getSQLRefReferenceForID(refId); return refReference; } else { throw new IllegalArgumentException( String.format( "Argument %s for parameter of %s.%s must not be null", new Object[] { "0", classReferenceType.getReference().getQualifiedName(), methodExpression.getQualifiedName() })); } } else { log.warn( "getAnnoRefIdFromMethodCallExpressionElement(): PsiElement ClassReferenceType FQA=" + classReferenceType.getReference().getQualifiedName() + " different" + " from ANNOREF_UTIL_CLASS_FQN=" + AnnoRefConfigSettings.getInstance(project) .getAnnoRefState() .ANNOREF_UTIL_CLASS_FQN); } } else { log.warn( "getAnnoRefIdFromMethodCallExpressionElement(): PsiElement ReferenceType=" + classReferenceType); } } else { log.warn( "getAnnoRefIdFromMethodCallExpressionElement(): PsiElement is of type=" + psiElement.getClass()); } } return null; }
/** * Returns a cloud debugger connection given a user email to indicate the credentials to use. The * function may return null if the user is not logged in. */ @Nullable private static Debugger getClient(final @Nullable String userEmail, final int timeout) { if (Strings.isNullOrEmpty(userEmail)) { LOG.warn("unexpected null email in controller initialize."); return null; } final String hashkey = userEmail + timeout; Debugger cloudDebuggerClient = myDebuggerClientsFromUserEmail.get(hashkey); if (cloudDebuggerClient == null) { try { final CredentialedUser user = GoogleLogin.getInstance().getAllUsers().get(userEmail); final Credential credential = (user != null ? user.getCredential() : null); if (credential != null) { user.getGoogleLoginState() .addLoginListener( new LoginListener() { @Override public void statusChanged(boolean login) { // aggressively remove the cached item on any status change. myDebuggerClientsFromUserEmail.remove(hashkey); } }); HttpRequestInitializer initializer = new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { httpRequest.setConnectTimeout(timeout); httpRequest.setReadTimeout(timeout); credential.initialize(httpRequest); } }; HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); cloudDebuggerClient = new Builder(httpTransport, JSON_FACTORY, initializer) .setRootUrl(ROOT_URL) .setApplicationName(GoogleLoginUtils.getCurrentPlatformName()) .build() .debugger(); } } catch (IOException ex) { LOG.warn("Error connecting to Cloud Debugger API", ex); } catch (GeneralSecurityException ex) { LOG.warn("Error connecting to Cloud Debugger API", ex); } if (cloudDebuggerClient != null) { myDebuggerClientsFromUserEmail.put(hashkey, cloudDebuggerClient); } } return cloudDebuggerClient; }
private boolean isGhcMod5_4(String exePath) { String versionStr = getVersion(exePath, "version"); if (versionStr == null) { LOG.warn("Could not retrieve ghc-mod version from " + exePath); return false; } Pair<Integer, Integer> version = parseGhcModVersion(versionStr); if (version == null) { LOG.warn("Could not parse ghc-mod version from string: " + versionStr); return false; } return version.first > 5 || (version.first == 5 && version.second >= 4); }
private static void checkForUpdates() { PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); long lastUpdate = propertiesComponent.getOrInitLong(KEY, 0); if (lastUpdate == 0 || System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)) { ApplicationManager.getApplication() .executeOnPooledThread( () -> { try { String buildNumber = ApplicationInfo.getInstance().getBuild().asString(); IdeaPluginDescriptor plugin = getPlugin(); String pluginVersion = plugin.getVersion(); String pluginId = plugin.getPluginId().getIdString(); String os = URLEncoder.encode( SystemInfo.OS_NAME + " " + SystemInfo.OS_VERSION, CharsetToolkit.UTF8); String uid = PermanentInstallationID.get(); String url = "https://plugins.jetbrains.com/plugins/list" + "?pluginId=" + pluginId + "&build=" + buildNumber + "&pluginVersion=" + pluginVersion + "&os=" + os + "&uuid=" + uid; PropertiesComponent.getInstance() .setValue(KEY, String.valueOf(System.currentTimeMillis())); HttpRequests.request(url) .connect( request -> { try { JDOMUtil.load(request.getReader()); LOG.info( (request.isSuccessful() ? "Successful" : "Unsuccessful") + " update: " + url); } catch (JDOMException e) { LOG.warn(e); } return null; }); } catch (UnknownHostException ignored) { } catch (IOException e) { LOG.warn(e); } }); } }
protected void runOverEditor( @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile psiFile) { final Document document = editor.getDocument(); if (!ReadonlyStatusHandler.ensureDocumentWritable(project, document)) return; final Runnable runnable = () -> { final int caretOffset = editor.getCaretModel().getOffset(); final int lineLength = getRightMargin(project); DartAnalysisServerService.getInstance().updateFilesContent(); DartAnalysisServerService.FormatResult formatResult = DartAnalysisServerService.getInstance() .edit_format(psiFile.getVirtualFile(), caretOffset, 0, lineLength); if (formatResult == null) { showHintLater(editor, DartBundle.message("dart.style.hint.failed"), true); LOG.warn("Unexpected response from edit_format, formatResult is null"); return; } final List<SourceEdit> edits = formatResult.getEdits(); if (edits == null || edits.size() == 0) { showHintLater(editor, DartBundle.message("dart.style.hint.already.good"), false); } else if (edits.size() == 1) { final String replacement = StringUtil.convertLineSeparators(edits.get(0).getReplacement()); document.replaceString(0, document.getTextLength(), replacement); final int offset = DartAnalysisServerService.getInstance() .getConvertedOffset(psiFile.getVirtualFile(), formatResult.getOffset()); editor.getCaretModel().moveToOffset(offset); showHintLater(editor, DartBundle.message("dart.style.hint.success"), false); } else { showHintLater(editor, DartBundle.message("dart.style.hint.failed"), true); LOG.warn( "Unexpected response from edit_format, formatResult.getEdits().size() = " + edits.size()); } }; ApplicationManager.getApplication() .runWriteAction( () -> CommandProcessor.getInstance() .executeCommand( project, runnable, DartBundle.message("dart.style.action.name"), null)); }
private void mergeWithDefaultConfiguration() { final ArrayList<Configuration> cfgList = new ArrayList<Configuration>(); for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) { final String config = support.getDefaultConfigUrl(); final URL url = config == null ? null : support.getClass().getResource(config); if (url != null) { try { cfgList.add(load(url.openStream())); } catch (Exception e) { LOG.warn(e); } } } final THashSet<Object> visited = new THashSet<Object>(); for (IdeaPluginDescriptor pluginDescriptor : PluginManager.getPlugins()) { if (pluginDescriptor instanceof IdeaPluginDescriptorImpl && !((IdeaPluginDescriptorImpl) pluginDescriptor).isEnabled()) continue; final ClassLoader loader = pluginDescriptor.getPluginClassLoader(); if (!visited.add(loader)) continue; if (loader instanceof PluginClassLoader && ((PluginClassLoader) loader).getUrls().isEmpty()) continue; try { final Enumeration<URL> enumeration = loader.getResources("META-INF/languageInjections.xml"); if (enumeration == null) continue; while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); if (!visited.add(url.getFile())) continue; // for DEBUG mode try { cfgList.add(load(url.openStream())); } catch (Exception e) { LOG.warn(e); } } } catch (Exception e) { LOG.warn(e); } } final ArrayList<BaseInjection> originalInjections = new ArrayList<BaseInjection>(); final ArrayList<BaseInjection> newInjections = new ArrayList<BaseInjection>(); myDefaultInjections = new ArrayList<BaseInjection>(); for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) { for (Configuration cfg : cfgList) { final List<BaseInjection> imported = cfg.getInjections(supportId); myDefaultInjections.addAll(imported); importInjections(getInjections(supportId), imported, originalInjections, newInjections); } } replaceInjections(newInjections, originalInjections); }
@Override public void importData( @NotNull Collection<DataNode<LibraryDependencyData>> toImport, @NotNull Project project, boolean synchronous) { if (toImport.isEmpty()) { return; } Map<DataNode<ModuleData>, List<DataNode<LibraryDependencyData>>> byModule = ExternalSystemApiUtil.groupBy(toImport, MODULE); for (Map.Entry<DataNode<ModuleData>, List<DataNode<LibraryDependencyData>>> entry : byModule.entrySet()) { Module module = myProjectStructureHelper.findIdeModule(entry.getKey().getData(), project); if (module == null) { myModuleManager.importData(Collections.singleton(entry.getKey()), project, true); module = myProjectStructureHelper.findIdeModule(entry.getKey().getData(), project); if (module == null) { LOG.warn( String.format( "Can't import library dependencies %s. Reason: target module (%s) is not found at the ide and can't be imported", entry.getValue(), entry.getKey())); continue; } } importData(entry.getValue(), module, synchronous); } }
@NotNull public static <K, V> Map<K, List<V>> groupBy( @NotNull Collection<V> nodes, @NotNull NullableFunction<V, K> grouper) { Map<K, List<V>> result = ContainerUtilRt.newHashMap(); for (V data : nodes) { K key = grouper.fun(data); if (key == null) { LOG.warn( String.format( "Skipping entry '%s' during grouping. Reason: it's not possible to build a grouping key with grouping strategy '%s'. " + "Given entries: %s", data, grouper.getClass(), nodes)); continue; } List<V> grouped = result.get(key); if (grouped == null) { result.put(key, grouped = ContainerUtilRt.newArrayList()); } grouped.add(data); } if (!result.isEmpty() && result.keySet().iterator().next() instanceof Comparable) { List<K> ordered = ContainerUtilRt.newArrayList(result.keySet()); Collections.sort(ordered, COMPARABLE_GLUE); Map<K, List<V>> orderedResult = ContainerUtilRt.newLinkedHashMap(); for (K k : ordered) { orderedResult.put(k, result.get(k)); } return orderedResult; } return result; }
/** * Gets the profile picture that corresponds to the {@code userInfo} and sets it on the provided * {@code pictureCallback}. * * @param userInfo the class to be parsed * @param pictureCallback the user image will be set on this callback */ public static void provideUserPicture( Userinfoplus userInfo, final IUserPropertyCallback pictureCallback) { // set the size of the image before it is served String urlString = userInfo.getPicture() + "?sz=" + DEFAULT_PICTURE_SIZE; URL url = null; try { url = new URL(urlString); } catch (MalformedURLException ex) { LOG.warn(String.format("The picture URL: %s, is not a valid URL string.", urlString), ex); return; } final URL newUrl = url; ApplicationManager.getApplication() .executeOnPooledThread( new Runnable() { @Override public void run() { Image image = Toolkit.getDefaultToolkit().getImage(newUrl); Toolkit.getDefaultToolkit().prepareImage(image, -1, -1, null); pictureCallback.setProperty(image); } }); }
@Override protected boolean isComponentSuitable(@Nullable Map<String, String> options) { if (!super.isComponentSuitable(options)) { return false; } if (options == null || options.isEmpty()) { return true; } for (String optionName : options.keySet()) { if ("workspace".equals(optionName)) { continue; } // we cannot filter using module options because at this moment module file data could be not // loaded String message = "Don't specify " + optionName + " in the component registration, transform component to service and implement your logic in your getInstance() method"; if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(message); } else { LOG.warn(message); } } return true; }
@NotNull @Override public LightClassConstructionContext getContextForClassOrObject( @NotNull JetClassOrObject classOrObject) { ResolveSessionForBodies session = KotlinCacheService.getInstance(classOrObject.getProject()) .getLazyResolveSession(classOrObject); if (classOrObject.isLocal()) { BindingContext bindingContext = session.resolveToElement(classOrObject, BodyResolveMode.FULL); ClassDescriptor descriptor = bindingContext.get(BindingContext.CLASS, classOrObject); if (descriptor == null) { LOG.warn( "No class descriptor in context for class: " + PsiUtilPackage.getElementTextWithContext(classOrObject)); return new LightClassConstructionContext(bindingContext, session.getModuleDescriptor()); } ForceResolveUtil.forceResolveAllContents(descriptor); return new LightClassConstructionContext(bindingContext, session.getModuleDescriptor()); } ForceResolveUtil.forceResolveAllContents(session.getClassDescriptor(classOrObject)); return new LightClassConstructionContext( session.getBindingContext(), session.getModuleDescriptor()); }
/** * Given the list of paths converts them to the list of {@link Change Changes} found in the {@link * ChangeListManager}, i.e. this works only for local changes. </br> Paths can be absolute or * relative to the repository. If a path is not found in the local changes, it is ignored, but the * fact is logged. */ @NotNull public static List<Change> findLocalChangesForPaths( @NotNull Project project, @NotNull VirtualFile root, @NotNull Collection<String> affectedPaths, boolean relativePaths) { ChangeListManagerEx changeListManager = (ChangeListManagerEx) ChangeListManager.getInstance(project); List<Change> affectedChanges = new ArrayList<Change>(); for (String path : affectedPaths) { String absolutePath = relativePaths ? toAbsolute(root, path) : path; VirtualFile file = findRefreshFileOrLog(absolutePath); if (file != null) { Change change = changeListManager.getChange(file); if (change != null) { affectedChanges.add(change); } else { String message = "Change is not found for " + file.getPath(); if (changeListManager.isInUpdate()) { message += " because ChangeListManager is being updated."; } LOG.warn(message); } } } return affectedChanges; }
static { System.setProperty("svnkit.log.native.calls", "true"); final SvnKitDebugLogger logger = new SvnKitDebugLogger( Boolean.getBoolean(LOG_PARAMETER_NAME), Boolean.getBoolean(TRACE_NATIVE_CALLS), LOG); SVNDebugLog.setDefaultLog(logger); SVNJNAUtil.setJNAEnabled(true); SvnHttpAuthMethodsDefaultChecker.check(); SVNAdminAreaFactory.setSelector(new SvnKitAdminAreaFactorySelector()); DAVRepositoryFactory.setup(); SVNRepositoryFactoryImpl.setup(); FSRepositoryFactory.setup(); // non-optimized writing is fast enough on Linux/MacOS, and somewhat more reliable if (SystemInfo.isWindows) { SVNAdminArea14.setOptimizedWritingEnabled(true); } if (!SVNJNAUtil.isJNAPresent()) { LOG.warn("JNA is not found by svnkit library"); } ourExplicitlySetSslProtocols = System.getProperty(SVNKIT_HTTP_SSL_PROTOCOLS); }
private void checkFsSanity() { try { String path = myProject.getProjectFilePath(); if (path == null || FileUtil.isAncestor(PathManager.getConfigPath(), path, true)) { return; } boolean actual = FileUtil.isFileSystemCaseSensitive(path); LOG.info(path + " case-sensitivity: " + actual); if (actual != SystemInfo.isFileSystemCaseSensitive) { int prefix = SystemInfo.isFileSystemCaseSensitive ? 1 : 0; // IDE=true -> FS=false -> prefix='in' String title = ApplicationBundle.message("fs.case.sensitivity.mismatch.title"); String text = ApplicationBundle.message("fs.case.sensitivity.mismatch.message", prefix); Notifications.Bus.notify( new Notification( Notifications.SYSTEM_MESSAGES_GROUP_ID, title, text, NotificationType.WARNING, NotificationListener.URL_OPENING_LISTENER), myProject); } } catch (FileNotFoundException e) { LOG.warn(e); } }
@Override public void compileAndRun( @NotNull final Runnable startRunnable, @NotNull final ExecutionEnvironment environment, @Nullable final RunProfileState state, @Nullable final Runnable onCancelRunnable) { long id = environment.getExecutionId(); if (id == 0) { id = environment.assignNewExecutionId(); } RunProfile profile = environment.getRunProfile(); if (!(profile instanceof RunConfiguration)) { startRunnable.run(); return; } final RunConfiguration runConfiguration = (RunConfiguration) profile; final List<BeforeRunTask> beforeRunTasks = RunManagerEx.getInstanceEx(myProject).getBeforeRunTasks(runConfiguration); if (beforeRunTasks.isEmpty()) { startRunnable.run(); } else { DataContext context = environment.getDataContext(); final DataContext projectContext = context != null ? context : SimpleDataContext.getProjectContext(myProject); final long finalId = id; final Long executionSessionId = new Long(id); ApplicationManager.getApplication() .executeOnPooledThread( () -> { for (BeforeRunTask task : beforeRunTasks) { if (myProject.isDisposed()) { return; } @SuppressWarnings("unchecked") BeforeRunTaskProvider<BeforeRunTask> provider = BeforeRunTaskProvider.getProvider(myProject, task.getProviderId()); if (provider == null) { LOG.warn( "Cannot find BeforeRunTaskProvider for id='" + task.getProviderId() + "'"); continue; } ExecutionEnvironment taskEnvironment = new ExecutionEnvironmentBuilder(environment).contentToReuse(null).build(); taskEnvironment.setExecutionId(finalId); EXECUTION_SESSION_ID_KEY.set(taskEnvironment, executionSessionId); if (!provider.executeTask( projectContext, runConfiguration, taskEnvironment, task)) { if (onCancelRunnable != null) { SwingUtilities.invokeLater(onCancelRunnable); } return; } } doRun(environment, startRunnable); }); } }
private List<VFileEvent> getEvents(String msg, @Nullable Runnable action) { LOG.debug("** waiting for " + msg); myAccept = true; if (action != null) { action.run(); } int timeout = myTimeout; try { synchronized (myWaiter) { //noinspection WaitNotInLoop myWaiter.wait(timeout); } } catch (InterruptedException e) { LOG.warn(e); } LOG.debug("** waited for " + timeout); myFileSystem.refresh(false); ArrayList<VFileEvent> result; synchronized (myEvents) { result = new ArrayList<VFileEvent>(myEvents); myEvents.clear(); } LOG.debug("** events: " + result.size()); return result; }
/** * Callback function for when GDB has responded to our expression evaluation request. * * @param event The event. * @param callback The callback passed to evaluate(). */ private void onGdbExpressionReady(GdbEvent event, XEvaluationCallback callback) { if (event instanceof GdbErrorEvent) { callback.errorOccurred(((GdbErrorEvent) event).message); return; } if (!(event instanceof GdbVariableObjects)) { callback.errorOccurred("Unexpected data received from GDB"); m_log.warn("Unexpected event " + event + " received from expression request"); return; } GdbVariableObjects variableObjects = (GdbVariableObjects) event; if (variableObjects.objects.isEmpty()) { callback.errorOccurred("Failed to evaluate expression"); return; } GdbVariableObject variableObject = variableObjects.objects.get(0); if (variableObject.value == null) { callback.errorOccurred("Failed to evaluate expression"); return; } callback.evaluated(new GdbValue(m_gdb, variableObject)); }
/** * TODO this is non-optimal and even incorrect, since such diff shows the difference between * committed changes For each of the given repositories looks to the diff between current branch * and the given branch and converts it to the list of local changes. */ @NotNull Map<GitRepository, List<Change>> collectLocalChangesConflictingWithBranch( @NotNull Collection<GitRepository> repositories, @NotNull String currentBranch, @NotNull String otherBranch) { Map<GitRepository, List<Change>> changes = new HashMap<GitRepository, List<Change>>(); for (GitRepository repository : repositories) { try { Collection<String> diff = GitUtil.getPathsDiffBetweenRefs(myGit, repository, currentBranch, otherBranch); List<Change> changesInRepo = convertPathsToChanges(repository, diff, false); if (!changesInRepo.isEmpty()) { changes.put(repository, changesInRepo); } } catch (VcsException e) { // ignoring the exception: this is not fatal if we won't collect such a diff from other // repositories. // At worst, use will get double dialog proposing the smart checkout. LOG.warn( String.format( "Couldn't collect diff between %s and %s in %s", currentBranch, otherBranch, repository.getRoot()), e); } } return changes; }
@Override public void initialize( @NotNull ManagingFS managingFS, @NotNull FileWatcherNotificationSink notificationSink) { myManagingFS = managingFS; myNotificationSink = notificationSink; boolean disabled = Boolean.parseBoolean(System.getProperty(PROPERTY_WATCHER_DISABLED)); myExecutable = getExecutable(); if (disabled) { LOG.info("Native file watcher is disabled"); } else if (myExecutable == null) { LOG.info("Native file watcher is not supported on this platform"); } else if (!myExecutable.exists()) { notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"), null); } else if (!myExecutable.canExecute()) { notifyOnFailure( ApplicationBundle.message("watcher.exe.not.exe", myExecutable), new NotificationListener() { @Override public void hyperlinkUpdate( @NotNull Notification notification, @NotNull HyperlinkEvent event) { ShowFilePathAction.openFile(myExecutable); } }); } else { try { startupProcess(false); LOG.info("Native file watcher is operational."); } catch (IOException e) { LOG.warn(e.getMessage()); notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null); } } }
@NotNull private static List<RepoPackage> getPackagesFromAdditionalRepository(@NotNull String url) throws IOException { final List<RepoPackage> result = new ArrayList<>(); final boolean simpleIndex = url.endsWith("simple/"); final List<String> packagesList = parsePyPIListFromWeb(url, simpleIndex); for (String pyPackage : packagesList) { if (simpleIndex) { final Pair<String, String> nameVersion = splitNameVersion(StringUtil.trimTrailing(pyPackage, '/')); result.add(new RepoPackage(nameVersion.getFirst(), url, nameVersion.getSecond())); } else { try { final Pattern repositoryPattern = Pattern.compile(url + "([^/]*)/([^/]*)$"); final Matcher matcher = repositoryPattern.matcher(URLDecoder.decode(pyPackage, "UTF-8")); if (matcher.find()) { final String packageName = matcher.group(1); final String packageVersion = matcher.group(2); if (!packageName.contains(" ")) { result.add(new RepoPackage(packageName, url, packageVersion)); } } } catch (UnsupportedEncodingException e) { LOG.warn(e.getMessage()); } } } return result; }
public static void setReadOnlyAttribute(@NotNull String path, boolean readOnlyFlag) { final boolean writableFlag = !readOnlyFlag; final File file = new File(path); if (!file.setWritable(writableFlag) && file.canWrite() != writableFlag) { LOG.warn("Can't set writable attribute of '" + path + "' to " + readOnlyFlag); } }
@Override protected void save(@NotNull Collection<VirtualFile> rootsToSave) throws VcsException { LOG.info("saving " + rootsToSave); for (VirtualFile root : rootsToSave) { final String message = GitHandlerUtil.formatOperationName("Stashing changes from", root); LOG.info(message); final String oldProgressTitle = myProgressIndicator.getText(); myProgressIndicator.setText(message); GitRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) { LOG.error("Repository is null for root " + root); } else { GitCommandResult result = myGit.stashSave(repository, myStashMessage); if (result.success() && somethingWasStashed(result)) { myStashedRoots.add(root); } else { String error = "stash " + repository.getRoot() + ": " + result.getErrorOutputAsJoinedString(); if (!result.success()) { throw new VcsException(error); } else { LOG.warn(error); } } } myProgressIndicator.setText(oldProgressTitle); } }