/** * Prints the message to console */ private void printMessageToConsole(String line) { final ConsoleView console = getConsole(); final LogFilterModel.MyProcessingResult processingResult = myLogFilterModel.processLine(line); if (processingResult.isApplicable()) { final Key key = processingResult.getKey(); if (key != null) { ConsoleViewContentType type = ConsoleViewContentType.getConsoleViewType(key); if (type != null) { final String messagePrefix = processingResult.getMessagePrefix(); if (messagePrefix != null) { String formattedPrefix = logFormatter.formatPrefix(messagePrefix); if (console != null) { console.print(formattedPrefix, type); } } String formattedMessage = logFormatter.formatMessage(line); if (console != null) { console.print(formattedMessage + "\n", type); } } } } }
@Override public void onTextAvailable(ProcessEvent event, Key outputType) { if (!myAuthData.isOAuth2() && !myPasswordEntered && !outputType.equals(ProcessOutputTypes.SYSTEM) && event.getText().contains(myAuthData.getEmail())) { myPasswordEntered = true; final OutputStream processInput = myProcessHandler.getProcessInput(); if (processInput != null) { //noinspection IOResourceOpenedButNotSafelyClosed final PrintWriter input = new PrintWriter(processInput); input.println(myAuthData.getPassword()); input.flush(); String message = StringUtil.repeatSymbol('*', myAuthData.getPassword().length()) + "\n"; if (myConsole != null) { myConsole.print(message, ConsoleViewContentType.USER_INPUT); } else if (myLoggingHandler != null) { myLoggingHandler.print(message); } } } }
@Nullable private static <T> T getCachedValue(PsiExpression expression, Key<T> key) { final T data = expression.getUserData(key); if (!(expression instanceof PsiBinaryExpression)) { return data; } final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; final PsiExpression lhs = binaryExpression.getLOperand(); T childData = null; if (lhs instanceof PsiBinaryExpression) { childData = lhs.getUserData(key); } if (childData == null) { final PsiExpression rhs = binaryExpression.getROperand(); if (rhs instanceof PsiBinaryExpression) { childData = rhs.getUserData(key); } } if (childData != data) { expression.putUserData(key, childData); } return childData; }
/** * Search for data in dataholder or members of union recursively * @param type start point * @param key key to search * @param <T> result tyoe * @return data or null if not found */ @Nullable public static <T> T findData(@NotNull final PyType type, @NotNull final Key<T> key) { if (type instanceof UserDataHolder) { return ((UserDataHolder)type).getUserData(key); } if (type instanceof PyUnionType) { for (final PyType memberType : ((PyUnionType)type).getMembers()) { if (memberType == null) { continue; } final T result = findData(memberType, key); if (result != null) { return result; } } } return null; }
public static GdkMethodHolder getHolderForClass(final PsiClass categoryClass, final boolean isStatic, final GlobalSearchScope scope) { final Project project = categoryClass.getProject(); Key<CachedValue<GdkMethodHolder>> key = isStatic ? CACHED_STATIC : CACHED_NON_STATIC; return CachedValuesManager.getManager(project).getCachedValue(categoryClass, key, new CachedValueProvider<GdkMethodHolder>() { @Override public Result<GdkMethodHolder> compute() { GdkMethodHolder result = new GdkMethodHolder(categoryClass, isStatic, scope); final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); final VirtualFile vfile = categoryClass.getContainingFile().getVirtualFile(); if (vfile != null && (rootManager.getFileIndex().isInLibraryClasses(vfile) || rootManager.getFileIndex().isInLibrarySource(vfile))) { return Result.create(result, rootManager); } return Result.create(result, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT, rootManager); } }, false); }
@NotNull public synchronized MavenEmbedderWrapper getEmbedder(Key kind) { MavenEmbedderWrapper result = myPool.get(kind); boolean alwaysOnline = kind == FOR_DOWNLOAD; if (result == null) { result = MavenServerManager.getInstance().createEmbedder(myProject, alwaysOnline); myPool.put(kind, result); } if (myEmbeddersInUse.contains(result)) { MavenLog.LOG.warn("embedder " + kind + " is already used"); return MavenServerManager.getInstance().createEmbedder(myProject, alwaysOnline); } myEmbeddersInUse.add(result); return result; }
@NotNull public static GrGdkMethod createGdkMethod(@NotNull final PsiMethod original, final boolean isStatic, @Nullable final String originInfo) { final Key<CachedValue<GrGdkMethodImpl>> cachedValueKey = isStatic ? CACHED_STATIC : CACHED_NON_STATIC; CachedValue<GrGdkMethodImpl> cachedValue = original.getUserData(cachedValueKey); if (cachedValue == null) { cachedValue = CachedValuesManager.getManager(original.getProject()).createCachedValue(new CachedValueProvider<GrGdkMethodImpl>() { @Override public Result<GrGdkMethodImpl> compute() { return Result.create(new GrGdkMethodImpl(original, isStatic, originInfo), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT); } }); original.putUserData(cachedValueKey, cachedValue); } return cachedValue.getValue(); }
@NotNull @Override public KeyFMap minus(@NotNull Key<?> key) { int oldSize = size(); int keyCode = key.hashCode(); if (!containsKey(keyCode)) { return this; } if (oldSize == ArrayBackedFMap.ARRAY_THRESHOLD + 1) { int[] keys = keys(); Object[] values = getValues(); int i = ArrayUtil.indexOf(keys, keyCode); keys = ArrayUtil.remove(keys, i); values = ArrayUtil.remove(values, i); return new ArrayBackedFMap(keys, values); } return new MapBackedFMap(this, keyCode); }
@Override public void onLineAvailable(String line, Key outputType) { if (ProcessOutputTypes.STDOUT.equals(outputType)) { final ProgressEvent event = converter.convert(line); if (event != null) { beforeHandler(event); try { callHandler(event); } catch (SVNException e) { cancel(); exception.set(e); } } } }
/** * Notify single line * * @param line a line to notify * @param outputType output type */ private void notifyLine(final String line, final Key outputType) { String trimmed = LineHandlerHelper.trimLineSeparator(line); // if line ends with return, then it is a progress line, ignore it if (myVcs != null && !"\r".equals(line.substring(trimmed.length()))) { if (outputType == ProcessOutputTypes.STDOUT) { if (!isStdoutSuppressed() && !mySilent && !StringUtil.isEmptyOrSpaces(line)) { myVcs.showMessages(trimmed); LOG.info(line.trim()); } else { OUTPUT_LOG.debug(line.trim()); } } else if (outputType == ProcessOutputTypes.STDERR && !isStderrSuppressed() && !mySilent && !StringUtil.isEmptyOrSpaces(line)) { myVcs.showErrorMessages(trimmed); LOG.info(line.trim()); } else { LOG.debug(line.trim()); } } myLineListeners.getMulticaster().onLineAvailable(trimmed, outputType); }
private static Key getProcessOutputType(@NotNull Log.LogLevel level) { switch (level) { case VERBOSE: return AndroidLogcatConstants.VERBOSE; case INFO: return AndroidLogcatConstants.INFO; case DEBUG: return AndroidLogcatConstants.DEBUG; case WARN: return AndroidLogcatConstants.WARNING; case ERROR: return AndroidLogcatConstants.ERROR; case ASSERT: return AndroidLogcatConstants.ASSERT; } return ProcessOutputTypes.STDOUT; }
@Override @Nullable @Contract( pure = true ) public <T> T getCopyableUserData(Key<T> key) { return xmlTag.getCopyableUserData(key); }
@NotNull @Override public MyProcessingResult processLine(String line) { LogCatMessage message = null; String continuation = null; boolean validContinuation = false; try { message = AndroidLogcatFormatter.tryParseMessage(line); continuation = message == null ? AndroidLogcatFormatter.tryParseContinuation(line) : null; validContinuation = continuation != null && this.myPrevHeader != null; } catch (Exception ignored) { } if (message == null && !validContinuation) { return new MyProcessingResult(ProcessOutputTypes.STDOUT, canAcceptMessage(line), null); } else { if (message != null) { this.myPrevHeader = message.getHeader(); this.myCustomApplicable = this.isMessageApplicable(message); this.myMessageSoFar.setLength(0); } boolean isApplicable = this.myCustomApplicable; if (!isApplicable) { this.myMessageSoFar.append(line); this.myMessageSoFar.append('\n'); } Key key = AndroidLogcatUtils.getProcessOutputType(this.myPrevHeader.getLogLevel()); MyProcessingResult result = new MyProcessingResult(key, isApplicable, this.myMessageSoFar.toString()); if (isApplicable) { this.myMessageSoFar.setLength(0); } return result; } }
@Nullable public static <T extends BeforeRunTask> BeforeRunTaskProvider<T> getProvider(Project project, Key<T> key) { BeforeRunTaskProvider<BeforeRunTask>[] providers = Extensions.getExtensions(EXTENSION_POINT_NAME, project); for (BeforeRunTaskProvider<BeforeRunTask> provider : providers) { if (provider.getId() == key) { //noinspection unchecked return (BeforeRunTaskProvider<T>)provider; } } return null; }
@Override public <T> T get(@NotNull Key<T> key) { Object value = myKey.equals(key) ? myValue : null; if (value == null && key instanceof KeyWithDefaultValue) { return ((KeyWithDefaultValue<T>)key).getDefaultValue(); } return (T)value; }
@Override @SuppressWarnings({"unchecked"}) public <T> T getHint(@NotNull Key<T> hintKey) { if (NameHint.KEY == hintKey && myName != null) { return (T)this; } if ((ClassHint.KEY == hintKey || ElementClassHint.KEY == hintKey) && myResolveTargetKinds != null) { return (T)this; } return null; }
public static IdFilter getProjectIdFilter(final Project project, final boolean includeNonProjectItems) { Key<CachedValue<IdFilter>> key = includeNonProjectItems ? OUTSIDE_PROJECT : INSIDE_PROJECT; return CachedValuesManager.getManager(project).getCachedValue(project, key, new CachedValueProvider<IdFilter>() { @Nullable @Override public Result<IdFilter> compute() { return Result.create(buildProjectIdFilter(project, includeNonProjectItems), ProjectRootManager.getInstance(project), VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS); } }, false); }
@Override public void onTextAvailable(ProcessEvent event, Key outputType) { String text = event.getText(); boolean hasError = text != null && text.toLowerCase(Locale.US).contains("error"); if (hasError || ProcessOutputTypes.STDERR.equals(outputType)) { ExecutionManager.getInstance(myProject).getContentManager().toFrontRunContent(myExecutor, myProcessHandler); } }
public static PsiType createTypeFromText(Project project, Key<PsiType> key, String text) { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiType type = project.getUserData(key); if (type == null) { type = factory.createTypeFromText(text, null); project.putUserData(key, type); } return type; }
@NotNull @Override public <V> KeyFMap plus(@NotNull Key<V> key, @NotNull V value) { int keyCode = key.hashCode(); assert keyCode >= 0 : key; @SuppressWarnings("unchecked") V oldValue = (V)get(keyCode); if (value == oldValue) return this; MapBackedFMap newMap = new MapBackedFMap(this, -1); newMap.put(keyCode, value); return newMap; }
@Override public void onTextAvailable(ProcessEvent event, Key outputType) { String line = event.getText(); if (LOG.isDebugEnabled()) { LOG.debug(line); } if (ApplicationManager.getApplication().isUnitTestMode()) { System.out.print(line); } }
@NotNull private static Set<File> getFilesContainer(CompileContext context, final Key<Set<File>> dataKey) { Set<File> files = dataKey.get(context); if (files == null) { files = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY); dataKey.set(context, files); } return files; }
@Override public <T> T getHint(@NotNull Key<T> hintKey) { if (hintKey == ElementClassHint.KEY) { return (T)this; } return super.getHint(hintKey); }
private void processStdOutConsistently(final String text, final Key outputType) { final int textLength = text.length(); if (textLength == 0) { return; } synchronized (myStdOutChunks) { myStdOutChunks.add(new OutputChunk(outputType, text)); } final char lastChar = text.charAt(textLength - 1); if (lastChar == '\n' || lastChar == '\r') { // buffer contains consistent string flushStdOutBuffer(); } else { // test framework may show some promt and ask user for smth. Question may not // finish with \n or \r thus buffer wont be flushed and user will have to input smth // before question. And question will became visible with next portion of text. // Such behaviour is confusing. So // 1. Let's assume that sevice messages starts with \n if console is editable // 2. Then we can suggest that each service message will start from new line and buffer should // be flushed before every service message. Thus if chunks list is empty and output doesn't end // with \n or \r but starts with ##teamcity then it is a service message and should be buffered otherwise // we can safely flush buffer. // TODO if editable: if (myStdinSupportEnabled && !isMostLikelyServiceMessagePart(text)) { flushStdOutBuffer(); } } }
@Override public <T> T getHint(@NotNull Key<T> hintKey) { if (hintKey == ElementClassHint.KEY) { //noinspection unchecked return (T)this; } return super.getHint(hintKey); }
@Override @NotNull public MyProcessingResult processLine(String line) { final String type = LogConsolePreferences.getType(line); Key contentType = type != null ? LogConsolePreferences.getProcessOutputTypes(type) : (LogConsolePreferences.ERROR.equals(myPrevType) ? ProcessOutputTypes.STDERR : ProcessOutputTypes.STDOUT); if (type != null) { myPrevType = type; } final boolean applicable = isApplicable(line); return new MyProcessingResult(contentType, applicable, null); }
private EmulatorOutputReader(@NotNull InputStream stream, @NotNull Key processOutputType) { super(BaseDataReader.SleepingPolicy.SIMPLE); // TODO: charset for the input stream reader? myBufferedReader = new BufferedReader(new InputStreamReader(stream)); myProcessOutputType = processOutputType; start(); }
public void addStdOutput(final String output, final Key outputType) { addLast(new Printable() { public void printOn(final Printer printer) { printer.print(output, ConsoleViewContentType.getConsoleViewType(outputType)); } }); }
@NotNull public <V> V putCachedValue(Key<V> key, @NotNull V value) { ConcurrentHashMap<Key, Object> map = myState.myCache; Object oldValue = map.putIfAbsent(key, value); if (oldValue != null) { return (V)oldValue; } return value; }
@Override public <T> T getUserData(Key<T> key) { if (myUserData == null) { return null; } //noinspection unchecked return (T)myUserData.get(key); }
@Override public <T> void putUserData(Key<T> key, T value) { if(myUserData == null) { myUserData = new SmartHashMap<Key, Object>(); } myUserData.put(key, value); }
@Override public void displayAs(NodeDescriptor descriptor) { if (descriptor instanceof NodeDescriptorImpl) { final NodeDescriptorImpl that = (NodeDescriptorImpl)descriptor; myIsExpanded = that.myIsExpanded; myIsSelected = that.myIsSelected; myIsVisible = that.myIsVisible; myUserData = that.myUserData != null ? new HashMap<Key, Object>(that.myUserData) : null; } }
@Override public void onLineAvailable(String line, Key outputType) { Matcher matcher = PATTERN.matcher(line); if (matcher.matches()) { myBaseBranch = matcher.group(1); } }
private static MergeSearchHelper forMergeList(MergeList mergeList, int contentIndex) { Key<MergeSearchHelper> key = (Key<MergeSearchHelper>)ourMergeListKeys[contentIndex]; MergeSearchHelper helper = mergeList.getUserData(key); if (helper == null) { helper = new MergeSearchHelper(mergeList, contentIndex); mergeList.putUserData(key, helper); } return helper; }
/** * When we send data to svn - we then get it back from corresponding stream. We could receive, for example: * - just sent data - for http, https in Unix * - prompt line + sent data (at the end) - for http, https in Windows * - just new line - for ssh client (as ssh does not output sent data to console) * <p/> * That is why if the next line (after answer is sent) is not explicitly handled, we skip it anyway. */ @Override public boolean handlePrompt(String line, Key outputType) { boolean result = doHandlePrompt(line, outputType); if (!result && mySkipOneLine) { LOG.debug("Skipped " + outputType + " line: " + line); mySkipOneLine = false; result = true; } return result; }
private String execute(@NotNull List<String> parameters, @NotNull File path) throws SvnBindException { // workaround: separately capture command output - used in exception handling logic to overcome svn 1.8 issue (see below) final ProcessOutput output = new ProcessOutput(); LineCommandListener listener = new LineCommandAdapter() { @Override public void onLineAvailable(String line, Key outputType) { if (outputType == ProcessOutputTypes.STDOUT) { output.appendStdout(line); } } }; try { CommandExecutor command = execute(myVcs, SvnTarget.fromFile(path), SvnCommandName.info, parameters, listener); return command.getOutput(); } catch (SvnBindException e) { final String text = StringUtil.notNullize(e.getMessage()); if (text.contains("W155010")) { // if "svn info" is executed for several files at once, then this warning could be printed only for some files, but info for other // files should be parsed from output return output.getStdout(); } // not a working copy exception // "E155007: '' is not a working copy" if (text.contains("is not a working copy") && StringUtil.isNotEmpty(output.getStdout())) { // TODO: Seems not reproducible in 1.8.4 // workaround: as in subversion 1.8 "svn info" on a working copy root outputs such error for parent folder, // if there are files with conflicts. // but the requested info is still in the output except root closing tag return output.getStdout() + "</info>"; } throw e; } }
public void testReadingSeveralStreams() throws Exception { final Map<Key, List<String>> written = new ConcurrentHashMap<Key, List<String>>(); for (final Key each : ALL_TYPES) { written.put(each, new ArrayList<String>()); execute(new Runnable() { @Override public void run() { Random r = new Random(); for (int i = 0; i < 1000; i++) { String s = StringUtil.repeat("A", 100 + r.nextInt(1000)); if (r.nextInt(1) == 1) s += "\n"; mySplitter.process(s, each); List<String> list = written.get(each); if (!list.isEmpty()) { String last = list.get(list.size() - 1); if (!last.endsWith("\n")) { list.set(list.size() - 1, last + s); continue; } } list.add(s); } } }).get(); } mySplitter.flush(); for (Key eachType : ALL_TYPES) { assertOrderedEquals(myOutput.get(eachType), written.get(eachType)); } }
@Override public void onLineAvailable(@NotNull String line, @NotNull Key outputType) { if (line.contains(myEvent.getMessageStartMarker())) { myMessageDetected = true; myFilesAreDisplayed = true; } else if (line.contains(myEvent.getMessageEndMarker())) { myFilesAreDisplayed = false; } else if (myFilesAreDisplayed) { myAffectedFiles.add(line.trim()); } }
public PyRemoteDebugProcessHandler(ProcessHandler handler) { myHandler = handler; myHandler.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(ProcessEvent event, Key outputType) { PyRemoteDebugProcessHandler.this.notifyTextAvailable(event.getText(), outputType); } }); }
public <T> T getUserData(@NotNull Key<T> key) { for (CompileScope compileScope : myScopes) { T userData = compileScope.getUserData(key); if (userData != null) { return userData; } } return super.getUserData(key); }