repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/psi/impl/MipsFileImpl.java
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // }
import com.equadon.intellij.mips.lang.MipsLanguage; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi.impl; public class MipsFileImpl extends PsiFileBase implements MipsFile { public MipsFileImpl(@NotNull FileViewProvider viewProvider) {
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // Path: src/com/equadon/intellij/mips/lang/psi/impl/MipsFileImpl.java import com.equadon.intellij.mips.lang.MipsLanguage; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.extapi.psi.PsiFileBase; import com.intellij.openapi.fileTypes.FileType; import com.intellij.psi.FileViewProvider; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi.impl; public class MipsFileImpl extends PsiFileBase implements MipsFile { public MipsFileImpl(@NotNull FileViewProvider viewProvider) {
super(viewProvider, MipsLanguage.INSTANCE);
equadon/intellij-mips
src/com/equadon/intellij/mips/run/controllers/MipsConsoleInputStream.java
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // }
import com.equadon.intellij.mips.icons.MipsIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.InputStream;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.controllers; public class MipsConsoleInputStream extends InputStream { private final Project project; private String message = null; private String buffer = null; private boolean eof; public MipsConsoleInputStream(Project project) { this.project = project; this.message = ""; eof = false; } public void setMessage(String message) { this.message += message; } @Override public int read(@NotNull byte[] bytes, int offset, int length) throws IOException { if (eof) return -1; readInput(); for (int i = offset; i < buffer.length(); i++) bytes[i] = (byte) buffer.charAt(i); eof = true; return buffer.length(); } private void readInput() { ApplicationManager.getApplication().invokeAndWait(() -> {
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // Path: src/com/equadon/intellij/mips/run/controllers/MipsConsoleInputStream.java import com.equadon.intellij.mips.icons.MipsIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.InputStream; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.controllers; public class MipsConsoleInputStream extends InputStream { private final Project project; private String message = null; private String buffer = null; private boolean eof; public MipsConsoleInputStream(Project project) { this.project = project; this.message = ""; eof = false; } public void setMessage(String message) { this.message += message; } @Override public int read(@NotNull byte[] bytes, int offset, int length) throws IOException { if (eof) return -1; readInput(); for (int i = offset; i < buffer.length(); i++) bytes[i] = (byte) buffer.charAt(i); eof = true; return buffer.length(); } private void readInput() { ApplicationManager.getApplication().invokeAndWait(() -> {
buffer = Messages.showInputDialog(project, message, "MIPS Input Dialog", MipsIcons.FILE);
equadon/intellij-mips
src/com/equadon/intellij/mips/icons/MipsIconProvider.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // }
import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.ide.IconProvider; import com.intellij.openapi.util.Iconable; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.icons; public class MipsIconProvider extends IconProvider { @Nullable @Override public Icon getIcon(@NotNull PsiElement e, @Iconable.IconFlags int flags) {
// Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // Path: src/com/equadon/intellij/mips/icons/MipsIconProvider.java import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.ide.IconProvider; import com.intellij.openapi.util.Iconable; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.icons; public class MipsIconProvider extends IconProvider { @Nullable @Override public Icon getIcon(@NotNull PsiElement e, @Iconable.IconFlags int flags) {
if (e instanceof MipsFile) return MipsIcons.FILE;
equadon/intellij-mips
src/com/equadon/intellij/mips/formatter/MipsFormattingBlock.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.formatting.Alignment; import com.intellij.formatting.Block; import com.intellij.formatting.Indent; import com.intellij.formatting.Spacing; import com.intellij.formatting.SpacingBuilder; import com.intellij.formatting.Wrap; import com.intellij.lang.ASTNode; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.formatter.common.AbstractBlock; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.formatter; public class MipsFormattingBlock extends AbstractBlock { private final SpacingBuilder spacingBuilder; private final CommonCodeStyleSettings commonSettings; private final MipsCodeStyleSettings mipsSettings; public MipsFormattingBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment, SpacingBuilder spacingBuilder, CommonCodeStyleSettings commonSettings, MipsCodeStyleSettings mipsSettings) { super(node, wrap, alignment); this.spacingBuilder = spacingBuilder; this.commonSettings = commonSettings; this.mipsSettings = mipsSettings; } @Override protected List<Block> buildChildren() { final List<Block> blocks = new ArrayList<>(); for (ASTNode child = myNode.getFirstChildNode(); child != null; child = child.getTreeNext()) { if (!shouldCreateBlockFor(child)) continue; blocks.add(createChildBlock(myNode, child)); } return Collections.unmodifiableList(blocks); } private boolean shouldCreateBlockFor(ASTNode node) { IElementType type = node.getElementType();
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // Path: src/com/equadon/intellij/mips/formatter/MipsFormattingBlock.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.formatting.Alignment; import com.intellij.formatting.Block; import com.intellij.formatting.Indent; import com.intellij.formatting.Spacing; import com.intellij.formatting.SpacingBuilder; import com.intellij.formatting.Wrap; import com.intellij.lang.ASTNode; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.formatter.common.AbstractBlock; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.formatter; public class MipsFormattingBlock extends AbstractBlock { private final SpacingBuilder spacingBuilder; private final CommonCodeStyleSettings commonSettings; private final MipsCodeStyleSettings mipsSettings; public MipsFormattingBlock(@NotNull ASTNode node, @Nullable Wrap wrap, @Nullable Alignment alignment, SpacingBuilder spacingBuilder, CommonCodeStyleSettings commonSettings, MipsCodeStyleSettings mipsSettings) { super(node, wrap, alignment); this.spacingBuilder = spacingBuilder; this.commonSettings = commonSettings; this.mipsSettings = mipsSettings; } @Override protected List<Block> buildChildren() { final List<Block> blocks = new ArrayList<>(); for (ASTNode child = myNode.getFirstChildNode(); child != null; child = child.getTreeNext()) { if (!shouldCreateBlockFor(child)) continue; blocks.add(createChildBlock(myNode, child)); } return Collections.unmodifiableList(blocks); } private boolean shouldCreateBlockFor(ASTNode node) { IElementType type = node.getElementType();
return getTextRange().getLength() != 0 && !MipsTokenTypes.WHITE_SPACES.contains(type);
equadon/intellij-mips
src/com/equadon/intellij/mips/run/debugger/MipsLineBreakpointType.java
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // }
import com.equadon.intellij.mips.lang.MipsFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.breakpoints.XBreakpointProperties; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.breakpoints.XLineBreakpointTypeBase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.debugger; public class MipsLineBreakpointType extends XLineBreakpointTypeBase { protected MipsLineBreakpointType() { super("mips-line", "MIPS Line Breakpoint", new MipsDebuggerEditorsProvider()); } @Override public String getDisplayText(XLineBreakpoint<XBreakpointProperties> breakpoint) { XSourcePosition sourcePosition = breakpoint.getSourcePosition(); assert sourcePosition != null; return "Line " + String.valueOf(sourcePosition.getLine()) + " in file " + sourcePosition.getFile().getName(); } @Override public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) {
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // Path: src/com/equadon/intellij/mips/run/debugger/MipsLineBreakpointType.java import com.equadon.intellij.mips.lang.MipsFileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.breakpoints.XBreakpointProperties; import com.intellij.xdebugger.breakpoints.XLineBreakpoint; import com.intellij.xdebugger.breakpoints.XLineBreakpointTypeBase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.debugger; public class MipsLineBreakpointType extends XLineBreakpointTypeBase { protected MipsLineBreakpointType() { super("mips-line", "MIPS Line Breakpoint", new MipsDebuggerEditorsProvider()); } @Override public String getDisplayText(XLineBreakpoint<XBreakpointProperties> breakpoint) { XSourcePosition sourcePosition = breakpoint.getSourcePosition(); assert sourcePosition != null; return "Line " + String.valueOf(sourcePosition.getLine()) + " in file " + sourcePosition.getFile().getName(); } @Override public boolean canPutAt(@NotNull VirtualFile file, int line, @NotNull Project project) {
return file.getFileType() == MipsFileType.INSTANCE;
equadon/intellij-mips
src/com/equadon/intellij/mips/MarsUtils.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java // public class MipsElementType extends IElementType { // public MipsElementType(@NotNull String debug) { // super(debug, MipsLanguage.INSTANCE); // } // // public static IElementType fromToken(@NotNull Token token) throws MipsException { // TokenTypes type = token.getType(); // // if (type.equals(TokenTypes.COLON)) // return MipsElementTypes.COLON; // if (type.equals(TokenTypes.COMMENT)) // return MipsTokenTypes.COMMENT; // if (type.equals(TokenTypes.DELIMITER)) // return TokenType.WHITE_SPACE; // if (type.equals(TokenTypes.DIRECTIVE)) // return MipsElementTypes.DIRECTIVE; // // if (type.equals(TokenTypes.EOL)) // // return MipsElementTypes.EOL; // if (type.equals(TokenTypes.ERROR)) // return TokenType.BAD_CHARACTER; // if (type.equals(TokenTypes.IDENTIFIER)) // return MipsElementTypes.IDENTIFIER; // if (type.equals(TokenTypes.INTEGER_5)) // return MipsElementTypes.INTEGER_5; // if (type.equals(TokenTypes.INTEGER_16)) // return MipsElementTypes.INTEGER_16; // if (type.equals(TokenTypes.INTEGER_16U)) // return MipsElementTypes.INTEGER_16U; // if (type.equals(TokenTypes.INTEGER_32)) // return MipsElementTypes.INTEGER_32; // if (type.equals(TokenTypes.LEFT_PAREN)) // return MipsElementTypes.LPAREN; // if (type.equals(TokenTypes.MINUS)) // return MipsElementTypes.MINUS; // if (type.equals(TokenTypes.OPERATOR)) // return MipsElementTypes.OPERATOR; // if (type.equals(TokenTypes.PLUS)) // return MipsElementTypes.PLUS; // if (type.equals(TokenTypes.QUOTED_STRING)) // return MipsElementTypes.QUOTED_STRING; // if (type.equals(TokenTypes.REAL_NUMBER)) // return MipsElementTypes.REAL_NUMBER; // if (type.equals(TokenTypes.REGISTER_NAME)) // return MipsElementTypes.REGISTER_NAME; // if (type.equals(TokenTypes.REGISTER_NUMBER)) // return MipsElementTypes.REGISTER_NUMBER; // if (type.equals(TokenTypes.RIGHT_PAREN)) // return MipsElementTypes.RPAREN; // // throw new MipsException("Unknown token type: " + type); // } // }
import com.equadon.intellij.mips.lang.psi.MipsElementType; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import mars.assembler.Token; import mars.assembler.TokenTypes;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MarsUtils { /** * Helper method for the lexer to get the correct element type. * @param text token string to find * @return element type */ public static IElementType getTokenType(CharSequence text) { TokenTypes type = TokenTypes.matchTokenType(text.toString()); try {
// Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java // public class MipsElementType extends IElementType { // public MipsElementType(@NotNull String debug) { // super(debug, MipsLanguage.INSTANCE); // } // // public static IElementType fromToken(@NotNull Token token) throws MipsException { // TokenTypes type = token.getType(); // // if (type.equals(TokenTypes.COLON)) // return MipsElementTypes.COLON; // if (type.equals(TokenTypes.COMMENT)) // return MipsTokenTypes.COMMENT; // if (type.equals(TokenTypes.DELIMITER)) // return TokenType.WHITE_SPACE; // if (type.equals(TokenTypes.DIRECTIVE)) // return MipsElementTypes.DIRECTIVE; // // if (type.equals(TokenTypes.EOL)) // // return MipsElementTypes.EOL; // if (type.equals(TokenTypes.ERROR)) // return TokenType.BAD_CHARACTER; // if (type.equals(TokenTypes.IDENTIFIER)) // return MipsElementTypes.IDENTIFIER; // if (type.equals(TokenTypes.INTEGER_5)) // return MipsElementTypes.INTEGER_5; // if (type.equals(TokenTypes.INTEGER_16)) // return MipsElementTypes.INTEGER_16; // if (type.equals(TokenTypes.INTEGER_16U)) // return MipsElementTypes.INTEGER_16U; // if (type.equals(TokenTypes.INTEGER_32)) // return MipsElementTypes.INTEGER_32; // if (type.equals(TokenTypes.LEFT_PAREN)) // return MipsElementTypes.LPAREN; // if (type.equals(TokenTypes.MINUS)) // return MipsElementTypes.MINUS; // if (type.equals(TokenTypes.OPERATOR)) // return MipsElementTypes.OPERATOR; // if (type.equals(TokenTypes.PLUS)) // return MipsElementTypes.PLUS; // if (type.equals(TokenTypes.QUOTED_STRING)) // return MipsElementTypes.QUOTED_STRING; // if (type.equals(TokenTypes.REAL_NUMBER)) // return MipsElementTypes.REAL_NUMBER; // if (type.equals(TokenTypes.REGISTER_NAME)) // return MipsElementTypes.REGISTER_NAME; // if (type.equals(TokenTypes.REGISTER_NUMBER)) // return MipsElementTypes.REGISTER_NUMBER; // if (type.equals(TokenTypes.RIGHT_PAREN)) // return MipsElementTypes.RPAREN; // // throw new MipsException("Unknown token type: " + type); // } // } // Path: src/com/equadon/intellij/mips/MarsUtils.java import com.equadon.intellij.mips.lang.psi.MipsElementType; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import mars.assembler.Token; import mars.assembler.TokenTypes; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MarsUtils { /** * Helper method for the lexer to get the correct element type. * @param text token string to find * @return element type */ public static IElementType getTokenType(CharSequence text) { TokenTypes type = TokenTypes.matchTokenType(text.toString()); try {
return MipsElementType.fromToken(new Token(type, null, null, 0, 0));
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/psi/MipsElementType.java
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // }
import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.MipsLanguage; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import mars.assembler.Token; import mars.assembler.TokenTypes;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi; public class MipsElementType extends IElementType { public MipsElementType(@NotNull String debug) {
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.MipsLanguage; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import mars.assembler.Token; import mars.assembler.TokenTypes; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi; public class MipsElementType extends IElementType { public MipsElementType(@NotNull String debug) {
super(debug, MipsLanguage.INSTANCE);
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/psi/MipsElementType.java
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // }
import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.MipsLanguage; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import mars.assembler.Token; import mars.assembler.TokenTypes;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi; public class MipsElementType extends IElementType { public MipsElementType(@NotNull String debug) { super(debug, MipsLanguage.INSTANCE); }
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.MipsLanguage; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import mars.assembler.Token; import mars.assembler.TokenTypes; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi; public class MipsElementType extends IElementType { public MipsElementType(@NotNull String debug) { super(debug, MipsLanguage.INSTANCE); }
public static IElementType fromToken(@NotNull Token token) throws MipsException {
equadon/intellij-mips
src/com/equadon/intellij/mips/template/MipsCreateFromTemplateHandler.java
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // }
import com.equadon.intellij.mips.lang.MipsFileType; import com.intellij.ide.fileTemplates.DefaultCreateFromTemplateHandler; import com.intellij.ide.fileTemplates.FileTemplate; import java.util.Map;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.template; public class MipsCreateFromTemplateHandler extends DefaultCreateFromTemplateHandler { @Override public boolean handlesTemplate(FileTemplate template) {
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // Path: src/com/equadon/intellij/mips/template/MipsCreateFromTemplateHandler.java import com.equadon.intellij.mips.lang.MipsFileType; import com.intellij.ide.fileTemplates.DefaultCreateFromTemplateHandler; import com.intellij.ide.fileTemplates.FileTemplate; import java.util.Map; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.template; public class MipsCreateFromTemplateHandler extends DefaultCreateFromTemplateHandler { @Override public boolean handlesTemplate(FileTemplate template) {
return template.isTemplateOfType(MipsFileType.INSTANCE);
equadon/intellij-mips
src/com/equadon/intellij/mips/run/MipsRunConfigurationProducer.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // }
import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import java.util.Iterator; import static com.intellij.execution.configurations.ConfigurationType.CONFIGURATION_TYPE_EP;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run; public class MipsRunConfigurationProducer extends RunConfigurationProducer<MipsRunConfiguration> { protected MipsRunConfigurationProducer() { super(Extensions.findExtension(CONFIGURATION_TYPE_EP, MipsRunConfigurationType.class)); } @Override protected boolean setupConfigurationFromContext(MipsRunConfiguration cfg, ConfigurationContext context, Ref<PsiElement> ref) { PsiElement psiElement = ref.get(); if (psiElement == null || !psiElement.isValid()) { return false; } PsiFile file = psiElement.getContainingFile();
// Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // Path: src/com/equadon/intellij/mips/run/MipsRunConfigurationProducer.java import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.execution.actions.ConfigurationContext; import com.intellij.execution.actions.RunConfigurationProducer; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.util.Ref; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import java.util.Iterator; import static com.intellij.execution.configurations.ConfigurationType.CONFIGURATION_TYPE_EP; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run; public class MipsRunConfigurationProducer extends RunConfigurationProducer<MipsRunConfiguration> { protected MipsRunConfigurationProducer() { super(Extensions.findExtension(CONFIGURATION_TYPE_EP, MipsRunConfigurationType.class)); } @Override protected boolean setupConfigurationFromContext(MipsRunConfiguration cfg, ConfigurationContext context, Ref<PsiElement> ref) { PsiElement psiElement = ref.get(); if (psiElement == null || !psiElement.isValid()) { return false; } PsiFile file = psiElement.getContainingFile();
if (!(file instanceof MipsFile)) {
equadon/intellij-mips
src/com/equadon/intellij/mips/run/debugger/MipsStackFrame.java
// Path: src/com/equadon/intellij/mips/run/controllers/MipsSimulatorController.java // public abstract class MipsSimulatorController { // protected final boolean debugger; // protected final MipsRunConfiguration cfg; // protected final ConsoleView console; // protected final ProcessHandler processHandler; // protected final XDebugProcess debugProcess; // protected final XDebugSession debugSession; // // protected MipsConsoleInputStream inputStream; // // protected final List<XBreakpoint> breakpoints; // // public MipsSimulatorController(MipsRunConfiguration cfg, ConsoleView console, ProcessHandler processHandler) { // this(false, cfg, console, processHandler, null, null); // } // // public MipsSimulatorController(MipsRunConfiguration cfg, ConsoleView console, XDebugProcess process, XDebugSession session) { // this(true, cfg, console, process.getProcessHandler(), process, session); // } // // public MipsSimulatorController(boolean debugger, // MipsRunConfiguration cfg, // ConsoleView console, // ProcessHandler processHandler, // XDebugProcess debugProcess, // XDebugSession debugSession) { // this.debugger = debugger; // this.cfg = cfg; // this.console = console; // this.processHandler = processHandler; // this.debugProcess = debugProcess; // this.debugSession = debugSession; // // inputStream = new MipsConsoleInputStream(cfg.getProject()); // // breakpoints = new ArrayList<>(); // // // Intercept System.out and System.in to handle output and input. // System.setOut(new MipsConsoleOutputStream(this, inputStream)); // System.setIn(inputStream); // } // // public boolean isDebugger() { // return debugger; // } // // /** // * Check if simulator has paused (at a breakpoint) // * @return true if paused // */ // public abstract boolean isPaused(); // // /** // * Check if simulator is finished (i.e. no more instructions to execute) // * @return true if finished // */ // public abstract boolean isFinished(); // // /** // * Resume simulation. // */ // public abstract void resume(); // // /** // * Pause simulation. // */ // public abstract void pause(); // // /** // * Stop simulation. // */ // public void stop() { // processHandler.destroyProcess(); // } // // /** // * Step one instruction. // */ // public abstract void step(); // // /** // * Add new breakpoint. // * @param breakpoint breakpoint to add // */ // public void addBreakpoint(XBreakpoint breakpoint) { // breakpoints.add(breakpoint); // } // // /** // * Remove breakpoint. // * @param breakpoint breakpoint to remove // */ // public void removeBreakpoint(XBreakpoint breakpoint) { // breakpoints.remove(breakpoint); // } // // public void println(String message) { // print(message + "\n"); // } // // public void print(String message) { // print(message, ConsoleViewContentType.NORMAL_OUTPUT); // } // // public void printlnSystem(String message) { // printSystem(message + "\n"); // } // // public void printSystem(String message) { // print(message, ConsoleViewContentType.SYSTEM_OUTPUT); // } // // public void printlnError(String message) { // printError(message + "\n"); // } // // public void printError(String message) { // print(message, ConsoleViewContentType.ERROR_OUTPUT); // } // // public void print(String message, ConsoleViewContentType type) { // console.print(message, type); // } // }
import com.equadon.intellij.mips.run.controllers.MipsSimulatorController; import com.intellij.openapi.project.Project; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.frame.XStackFrame; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.debugger; public class MipsStackFrame extends XStackFrame { private final Project project;
// Path: src/com/equadon/intellij/mips/run/controllers/MipsSimulatorController.java // public abstract class MipsSimulatorController { // protected final boolean debugger; // protected final MipsRunConfiguration cfg; // protected final ConsoleView console; // protected final ProcessHandler processHandler; // protected final XDebugProcess debugProcess; // protected final XDebugSession debugSession; // // protected MipsConsoleInputStream inputStream; // // protected final List<XBreakpoint> breakpoints; // // public MipsSimulatorController(MipsRunConfiguration cfg, ConsoleView console, ProcessHandler processHandler) { // this(false, cfg, console, processHandler, null, null); // } // // public MipsSimulatorController(MipsRunConfiguration cfg, ConsoleView console, XDebugProcess process, XDebugSession session) { // this(true, cfg, console, process.getProcessHandler(), process, session); // } // // public MipsSimulatorController(boolean debugger, // MipsRunConfiguration cfg, // ConsoleView console, // ProcessHandler processHandler, // XDebugProcess debugProcess, // XDebugSession debugSession) { // this.debugger = debugger; // this.cfg = cfg; // this.console = console; // this.processHandler = processHandler; // this.debugProcess = debugProcess; // this.debugSession = debugSession; // // inputStream = new MipsConsoleInputStream(cfg.getProject()); // // breakpoints = new ArrayList<>(); // // // Intercept System.out and System.in to handle output and input. // System.setOut(new MipsConsoleOutputStream(this, inputStream)); // System.setIn(inputStream); // } // // public boolean isDebugger() { // return debugger; // } // // /** // * Check if simulator has paused (at a breakpoint) // * @return true if paused // */ // public abstract boolean isPaused(); // // /** // * Check if simulator is finished (i.e. no more instructions to execute) // * @return true if finished // */ // public abstract boolean isFinished(); // // /** // * Resume simulation. // */ // public abstract void resume(); // // /** // * Pause simulation. // */ // public abstract void pause(); // // /** // * Stop simulation. // */ // public void stop() { // processHandler.destroyProcess(); // } // // /** // * Step one instruction. // */ // public abstract void step(); // // /** // * Add new breakpoint. // * @param breakpoint breakpoint to add // */ // public void addBreakpoint(XBreakpoint breakpoint) { // breakpoints.add(breakpoint); // } // // /** // * Remove breakpoint. // * @param breakpoint breakpoint to remove // */ // public void removeBreakpoint(XBreakpoint breakpoint) { // breakpoints.remove(breakpoint); // } // // public void println(String message) { // print(message + "\n"); // } // // public void print(String message) { // print(message, ConsoleViewContentType.NORMAL_OUTPUT); // } // // public void printlnSystem(String message) { // printSystem(message + "\n"); // } // // public void printSystem(String message) { // print(message, ConsoleViewContentType.SYSTEM_OUTPUT); // } // // public void printlnError(String message) { // printError(message + "\n"); // } // // public void printError(String message) { // print(message, ConsoleViewContentType.ERROR_OUTPUT); // } // // public void print(String message, ConsoleViewContentType type) { // console.print(message, type); // } // } // Path: src/com/equadon/intellij/mips/run/debugger/MipsStackFrame.java import com.equadon.intellij.mips.run.controllers.MipsSimulatorController; import com.intellij.openapi.project.Project; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.frame.XStackFrame; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.debugger; public class MipsStackFrame extends XStackFrame { private final Project project;
private final MipsSimulatorController controller;
equadon/intellij-mips
src/com/equadon/intellij/mips/MipsUtil.java
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsNamedElement.java // public interface MipsNamedElement extends MipsElement, PsiNameIdentifierOwner { // }
import java.util.List; import com.equadon.intellij.mips.lang.MipsFileType; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsNamedElement; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.indexing.FileBasedIndex; import java.util.ArrayList; import java.util.Collection; import java.util.Collections;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MipsUtil { /** * Find named elements that belong to the given project. * @param project Project that the elements belong to * @param cls Class type * @param <E> MipsNamedElement type * @return List of elements */ public static <E extends MipsNamedElement> List<E> findNamedElements(Project project, Class<E> cls) { List<E> result = new ArrayList<>(); Collection<VirtualFile> virtualFiles =
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsNamedElement.java // public interface MipsNamedElement extends MipsElement, PsiNameIdentifierOwner { // } // Path: src/com/equadon/intellij/mips/MipsUtil.java import java.util.List; import com.equadon.intellij.mips.lang.MipsFileType; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsNamedElement; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.indexing.FileBasedIndex; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MipsUtil { /** * Find named elements that belong to the given project. * @param project Project that the elements belong to * @param cls Class type * @param <E> MipsNamedElement type * @return List of elements */ public static <E extends MipsNamedElement> List<E> findNamedElements(Project project, Class<E> cls) { List<E> result = new ArrayList<>(); Collection<VirtualFile> virtualFiles =
FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, MipsFileType.INSTANCE, GlobalSearchScope.allScope(project));
equadon/intellij-mips
src/com/equadon/intellij/mips/MipsUtil.java
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsNamedElement.java // public interface MipsNamedElement extends MipsElement, PsiNameIdentifierOwner { // }
import java.util.List; import com.equadon.intellij.mips.lang.MipsFileType; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsNamedElement; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.indexing.FileBasedIndex; import java.util.ArrayList; import java.util.Collection; import java.util.Collections;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MipsUtil { /** * Find named elements that belong to the given project. * @param project Project that the elements belong to * @param cls Class type * @param <E> MipsNamedElement type * @return List of elements */ public static <E extends MipsNamedElement> List<E> findNamedElements(Project project, Class<E> cls) { List<E> result = new ArrayList<>(); Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, MipsFileType.INSTANCE, GlobalSearchScope.allScope(project)); for (VirtualFile virtualFile : virtualFiles) {
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsNamedElement.java // public interface MipsNamedElement extends MipsElement, PsiNameIdentifierOwner { // } // Path: src/com/equadon/intellij/mips/MipsUtil.java import java.util.List; import com.equadon.intellij.mips.lang.MipsFileType; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsNamedElement; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiManager; import com.intellij.psi.search.FileTypeIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.indexing.FileBasedIndex; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MipsUtil { /** * Find named elements that belong to the given project. * @param project Project that the elements belong to * @param cls Class type * @param <E> MipsNamedElement type * @return List of elements */ public static <E extends MipsNamedElement> List<E> findNamedElements(Project project, Class<E> cls) { List<E> result = new ArrayList<>(); Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, MipsFileType.INSTANCE, GlobalSearchScope.allScope(project)); for (VirtualFile virtualFile : virtualFiles) {
MipsFile file = (MipsFile) PsiManager.getInstance(project).findFile(virtualFile);
equadon/intellij-mips
src/com/equadon/intellij/mips/formatter/MipsCodeStyleConfigurable.java
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // }
import com.equadon.intellij.mips.lang.MipsLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.psi.codeStyle.CodeStyleSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.formatter; public class MipsCodeStyleConfigurable extends CodeStyleAbstractConfigurable { public MipsCodeStyleConfigurable(@NotNull CodeStyleSettings settings, CodeStyleSettings cloneSettings) { super(settings, cloneSettings, "MIPS"); } @Override protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) { return new MipsCodeStyleMainPanel(getCurrentSettings(), settings); } @Nullable @Override public String getHelpTopic() { return null; } private static class MipsCodeStyleMainPanel extends TabbedLanguageCodeStylePanel { private MipsCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // Path: src/com/equadon/intellij/mips/formatter/MipsCodeStyleConfigurable.java import com.equadon.intellij.mips.lang.MipsLanguage; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.psi.codeStyle.CodeStyleSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.formatter; public class MipsCodeStyleConfigurable extends CodeStyleAbstractConfigurable { public MipsCodeStyleConfigurable(@NotNull CodeStyleSettings settings, CodeStyleSettings cloneSettings) { super(settings, cloneSettings, "MIPS"); } @Override protected CodeStyleAbstractPanel createPanel(CodeStyleSettings settings) { return new MipsCodeStyleMainPanel(getCurrentSettings(), settings); } @Nullable @Override public String getHelpTopic() { return null; } private static class MipsCodeStyleMainPanel extends TabbedLanguageCodeStylePanel { private MipsCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
super(MipsLanguage.INSTANCE, currentSettings, settings);
equadon/intellij-mips
src/com/equadon/intellij/mips/MipsBraceMatcher.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // }
import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lang.BracePair; import com.intellij.lang.PairedBraceMatcher; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MipsBraceMatcher implements PairedBraceMatcher { private static final BracePair[] PAIRS = new BracePair[] { new BracePair(MipsElementTypes.LPAREN, MipsElementTypes.RPAREN, false), new BracePair(MipsElementTypes.LQUOTE, MipsElementTypes.RQUOTE, false) }; @Override public BracePair[] getPairs() { return PAIRS; } @Override public boolean isPairedBracesAllowedBeforeType(@NotNull IElementType lBraceType, @Nullable IElementType type) {
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // Path: src/com/equadon/intellij/mips/MipsBraceMatcher.java import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lang.BracePair; import com.intellij.lang.PairedBraceMatcher; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips; public class MipsBraceMatcher implements PairedBraceMatcher { private static final BracePair[] PAIRS = new BracePair[] { new BracePair(MipsElementTypes.LPAREN, MipsElementTypes.RPAREN, false), new BracePair(MipsElementTypes.LQUOTE, MipsElementTypes.RQUOTE, false) }; @Override public BracePair[] getPairs() { return PAIRS; } @Override public boolean isPairedBracesAllowedBeforeType(@NotNull IElementType lBraceType, @Nullable IElementType type) {
return MipsTokenTypes.WHITE_SPACES.contains(type) ||
equadon/intellij-mips
src/com/equadon/intellij/mips/completion/MipsCompletionContributor.java
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // }
import com.equadon.intellij.mips.icons.MipsIcons; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import mars.Globals; import mars.assembler.Directives; import mars.mips.instructions.Instruction; import static com.intellij.patterns.PlatformPatterns.psiElement;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.completion; public class MipsCompletionContributor extends CompletionContributor { private static final Pattern INSTRUCTION_ID = Pattern.compile("^([^\\d]+)\\d{3} $"); public MipsCompletionContributor() { // Completion for directives and instructions
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // Path: src/com/equadon/intellij/mips/completion/MipsCompletionContributor.java import com.equadon.intellij.mips.icons.MipsIcons; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import mars.Globals; import mars.assembler.Directives; import mars.mips.instructions.Instruction; import static com.intellij.patterns.PlatformPatterns.psiElement; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.completion; public class MipsCompletionContributor extends CompletionContributor { private static final Pattern INSTRUCTION_ID = Pattern.compile("^([^\\d]+)\\d{3} $"); public MipsCompletionContributor() { // Completion for directives and instructions
extend(CompletionType.BASIC, psiElement().withParent(MipsFile.class), new CompletionProvider<CompletionParameters>() {
equadon/intellij-mips
src/com/equadon/intellij/mips/completion/MipsCompletionContributor.java
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // }
import com.equadon.intellij.mips.icons.MipsIcons; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import mars.Globals; import mars.assembler.Directives; import mars.mips.instructions.Instruction; import static com.intellij.patterns.PlatformPatterns.psiElement;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.completion; public class MipsCompletionContributor extends CompletionContributor { private static final Pattern INSTRUCTION_ID = Pattern.compile("^([^\\d]+)\\d{3} $"); public MipsCompletionContributor() { // Completion for directives and instructions extend(CompletionType.BASIC, psiElement().withParent(MipsFile.class), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters params, ProcessingContext context, @NotNull CompletionResultSet result) { suggestDirectives(result); suggestInstructions(result); } }); // Completion for labels extend(CompletionType.BASIC, psiElement(), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters params, ProcessingContext context, @NotNull CompletionResultSet result) { suggestLabels(params, result); } }); } /** * Add all label definitions in current file. * TODO: Optimize using index. * TODO: Add tail text as documentation if there is a comment just above/below the label definition. * @param params Completion parameters to get the PsiFile * @param result Result set completions will be added to */ private void suggestLabels(CompletionParameters params, CompletionResultSet result) { if (params.getOriginalFile() instanceof MipsFile) { MipsFile file = (MipsFile) params.getOriginalFile(); for (MipsLabelDefinition label : file.getLabelDefinitions()) { if (label.getName() != null) { result.addElement(LookupElementBuilder.create(label.getName()) .withTypeText("Label") .withBoldness(true)
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsFile.java // public interface MipsFile extends PsiFile { // Collection<MipsLabelDefinition> getLabelDefinitions(); // } // Path: src/com/equadon/intellij/mips/completion/MipsCompletionContributor.java import com.equadon.intellij.mips.icons.MipsIcons; import com.equadon.intellij.mips.lang.psi.MipsFile; import com.equadon.intellij.mips.lang.psi.MipsLabelDefinition; import com.intellij.codeInsight.completion.CompletionContributor; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionProvider; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.completion.InsertHandler; import com.intellij.codeInsight.completion.InsertionContext; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import mars.Globals; import mars.assembler.Directives; import mars.mips.instructions.Instruction; import static com.intellij.patterns.PlatformPatterns.psiElement; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.completion; public class MipsCompletionContributor extends CompletionContributor { private static final Pattern INSTRUCTION_ID = Pattern.compile("^([^\\d]+)\\d{3} $"); public MipsCompletionContributor() { // Completion for directives and instructions extend(CompletionType.BASIC, psiElement().withParent(MipsFile.class), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters params, ProcessingContext context, @NotNull CompletionResultSet result) { suggestDirectives(result); suggestInstructions(result); } }); // Completion for labels extend(CompletionType.BASIC, psiElement(), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters params, ProcessingContext context, @NotNull CompletionResultSet result) { suggestLabels(params, result); } }); } /** * Add all label definitions in current file. * TODO: Optimize using index. * TODO: Add tail text as documentation if there is a comment just above/below the label definition. * @param params Completion parameters to get the PsiFile * @param result Result set completions will be added to */ private void suggestLabels(CompletionParameters params, CompletionResultSet result) { if (params.getOriginalFile() instanceof MipsFile) { MipsFile file = (MipsFile) params.getOriginalFile(); for (MipsLabelDefinition label : file.getLabelDefinitions()) { if (label.getName() != null) { result.addElement(LookupElementBuilder.create(label.getName()) .withTypeText("Label") .withBoldness(true)
.withIcon(MipsIcons.LABEL)
equadon/intellij-mips
src/com/equadon/intellij/mips/actions/CreateMipsFileAction.java
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // }
import com.equadon.intellij.mips.icons.MipsIcons; import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.ide.actions.CreateFileFromTemplateDialog; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.actions; public class CreateMipsFileAction extends CreateFileFromTemplateAction implements DumbAware { private static final String NEW_MIPS_FILE = "New MIPS Application"; public CreateMipsFileAction() {
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // Path: src/com/equadon/intellij/mips/actions/CreateMipsFileAction.java import com.equadon.intellij.mips.icons.MipsIcons; import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.ide.actions.CreateFileFromTemplateDialog; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.actions; public class CreateMipsFileAction extends CreateFileFromTemplateAction implements DumbAware { private static final String NEW_MIPS_FILE = "New MIPS Application"; public CreateMipsFileAction() {
super(NEW_MIPS_FILE, "", MipsIcons.FILE);
equadon/intellij-mips
src/com/equadon/intellij/mips/stubs/types/MipsFileElementType.java
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // // Path: src/com/equadon/intellij/mips/stubs/MipsFileStub.java // public class MipsFileStub extends PsiFileStubImpl<MipsFile> { // private final boolean isMainFile; // // public MipsFileStub(MipsFile file) { // super(file); // // isMainFile = true; // } // // public boolean isMainFile() { // return isMainFile; // } // }
import com.equadon.intellij.mips.lang.MipsLanguage; import com.equadon.intellij.mips.stubs.MipsFileStub; import com.intellij.psi.tree.IStubFileElementType;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.stubs.types; public class MipsFileElementType extends IStubFileElementType<MipsFileStub> { public static final IStubFileElementType INSTANCE = new MipsFileElementType(); private MipsFileElementType() {
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // // Path: src/com/equadon/intellij/mips/stubs/MipsFileStub.java // public class MipsFileStub extends PsiFileStubImpl<MipsFile> { // private final boolean isMainFile; // // public MipsFileStub(MipsFile file) { // super(file); // // isMainFile = true; // } // // public boolean isMainFile() { // return isMainFile; // } // } // Path: src/com/equadon/intellij/mips/stubs/types/MipsFileElementType.java import com.equadon.intellij.mips.lang.MipsLanguage; import com.equadon.intellij.mips.stubs.MipsFileStub; import com.intellij.psi.tree.IStubFileElementType; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.stubs.types; public class MipsFileElementType extends IStubFileElementType<MipsFileStub> { public static final IStubFileElementType INSTANCE = new MipsFileElementType(); private MipsFileElementType() {
super("MIPS_FILE", MipsLanguage.INSTANCE);
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/psi/mixins/MipsLabelDefinitionMixin.java
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // // Path: src/com/equadon/intellij/mips/lang/psi/impl/MipsNamedElementImpl.java // public class MipsNamedElementImpl extends MipsElementImpl implements MipsNamedElement { // public MipsNamedElementImpl(@NotNull ASTNode node) { // super(node); // } // // @Override // public String getName() { // PsiElement element = getNameIdentifier(); // if (element != null) // return getValue(element); // // return null; // } // // @Nullable // @Override // public PsiElement getNameIdentifier() { // return getFirstChild(); // } // // @Override // public PsiElement setName(@NotNull String name) throws IncorrectOperationException { // return null; // } // // public static String getValue(PsiElement element) { // return element.getText(); // } // }
import com.equadon.intellij.mips.icons.MipsIcons; import com.equadon.intellij.mips.lang.psi.impl.MipsNamedElementImpl; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.psi.NavigatablePsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*;
@Override public boolean canNavigate() { return true; } @Override public boolean canNavigateToSource() { return true; } @Override public ItemPresentation getPresentation() { return new ItemPresentation() { @Nullable @Override public String getPresentableText() { return getName(); } @Nullable @Override public String getLocationString() { PsiFile file = getContainingFile(); return (file == null) ? "(unknown)" : "(" + file.getName() + ")"; } @Nullable @Override public Icon getIcon(boolean unused) {
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // // Path: src/com/equadon/intellij/mips/lang/psi/impl/MipsNamedElementImpl.java // public class MipsNamedElementImpl extends MipsElementImpl implements MipsNamedElement { // public MipsNamedElementImpl(@NotNull ASTNode node) { // super(node); // } // // @Override // public String getName() { // PsiElement element = getNameIdentifier(); // if (element != null) // return getValue(element); // // return null; // } // // @Nullable // @Override // public PsiElement getNameIdentifier() { // return getFirstChild(); // } // // @Override // public PsiElement setName(@NotNull String name) throws IncorrectOperationException { // return null; // } // // public static String getValue(PsiElement element) { // return element.getText(); // } // } // Path: src/com/equadon/intellij/mips/lang/psi/mixins/MipsLabelDefinitionMixin.java import com.equadon.intellij.mips.icons.MipsIcons; import com.equadon.intellij.mips.lang.psi.impl.MipsNamedElementImpl; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.psi.NavigatablePsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; @Override public boolean canNavigate() { return true; } @Override public boolean canNavigateToSource() { return true; } @Override public ItemPresentation getPresentation() { return new ItemPresentation() { @Nullable @Override public String getPresentableText() { return getName(); } @Nullable @Override public String getLocationString() { PsiFile file = getContainingFile(); return (file == null) ? "(unknown)" : "(" + file.getName() + ")"; } @Nullable @Override public Icon getIcon(boolean unused) {
return MipsIcons.LABEL;
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/psi/mixins/MipsRegisterLiteralMixin.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // // Path: src/com/equadon/intellij/mips/lang/psi/impl/MipsNamedElementImpl.java // public class MipsNamedElementImpl extends MipsElementImpl implements MipsNamedElement { // public MipsNamedElementImpl(@NotNull ASTNode node) { // super(node); // } // // @Override // public String getName() { // PsiElement element = getNameIdentifier(); // if (element != null) // return getValue(element); // // return null; // } // // @Nullable // @Override // public PsiElement getNameIdentifier() { // return getFirstChild(); // } // // @Override // public PsiElement setName(@NotNull String name) throws IncorrectOperationException { // return null; // } // // public static String getValue(PsiElement element) { // return element.getText(); // } // }
import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.equadon.intellij.mips.lang.psi.impl.MipsNamedElementImpl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi.mixins; public class MipsRegisterLiteralMixin extends MipsNamedElementImpl { public MipsRegisterLiteralMixin(@NotNull ASTNode node) { super(node); } @Nullable @Override public PsiElement getNameIdentifier() {
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // // Path: src/com/equadon/intellij/mips/lang/psi/impl/MipsNamedElementImpl.java // public class MipsNamedElementImpl extends MipsElementImpl implements MipsNamedElement { // public MipsNamedElementImpl(@NotNull ASTNode node) { // super(node); // } // // @Override // public String getName() { // PsiElement element = getNameIdentifier(); // if (element != null) // return getValue(element); // // return null; // } // // @Nullable // @Override // public PsiElement getNameIdentifier() { // return getFirstChild(); // } // // @Override // public PsiElement setName(@NotNull String name) throws IncorrectOperationException { // return null; // } // // public static String getValue(PsiElement element) { // return element.getText(); // } // } // Path: src/com/equadon/intellij/mips/lang/psi/mixins/MipsRegisterLiteralMixin.java import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.equadon.intellij.mips.lang.psi.impl.MipsNamedElementImpl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.psi.mixins; public class MipsRegisterLiteralMixin extends MipsNamedElementImpl { public MipsRegisterLiteralMixin(@NotNull ASTNode node) { super(node); } @Nullable @Override public PsiElement getNameIdentifier() {
return findChildByType(MipsTokenTypes.REGISTERS);
equadon/intellij-mips
src/com/equadon/intellij/mips/editor/MipsSyntaxHighlighter.java
// Path: src/com/equadon/intellij/mips/lang/lexer/MipsLexerAdapter.java // public class MipsLexerAdapter extends LookAheadLexer { // public MipsLexerAdapter() { // super(new MergingLexerAdapter(new FlexAdapter(new __MipsLexer()), MipsTokenTypes.COMMENTS)); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // }
import com.equadon.intellij.mips.lang.lexer.MipsLexerAdapter; import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.editor; public class MipsSyntaxHighlighter extends SyntaxHighlighterBase { public static final TextAttributesKey ERROR = TextAttributesKey.createTextAttributesKey("MIPS_ERROR", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE); public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey("MIPS_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("MIPS_OPERATOR", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey DIRECTIVE = TextAttributesKey.createTextAttributesKey("MIPS_DIRECTIVE", DefaultLanguageHighlighterColors.STATIC_FIELD); public static final TextAttributesKey LABEL = TextAttributesKey.createTextAttributesKey("MIPS_LABEL", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey MAIN_LABEL = TextAttributesKey.createTextAttributesKey("MIPS_MAIN_LABEL", DefaultLanguageHighlighterColors.STATIC_METHOD); public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey("MIPS_STRING", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("MIPS_NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey REGISTER = TextAttributesKey.createTextAttributesKey("MIPS_REGISTER", DefaultLanguageHighlighterColors.INSTANCE_FIELD); @NotNull @Override public Lexer getHighlightingLexer() {
// Path: src/com/equadon/intellij/mips/lang/lexer/MipsLexerAdapter.java // public class MipsLexerAdapter extends LookAheadLexer { // public MipsLexerAdapter() { // super(new MergingLexerAdapter(new FlexAdapter(new __MipsLexer()), MipsTokenTypes.COMMENTS)); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // Path: src/com/equadon/intellij/mips/editor/MipsSyntaxHighlighter.java import com.equadon.intellij.mips.lang.lexer.MipsLexerAdapter; import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.editor; public class MipsSyntaxHighlighter extends SyntaxHighlighterBase { public static final TextAttributesKey ERROR = TextAttributesKey.createTextAttributesKey("MIPS_ERROR", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE); public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey("MIPS_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("MIPS_OPERATOR", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey DIRECTIVE = TextAttributesKey.createTextAttributesKey("MIPS_DIRECTIVE", DefaultLanguageHighlighterColors.STATIC_FIELD); public static final TextAttributesKey LABEL = TextAttributesKey.createTextAttributesKey("MIPS_LABEL", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey MAIN_LABEL = TextAttributesKey.createTextAttributesKey("MIPS_MAIN_LABEL", DefaultLanguageHighlighterColors.STATIC_METHOD); public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey("MIPS_STRING", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("MIPS_NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey REGISTER = TextAttributesKey.createTextAttributesKey("MIPS_REGISTER", DefaultLanguageHighlighterColors.INSTANCE_FIELD); @NotNull @Override public Lexer getHighlightingLexer() {
return new MipsLexerAdapter();
equadon/intellij-mips
src/com/equadon/intellij/mips/editor/MipsSyntaxHighlighter.java
// Path: src/com/equadon/intellij/mips/lang/lexer/MipsLexerAdapter.java // public class MipsLexerAdapter extends LookAheadLexer { // public MipsLexerAdapter() { // super(new MergingLexerAdapter(new FlexAdapter(new __MipsLexer()), MipsTokenTypes.COMMENTS)); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // }
import com.equadon.intellij.mips.lang.lexer.MipsLexerAdapter; import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.editor; public class MipsSyntaxHighlighter extends SyntaxHighlighterBase { public static final TextAttributesKey ERROR = TextAttributesKey.createTextAttributesKey("MIPS_ERROR", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE); public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey("MIPS_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("MIPS_OPERATOR", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey DIRECTIVE = TextAttributesKey.createTextAttributesKey("MIPS_DIRECTIVE", DefaultLanguageHighlighterColors.STATIC_FIELD); public static final TextAttributesKey LABEL = TextAttributesKey.createTextAttributesKey("MIPS_LABEL", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey MAIN_LABEL = TextAttributesKey.createTextAttributesKey("MIPS_MAIN_LABEL", DefaultLanguageHighlighterColors.STATIC_METHOD); public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey("MIPS_STRING", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("MIPS_NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey REGISTER = TextAttributesKey.createTextAttributesKey("MIPS_REGISTER", DefaultLanguageHighlighterColors.INSTANCE_FIELD); @NotNull @Override public Lexer getHighlightingLexer() { return new MipsLexerAdapter(); } @NotNull @Override public TextAttributesKey[] getTokenHighlights(IElementType type) { if (type == TokenType.BAD_CHARACTER) return pack(ERROR);
// Path: src/com/equadon/intellij/mips/lang/lexer/MipsLexerAdapter.java // public class MipsLexerAdapter extends LookAheadLexer { // public MipsLexerAdapter() { // super(new MergingLexerAdapter(new FlexAdapter(new __MipsLexer()), MipsTokenTypes.COMMENTS)); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // Path: src/com/equadon/intellij/mips/editor/MipsSyntaxHighlighter.java import com.equadon.intellij.mips.lang.lexer.MipsLexerAdapter; import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lexer.Lexer; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighterBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.editor; public class MipsSyntaxHighlighter extends SyntaxHighlighterBase { public static final TextAttributesKey ERROR = TextAttributesKey.createTextAttributesKey("MIPS_ERROR", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE); public static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey("MIPS_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT); public static final TextAttributesKey OPERATOR = TextAttributesKey.createTextAttributesKey("MIPS_OPERATOR", DefaultLanguageHighlighterColors.KEYWORD); public static final TextAttributesKey DIRECTIVE = TextAttributesKey.createTextAttributesKey("MIPS_DIRECTIVE", DefaultLanguageHighlighterColors.STATIC_FIELD); public static final TextAttributesKey LABEL = TextAttributesKey.createTextAttributesKey("MIPS_LABEL", DefaultLanguageHighlighterColors.IDENTIFIER); public static final TextAttributesKey MAIN_LABEL = TextAttributesKey.createTextAttributesKey("MIPS_MAIN_LABEL", DefaultLanguageHighlighterColors.STATIC_METHOD); public static final TextAttributesKey STRING = TextAttributesKey.createTextAttributesKey("MIPS_STRING", DefaultLanguageHighlighterColors.STRING); public static final TextAttributesKey NUMBER = TextAttributesKey.createTextAttributesKey("MIPS_NUMBER", DefaultLanguageHighlighterColors.NUMBER); public static final TextAttributesKey REGISTER = TextAttributesKey.createTextAttributesKey("MIPS_REGISTER", DefaultLanguageHighlighterColors.INSTANCE_FIELD); @NotNull @Override public Lexer getHighlightingLexer() { return new MipsLexerAdapter(); } @NotNull @Override public TextAttributesKey[] getTokenHighlights(IElementType type) { if (type == TokenType.BAD_CHARACTER) return pack(ERROR);
if (MipsTokenTypes.COMMENTS.contains(type))
equadon/intellij-mips
src/com/equadon/intellij/mips/mars/lexer/MipsLexer.java
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java // public class MipsElementType extends IElementType { // public MipsElementType(@NotNull String debug) { // super(debug, MipsLanguage.INSTANCE); // } // // public static IElementType fromToken(@NotNull Token token) throws MipsException { // TokenTypes type = token.getType(); // // if (type.equals(TokenTypes.COLON)) // return MipsElementTypes.COLON; // if (type.equals(TokenTypes.COMMENT)) // return MipsTokenTypes.COMMENT; // if (type.equals(TokenTypes.DELIMITER)) // return TokenType.WHITE_SPACE; // if (type.equals(TokenTypes.DIRECTIVE)) // return MipsElementTypes.DIRECTIVE; // // if (type.equals(TokenTypes.EOL)) // // return MipsElementTypes.EOL; // if (type.equals(TokenTypes.ERROR)) // return TokenType.BAD_CHARACTER; // if (type.equals(TokenTypes.IDENTIFIER)) // return MipsElementTypes.IDENTIFIER; // if (type.equals(TokenTypes.INTEGER_5)) // return MipsElementTypes.INTEGER_5; // if (type.equals(TokenTypes.INTEGER_16)) // return MipsElementTypes.INTEGER_16; // if (type.equals(TokenTypes.INTEGER_16U)) // return MipsElementTypes.INTEGER_16U; // if (type.equals(TokenTypes.INTEGER_32)) // return MipsElementTypes.INTEGER_32; // if (type.equals(TokenTypes.LEFT_PAREN)) // return MipsElementTypes.LPAREN; // if (type.equals(TokenTypes.MINUS)) // return MipsElementTypes.MINUS; // if (type.equals(TokenTypes.OPERATOR)) // return MipsElementTypes.OPERATOR; // if (type.equals(TokenTypes.PLUS)) // return MipsElementTypes.PLUS; // if (type.equals(TokenTypes.QUOTED_STRING)) // return MipsElementTypes.QUOTED_STRING; // if (type.equals(TokenTypes.REAL_NUMBER)) // return MipsElementTypes.REAL_NUMBER; // if (type.equals(TokenTypes.REGISTER_NAME)) // return MipsElementTypes.REGISTER_NAME; // if (type.equals(TokenTypes.REGISTER_NUMBER)) // return MipsElementTypes.REGISTER_NUMBER; // if (type.equals(TokenTypes.RIGHT_PAREN)) // return MipsElementTypes.RPAREN; // // throw new MipsException("Unknown token type: " + type); // } // }
import mars.ErrorList; import mars.ErrorMessage; import mars.ProcessingException; import mars.assembler.SourceLine; import mars.assembler.Token; import mars.assembler.TokenList; import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.psi.MipsElementType; import com.equadon.intellij.mips.mars.old.MipsProgram; import com.intellij.lexer.LexerBase; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List;
if (tokenType == null && !eof) advance(); return tokenType; } @Override public int getTokenStart() { return tokenStart; } @Override public int getTokenEnd() { return tokenEnd; } @Override public void advance() { if (tokenStart >= bufferEnd || tokens.isEmpty()) { // System.out.println("LEXER: end of file"); tokenType = null; tokenStart = bufferEnd; tokenEnd = bufferEnd; prevIndex = bufferEnd; eof = true; return; } Token token = tokens.pop(); try {
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java // public class MipsElementType extends IElementType { // public MipsElementType(@NotNull String debug) { // super(debug, MipsLanguage.INSTANCE); // } // // public static IElementType fromToken(@NotNull Token token) throws MipsException { // TokenTypes type = token.getType(); // // if (type.equals(TokenTypes.COLON)) // return MipsElementTypes.COLON; // if (type.equals(TokenTypes.COMMENT)) // return MipsTokenTypes.COMMENT; // if (type.equals(TokenTypes.DELIMITER)) // return TokenType.WHITE_SPACE; // if (type.equals(TokenTypes.DIRECTIVE)) // return MipsElementTypes.DIRECTIVE; // // if (type.equals(TokenTypes.EOL)) // // return MipsElementTypes.EOL; // if (type.equals(TokenTypes.ERROR)) // return TokenType.BAD_CHARACTER; // if (type.equals(TokenTypes.IDENTIFIER)) // return MipsElementTypes.IDENTIFIER; // if (type.equals(TokenTypes.INTEGER_5)) // return MipsElementTypes.INTEGER_5; // if (type.equals(TokenTypes.INTEGER_16)) // return MipsElementTypes.INTEGER_16; // if (type.equals(TokenTypes.INTEGER_16U)) // return MipsElementTypes.INTEGER_16U; // if (type.equals(TokenTypes.INTEGER_32)) // return MipsElementTypes.INTEGER_32; // if (type.equals(TokenTypes.LEFT_PAREN)) // return MipsElementTypes.LPAREN; // if (type.equals(TokenTypes.MINUS)) // return MipsElementTypes.MINUS; // if (type.equals(TokenTypes.OPERATOR)) // return MipsElementTypes.OPERATOR; // if (type.equals(TokenTypes.PLUS)) // return MipsElementTypes.PLUS; // if (type.equals(TokenTypes.QUOTED_STRING)) // return MipsElementTypes.QUOTED_STRING; // if (type.equals(TokenTypes.REAL_NUMBER)) // return MipsElementTypes.REAL_NUMBER; // if (type.equals(TokenTypes.REGISTER_NAME)) // return MipsElementTypes.REGISTER_NAME; // if (type.equals(TokenTypes.REGISTER_NUMBER)) // return MipsElementTypes.REGISTER_NUMBER; // if (type.equals(TokenTypes.RIGHT_PAREN)) // return MipsElementTypes.RPAREN; // // throw new MipsException("Unknown token type: " + type); // } // } // Path: src/com/equadon/intellij/mips/mars/lexer/MipsLexer.java import mars.ErrorList; import mars.ErrorMessage; import mars.ProcessingException; import mars.assembler.SourceLine; import mars.assembler.Token; import mars.assembler.TokenList; import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.psi.MipsElementType; import com.equadon.intellij.mips.mars.old.MipsProgram; import com.intellij.lexer.LexerBase; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; if (tokenType == null && !eof) advance(); return tokenType; } @Override public int getTokenStart() { return tokenStart; } @Override public int getTokenEnd() { return tokenEnd; } @Override public void advance() { if (tokenStart >= bufferEnd || tokens.isEmpty()) { // System.out.println("LEXER: end of file"); tokenType = null; tokenStart = bufferEnd; tokenEnd = bufferEnd; prevIndex = bufferEnd; eof = true; return; } Token token = tokens.pop(); try {
tokenType = MipsElementType.fromToken(token);
equadon/intellij-mips
src/com/equadon/intellij/mips/mars/lexer/MipsLexer.java
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java // public class MipsElementType extends IElementType { // public MipsElementType(@NotNull String debug) { // super(debug, MipsLanguage.INSTANCE); // } // // public static IElementType fromToken(@NotNull Token token) throws MipsException { // TokenTypes type = token.getType(); // // if (type.equals(TokenTypes.COLON)) // return MipsElementTypes.COLON; // if (type.equals(TokenTypes.COMMENT)) // return MipsTokenTypes.COMMENT; // if (type.equals(TokenTypes.DELIMITER)) // return TokenType.WHITE_SPACE; // if (type.equals(TokenTypes.DIRECTIVE)) // return MipsElementTypes.DIRECTIVE; // // if (type.equals(TokenTypes.EOL)) // // return MipsElementTypes.EOL; // if (type.equals(TokenTypes.ERROR)) // return TokenType.BAD_CHARACTER; // if (type.equals(TokenTypes.IDENTIFIER)) // return MipsElementTypes.IDENTIFIER; // if (type.equals(TokenTypes.INTEGER_5)) // return MipsElementTypes.INTEGER_5; // if (type.equals(TokenTypes.INTEGER_16)) // return MipsElementTypes.INTEGER_16; // if (type.equals(TokenTypes.INTEGER_16U)) // return MipsElementTypes.INTEGER_16U; // if (type.equals(TokenTypes.INTEGER_32)) // return MipsElementTypes.INTEGER_32; // if (type.equals(TokenTypes.LEFT_PAREN)) // return MipsElementTypes.LPAREN; // if (type.equals(TokenTypes.MINUS)) // return MipsElementTypes.MINUS; // if (type.equals(TokenTypes.OPERATOR)) // return MipsElementTypes.OPERATOR; // if (type.equals(TokenTypes.PLUS)) // return MipsElementTypes.PLUS; // if (type.equals(TokenTypes.QUOTED_STRING)) // return MipsElementTypes.QUOTED_STRING; // if (type.equals(TokenTypes.REAL_NUMBER)) // return MipsElementTypes.REAL_NUMBER; // if (type.equals(TokenTypes.REGISTER_NAME)) // return MipsElementTypes.REGISTER_NAME; // if (type.equals(TokenTypes.REGISTER_NUMBER)) // return MipsElementTypes.REGISTER_NUMBER; // if (type.equals(TokenTypes.RIGHT_PAREN)) // return MipsElementTypes.RPAREN; // // throw new MipsException("Unknown token type: " + type); // } // }
import mars.ErrorList; import mars.ErrorMessage; import mars.ProcessingException; import mars.assembler.SourceLine; import mars.assembler.Token; import mars.assembler.TokenList; import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.psi.MipsElementType; import com.equadon.intellij.mips.mars.old.MipsProgram; import com.intellij.lexer.LexerBase; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List;
@Override public void advance() { if (tokenStart >= bufferEnd || tokens.isEmpty()) { // System.out.println("LEXER: end of file"); tokenType = null; tokenStart = bufferEnd; tokenEnd = bufferEnd; prevIndex = bufferEnd; eof = true; return; } Token token = tokens.pop(); try { tokenType = MipsElementType.fromToken(token); tokenStart = lineIndexes.get(token.getOriginalSourceLine() - 1) + token.getStartPos() - 1; String value = token.getValue(); tokenEnd = tokenStart + value.length(); // System.out.println("LEXER: Token: " + tokenType + " (index=" + (tokenStart == tokenEnd ? tokenStart : tokenStart + ".." + tokenEnd) + "): \"" + buffer.subSequence(tokenStart, tokenEnd).toString().replace("\n", "\\n").replace("\t", "\\t") + "\""); if (prevIndex != tokenStart) { System.out.println("WARNING: gap found at " + prevIndex); throw new RuntimeException("gap at " + prevIndex + " to " + tokenStart); } prevIndex = tokenEnd;
// Path: src/com/equadon/intellij/mips/MipsException.java // public class MipsException extends Exception { // public MipsException(String text) { // super(text); // } // } // // Path: src/com/equadon/intellij/mips/lang/psi/MipsElementType.java // public class MipsElementType extends IElementType { // public MipsElementType(@NotNull String debug) { // super(debug, MipsLanguage.INSTANCE); // } // // public static IElementType fromToken(@NotNull Token token) throws MipsException { // TokenTypes type = token.getType(); // // if (type.equals(TokenTypes.COLON)) // return MipsElementTypes.COLON; // if (type.equals(TokenTypes.COMMENT)) // return MipsTokenTypes.COMMENT; // if (type.equals(TokenTypes.DELIMITER)) // return TokenType.WHITE_SPACE; // if (type.equals(TokenTypes.DIRECTIVE)) // return MipsElementTypes.DIRECTIVE; // // if (type.equals(TokenTypes.EOL)) // // return MipsElementTypes.EOL; // if (type.equals(TokenTypes.ERROR)) // return TokenType.BAD_CHARACTER; // if (type.equals(TokenTypes.IDENTIFIER)) // return MipsElementTypes.IDENTIFIER; // if (type.equals(TokenTypes.INTEGER_5)) // return MipsElementTypes.INTEGER_5; // if (type.equals(TokenTypes.INTEGER_16)) // return MipsElementTypes.INTEGER_16; // if (type.equals(TokenTypes.INTEGER_16U)) // return MipsElementTypes.INTEGER_16U; // if (type.equals(TokenTypes.INTEGER_32)) // return MipsElementTypes.INTEGER_32; // if (type.equals(TokenTypes.LEFT_PAREN)) // return MipsElementTypes.LPAREN; // if (type.equals(TokenTypes.MINUS)) // return MipsElementTypes.MINUS; // if (type.equals(TokenTypes.OPERATOR)) // return MipsElementTypes.OPERATOR; // if (type.equals(TokenTypes.PLUS)) // return MipsElementTypes.PLUS; // if (type.equals(TokenTypes.QUOTED_STRING)) // return MipsElementTypes.QUOTED_STRING; // if (type.equals(TokenTypes.REAL_NUMBER)) // return MipsElementTypes.REAL_NUMBER; // if (type.equals(TokenTypes.REGISTER_NAME)) // return MipsElementTypes.REGISTER_NAME; // if (type.equals(TokenTypes.REGISTER_NUMBER)) // return MipsElementTypes.REGISTER_NUMBER; // if (type.equals(TokenTypes.RIGHT_PAREN)) // return MipsElementTypes.RPAREN; // // throw new MipsException("Unknown token type: " + type); // } // } // Path: src/com/equadon/intellij/mips/mars/lexer/MipsLexer.java import mars.ErrorList; import mars.ErrorMessage; import mars.ProcessingException; import mars.assembler.SourceLine; import mars.assembler.Token; import mars.assembler.TokenList; import com.equadon.intellij.mips.MipsException; import com.equadon.intellij.mips.lang.psi.MipsElementType; import com.equadon.intellij.mips.mars.old.MipsProgram; import com.intellij.lexer.LexerBase; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; @Override public void advance() { if (tokenStart >= bufferEnd || tokens.isEmpty()) { // System.out.println("LEXER: end of file"); tokenType = null; tokenStart = bufferEnd; tokenEnd = bufferEnd; prevIndex = bufferEnd; eof = true; return; } Token token = tokens.pop(); try { tokenType = MipsElementType.fromToken(token); tokenStart = lineIndexes.get(token.getOriginalSourceLine() - 1) + token.getStartPos() - 1; String value = token.getValue(); tokenEnd = tokenStart + value.length(); // System.out.println("LEXER: Token: " + tokenType + " (index=" + (tokenStart == tokenEnd ? tokenStart : tokenStart + ".." + tokenEnd) + "): \"" + buffer.subSequence(tokenStart, tokenEnd).toString().replace("\n", "\\n").replace("\t", "\\t") + "\""); if (prevIndex != tokenStart) { System.out.println("WARNING: gap found at " + prevIndex); throw new RuntimeException("gap at " + prevIndex + " to " + tokenStart); } prevIndex = tokenEnd;
} catch (MipsException e) {
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/MipsFileType.java
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // }
import com.equadon.intellij.mips.icons.MipsIcons; import com.intellij.openapi.fileTypes.LanguageFileType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang; public class MipsFileType extends LanguageFileType { public static final MipsFileType INSTANCE = new MipsFileType(); public static final String DEFAULT_EXTENSION = "s"; private MipsFileType() { super(MipsLanguage.INSTANCE); } @NotNull @Override public String getName() { return MipsLanguage.NAME; } @NotNull @Override public String getDescription() { return "MIPS File"; } @NotNull @Override public String getDefaultExtension() { return DEFAULT_EXTENSION; } @Nullable @Override public Icon getIcon() {
// Path: src/com/equadon/intellij/mips/icons/MipsIcons.java // public interface MipsIcons { // Icon FILE = IconLoader.getIcon("/icons/mips-file-16.png"); // Icon LABEL = IconLoader.getIcon("/icons/mips-label-16.png"); // Icon DIRECTIVE = IconLoader.getIcon("/icons/mips-directive-16.png"); // Icon INSTRUCTION = IconLoader.getIcon("/icons/mips-instruction-16.png"); // } // Path: src/com/equadon/intellij/mips/lang/MipsFileType.java import com.equadon.intellij.mips.icons.MipsIcons; import com.intellij.openapi.fileTypes.LanguageFileType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang; public class MipsFileType extends LanguageFileType { public static final MipsFileType INSTANCE = new MipsFileType(); public static final String DEFAULT_EXTENSION = "s"; private MipsFileType() { super(MipsLanguage.INSTANCE); } @NotNull @Override public String getName() { return MipsLanguage.NAME; } @NotNull @Override public String getDescription() { return "MIPS File"; } @NotNull @Override public String getDefaultExtension() { return DEFAULT_EXTENSION; } @Nullable @Override public Icon getIcon() {
return MipsIcons.FILE;
equadon/intellij-mips
src/com/equadon/intellij/mips/formatter/MipsFormattingModelBuilder.java
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.equadon.intellij.mips.lang.MipsLanguage; import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.intellij.formatting.FormattingModel; import com.intellij.formatting.FormattingModelBuilder; import com.intellij.formatting.FormattingModelProvider; import com.intellij.formatting.SpacingBuilder; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.tree.TokenSet;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.formatter; public class MipsFormattingModelBuilder implements FormattingModelBuilder { @NotNull @Override public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
// Path: src/com/equadon/intellij/mips/lang/MipsLanguage.java // public class MipsLanguage extends Language { // public static final MipsLanguage INSTANCE = new MipsLanguage(); // // public static final String NAME = "MIPS"; // // private MipsLanguage() { // super(NAME); // // Globals.initialize(false); // Globals.program = new MIPSprogram(); // } // // @NotNull // @Override // public String getDisplayName() { // return NAME; // } // } // Path: src/com/equadon/intellij/mips/formatter/MipsFormattingModelBuilder.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import com.equadon.intellij.mips.lang.MipsLanguage; import com.equadon.intellij.mips.lang.psi.MipsElementTypes; import com.intellij.formatting.FormattingModel; import com.intellij.formatting.FormattingModelBuilder; import com.intellij.formatting.FormattingModelProvider; import com.intellij.formatting.SpacingBuilder; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.tree.TokenSet; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.formatter; public class MipsFormattingModelBuilder implements FormattingModelBuilder { @NotNull @Override public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {
CommonCodeStyleSettings commonSettings = settings.getCommonSettings(MipsLanguage.INSTANCE);
equadon/intellij-mips
src/com/equadon/intellij/mips/lang/lexer/MipsLexerAdapter.java
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // }
import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lexer.FlexAdapter; import com.intellij.lexer.LookAheadLexer; import com.intellij.lexer.MergingLexerAdapter;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.lexer; public class MipsLexerAdapter extends LookAheadLexer { public MipsLexerAdapter() {
// Path: src/com/equadon/intellij/mips/lang/psi/MipsTokenTypes.java // public class MipsTokenTypes { // public static final IElementType COMMENT = new MipsElementType("COMMENT"); // // public static final IElementType TAB = new MipsElementType("TAB"); // // /** Token sets */ // public static final TokenSet WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE, TAB); // public static final TokenSet COMMENTS = TokenSet.create(COMMENT); // public static final TokenSet STRINGS = TokenSet.create(LQUOTE, QUOTED_STRING, RQUOTE); // // public static final TokenSet NUMBERS = TokenSet.create(INTEGER_5, INTEGER_16, INTEGER_16U, REAL_NUMBER); // public static final TokenSet REGISTERS = TokenSet.create(REGISTER_NAME, REGISTER_NUMBER); // } // Path: src/com/equadon/intellij/mips/lang/lexer/MipsLexerAdapter.java import com.equadon.intellij.mips.lang.psi.MipsTokenTypes; import com.intellij.lexer.FlexAdapter; import com.intellij.lexer.LookAheadLexer; import com.intellij.lexer.MergingLexerAdapter; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.lang.lexer; public class MipsLexerAdapter extends LookAheadLexer { public MipsLexerAdapter() {
super(new MergingLexerAdapter(new FlexAdapter(new __MipsLexer()), MipsTokenTypes.COMMENTS));
equadon/intellij-mips
src/com/equadon/intellij/mips/run/debugger/MipsDebuggerEditorsProvider.java
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // }
import com.equadon.intellij.mips.lang.MipsFileType; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.EvaluationMode; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
/* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.debugger; public class MipsDebuggerEditorsProvider extends XDebuggerEditorsProvider { @NotNull @Override public FileType getFileType() {
// Path: src/com/equadon/intellij/mips/lang/MipsFileType.java // public class MipsFileType extends LanguageFileType { // public static final MipsFileType INSTANCE = new MipsFileType(); // // public static final String DEFAULT_EXTENSION = "s"; // // private MipsFileType() { // super(MipsLanguage.INSTANCE); // } // // @NotNull // @Override // public String getName() { // return MipsLanguage.NAME; // } // // @NotNull // @Override // public String getDescription() { // return "MIPS File"; // } // // @NotNull // @Override // public String getDefaultExtension() { // return DEFAULT_EXTENSION; // } // // @Nullable // @Override // public Icon getIcon() { // return MipsIcons.FILE; // } // } // Path: src/com/equadon/intellij/mips/run/debugger/MipsDebuggerEditorsProvider.java import com.equadon.intellij.mips.lang.MipsFileType; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.evaluation.EvaluationMode; import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Copyright 2017 Niklas Persson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.equadon.intellij.mips.run.debugger; public class MipsDebuggerEditorsProvider extends XDebuggerEditorsProvider { @NotNull @Override public FileType getFileType() {
return MipsFileType.INSTANCE;
apache/mrunit
src/main/java/org/apache/hadoop/mrunit/MapReduceDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mrunit.types.Pair; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.RawComparator;
public MapReduceDriver<K1, V1, K2, V2, K3, V3> withCombiner( Reducer<K2, V2, K2, V2> c) { setCombiner(c); return this; } /** * @return the Combiner object being used for this test */ public Reducer<K2, V2, K2, V2> getCombiner() { return myCombiner; } /** * Identical to addInput() but returns self for fluent programming style * @param key * @param val * @return this */ public MapReduceDriver<K1, V1, K2, V2, K3, V3> withInput(K1 key, V1 val) { addInput(key, val); return this; } /** * Identical to addInput() but returns self for fluent programming style * @param input The (k, v) pair to add * @return this */ public MapReduceDriver<K1, V1, K2, V2, K3, V3> withInput(
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/main/java/org/apache/hadoop/mrunit/MapReduceDriver.java import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mrunit.types.Pair; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.RawComparator; public MapReduceDriver<K1, V1, K2, V2, K3, V3> withCombiner( Reducer<K2, V2, K2, V2> c) { setCombiner(c); return this; } /** * @return the Combiner object being used for this test */ public Reducer<K2, V2, K2, V2> getCombiner() { return myCombiner; } /** * Identical to addInput() but returns self for fluent programming style * @param key * @param val * @return this */ public MapReduceDriver<K1, V1, K2, V2, K3, V3> withInput(K1 key, V1 val) { addInput(key, val); return this; } /** * Identical to addInput() but returns self for fluent programming style * @param input The (k, v) pair to add * @return this */ public MapReduceDriver<K1, V1, K2, V2, K3, V3> withInput(
Pair<K1, V1> input) {
apache/mrunit
src/test/java/org/apache/hadoop/mrunit/TestTestDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Test;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; public class TestTestDriver extends TestCase { /** * Test method for * {@link org.apache.hadoop.mrunit.TestDriver#parseTabbedPair(java.lang.String)}. */ @Test public void testParseTabbedPair1() {
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/test/java/org/apache/hadoop/mrunit/TestTestDriver.java import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Test; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; public class TestTestDriver extends TestCase { /** * Test method for * {@link org.apache.hadoop.mrunit.TestDriver#parseTabbedPair(java.lang.String)}. */ @Test public void testParseTabbedPair1() {
Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\tbar");
apache/mrunit
src/test/java/org/apache/hadoop/mrunit/TestTestDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Test;
public void testParseTabbedPair6() { Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\t\tbar"); assertEquals(pr.getFirst().toString(), "foo"); assertEquals(pr.getSecond().toString(), "\tbar"); } @Test public void testParseTabbedPair7() { Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\tbar\n"); assertEquals(pr.getFirst().toString(), "foo"); assertEquals(pr.getSecond().toString(), "bar\n"); } @Test public void testParseTabbedPair8() { Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\t bar\tbaz"); assertEquals(pr.getFirst().toString(), "foo"); assertEquals(pr.getSecond().toString(), " bar\tbaz"); } /** * Test method for * {@link * org.apache.hadoop.mrunit.TestDriver#parseCommaDelimitedList(java.lang.String)}. */ @Test public void testParseCommaDelimList1() { List<Text> out = TestDriver.parseCommaDelimitedList("foo"); ArrayList<Text> verify = new ArrayList<Text>(); verify.add(new Text("foo"));
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/test/java/org/apache/hadoop/mrunit/TestTestDriver.java import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Test; public void testParseTabbedPair6() { Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\t\tbar"); assertEquals(pr.getFirst().toString(), "foo"); assertEquals(pr.getSecond().toString(), "\tbar"); } @Test public void testParseTabbedPair7() { Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\tbar\n"); assertEquals(pr.getFirst().toString(), "foo"); assertEquals(pr.getSecond().toString(), "bar\n"); } @Test public void testParseTabbedPair8() { Pair<Text, Text> pr = TestDriver.parseTabbedPair("foo\t bar\tbaz"); assertEquals(pr.getFirst().toString(), "foo"); assertEquals(pr.getSecond().toString(), " bar\tbaz"); } /** * Test method for * {@link * org.apache.hadoop.mrunit.TestDriver#parseCommaDelimitedList(java.lang.String)}. */ @Test public void testParseCommaDelimList1() { List<Text> out = TestDriver.parseCommaDelimitedList("foo"); ArrayList<Text> verify = new ArrayList<Text>(); verify.add(new Text("foo"));
assertListEquals(out, verify);
apache/mrunit
src/test/java/org/apache/hadoop/mrunit/AllTests.java
// Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockReporter.java // public class TestMockReporter extends TestCase { // // @Test // public void testGetInputSplitForMapper() { // InputSplit split = new MockReporter(MockReporter.ReporterType.Mapper, null).getInputSplit(); // assertTrue(null != split); // } // // // reporter is contractually obligated to throw an exception // // if the reducer tries to grab the input split. // @Test // public void testGetInputSplitForReducer() { // try { // new MockReporter(MockReporter.ReporterType.Reducer, null).getInputSplit(); // fail(); // shouldn't get here // } catch (UnsupportedOperationException uoe) { // // expected this. // } // } // } // // Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockOutputCollector.java // public class TestMockOutputCollector extends TestCase { // // /** // * A mapper that reuses the same key and val objects to emit multiple values // */ // class RepeatMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { // public void map(Text k, Text v, OutputCollector<Text, Text> out, Reporter r) // throws IOException { // Text outKey = new Text(); // Text outVal = new Text(); // // outKey.set("1"); // outVal.set("a"); // out.collect(outKey, outVal); // // outKey.set("2"); // outVal.set("b"); // out.collect(outKey, outVal); // // outKey.set("3"); // outVal.set("c"); // out.collect(outKey, outVal); // } // } // // @Test // public void testRepeatedObjectUse() { // Mapper<Text, Text, Text, Text> mapper = new RepeatMapper(); // MapDriver<Text, Text, Text, Text> driver = new MapDriver(mapper); // // driver.withInput(new Text("inK"), new Text("inV")) // .withOutput(new Text("1"), new Text("a")) // .withOutput(new Text("2"), new Text("b")) // .withOutput(new Text("3"), new Text("c")) // .runTest(); // } // }
import org.apache.hadoop.mrunit.mock.TestMockReporter; import org.apache.hadoop.mrunit.mock.TestMockOutputCollector; import junit.framework.Test; import junit.framework.TestSuite;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * All tests for MRUnit testing device (org.apache.hadoop.mrunit) * */ public final class AllTests { private AllTests() { } public static Test suite() { TestSuite suite = new TestSuite("Test for org.apache.hadoop.mrunit"); suite.addTestSuite(TestMapDriver.class); suite.addTestSuite(TestMapReduceDriver.class); suite.addTestSuite(TestPipelineMapReduceDriver.class);
// Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockReporter.java // public class TestMockReporter extends TestCase { // // @Test // public void testGetInputSplitForMapper() { // InputSplit split = new MockReporter(MockReporter.ReporterType.Mapper, null).getInputSplit(); // assertTrue(null != split); // } // // // reporter is contractually obligated to throw an exception // // if the reducer tries to grab the input split. // @Test // public void testGetInputSplitForReducer() { // try { // new MockReporter(MockReporter.ReporterType.Reducer, null).getInputSplit(); // fail(); // shouldn't get here // } catch (UnsupportedOperationException uoe) { // // expected this. // } // } // } // // Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockOutputCollector.java // public class TestMockOutputCollector extends TestCase { // // /** // * A mapper that reuses the same key and val objects to emit multiple values // */ // class RepeatMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { // public void map(Text k, Text v, OutputCollector<Text, Text> out, Reporter r) // throws IOException { // Text outKey = new Text(); // Text outVal = new Text(); // // outKey.set("1"); // outVal.set("a"); // out.collect(outKey, outVal); // // outKey.set("2"); // outVal.set("b"); // out.collect(outKey, outVal); // // outKey.set("3"); // outVal.set("c"); // out.collect(outKey, outVal); // } // } // // @Test // public void testRepeatedObjectUse() { // Mapper<Text, Text, Text, Text> mapper = new RepeatMapper(); // MapDriver<Text, Text, Text, Text> driver = new MapDriver(mapper); // // driver.withInput(new Text("inK"), new Text("inV")) // .withOutput(new Text("1"), new Text("a")) // .withOutput(new Text("2"), new Text("b")) // .withOutput(new Text("3"), new Text("c")) // .runTest(); // } // } // Path: src/test/java/org/apache/hadoop/mrunit/AllTests.java import org.apache.hadoop.mrunit.mock.TestMockReporter; import org.apache.hadoop.mrunit.mock.TestMockOutputCollector; import junit.framework.Test; import junit.framework.TestSuite; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * All tests for MRUnit testing device (org.apache.hadoop.mrunit) * */ public final class AllTests { private AllTests() { } public static Test suite() { TestSuite suite = new TestSuite("Test for org.apache.hadoop.mrunit"); suite.addTestSuite(TestMapDriver.class); suite.addTestSuite(TestMapReduceDriver.class); suite.addTestSuite(TestPipelineMapReduceDriver.class);
suite.addTestSuite(TestMockReporter.class);
apache/mrunit
src/test/java/org/apache/hadoop/mrunit/AllTests.java
// Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockReporter.java // public class TestMockReporter extends TestCase { // // @Test // public void testGetInputSplitForMapper() { // InputSplit split = new MockReporter(MockReporter.ReporterType.Mapper, null).getInputSplit(); // assertTrue(null != split); // } // // // reporter is contractually obligated to throw an exception // // if the reducer tries to grab the input split. // @Test // public void testGetInputSplitForReducer() { // try { // new MockReporter(MockReporter.ReporterType.Reducer, null).getInputSplit(); // fail(); // shouldn't get here // } catch (UnsupportedOperationException uoe) { // // expected this. // } // } // } // // Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockOutputCollector.java // public class TestMockOutputCollector extends TestCase { // // /** // * A mapper that reuses the same key and val objects to emit multiple values // */ // class RepeatMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { // public void map(Text k, Text v, OutputCollector<Text, Text> out, Reporter r) // throws IOException { // Text outKey = new Text(); // Text outVal = new Text(); // // outKey.set("1"); // outVal.set("a"); // out.collect(outKey, outVal); // // outKey.set("2"); // outVal.set("b"); // out.collect(outKey, outVal); // // outKey.set("3"); // outVal.set("c"); // out.collect(outKey, outVal); // } // } // // @Test // public void testRepeatedObjectUse() { // Mapper<Text, Text, Text, Text> mapper = new RepeatMapper(); // MapDriver<Text, Text, Text, Text> driver = new MapDriver(mapper); // // driver.withInput(new Text("inK"), new Text("inV")) // .withOutput(new Text("1"), new Text("a")) // .withOutput(new Text("2"), new Text("b")) // .withOutput(new Text("3"), new Text("c")) // .runTest(); // } // }
import org.apache.hadoop.mrunit.mock.TestMockReporter; import org.apache.hadoop.mrunit.mock.TestMockOutputCollector; import junit.framework.Test; import junit.framework.TestSuite;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * All tests for MRUnit testing device (org.apache.hadoop.mrunit) * */ public final class AllTests { private AllTests() { } public static Test suite() { TestSuite suite = new TestSuite("Test for org.apache.hadoop.mrunit"); suite.addTestSuite(TestMapDriver.class); suite.addTestSuite(TestMapReduceDriver.class); suite.addTestSuite(TestPipelineMapReduceDriver.class); suite.addTestSuite(TestMockReporter.class);
// Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockReporter.java // public class TestMockReporter extends TestCase { // // @Test // public void testGetInputSplitForMapper() { // InputSplit split = new MockReporter(MockReporter.ReporterType.Mapper, null).getInputSplit(); // assertTrue(null != split); // } // // // reporter is contractually obligated to throw an exception // // if the reducer tries to grab the input split. // @Test // public void testGetInputSplitForReducer() { // try { // new MockReporter(MockReporter.ReporterType.Reducer, null).getInputSplit(); // fail(); // shouldn't get here // } catch (UnsupportedOperationException uoe) { // // expected this. // } // } // } // // Path: src/test/java/org/apache/hadoop/mrunit/mock/TestMockOutputCollector.java // public class TestMockOutputCollector extends TestCase { // // /** // * A mapper that reuses the same key and val objects to emit multiple values // */ // class RepeatMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { // public void map(Text k, Text v, OutputCollector<Text, Text> out, Reporter r) // throws IOException { // Text outKey = new Text(); // Text outVal = new Text(); // // outKey.set("1"); // outVal.set("a"); // out.collect(outKey, outVal); // // outKey.set("2"); // outVal.set("b"); // out.collect(outKey, outVal); // // outKey.set("3"); // outVal.set("c"); // out.collect(outKey, outVal); // } // } // // @Test // public void testRepeatedObjectUse() { // Mapper<Text, Text, Text, Text> mapper = new RepeatMapper(); // MapDriver<Text, Text, Text, Text> driver = new MapDriver(mapper); // // driver.withInput(new Text("inK"), new Text("inV")) // .withOutput(new Text("1"), new Text("a")) // .withOutput(new Text("2"), new Text("b")) // .withOutput(new Text("3"), new Text("c")) // .runTest(); // } // } // Path: src/test/java/org/apache/hadoop/mrunit/AllTests.java import org.apache.hadoop.mrunit.mock.TestMockReporter; import org.apache.hadoop.mrunit.mock.TestMockOutputCollector; import junit.framework.Test; import junit.framework.TestSuite; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * All tests for MRUnit testing device (org.apache.hadoop.mrunit) * */ public final class AllTests { private AllTests() { } public static Test suite() { TestSuite suite = new TestSuite("Test for org.apache.hadoop.mrunit"); suite.addTestSuite(TestMapDriver.class); suite.addTestSuite(TestMapReduceDriver.class); suite.addTestSuite(TestPipelineMapReduceDriver.class); suite.addTestSuite(TestMockReporter.class);
suite.addTestSuite(TestMockOutputCollector.class);
apache/mrunit
src/test/java/org/apache/hadoop/mrunit/TestMapReduceDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.IdentityMapper; import org.apache.hadoop.mapred.lib.IdentityReducer; import org.apache.hadoop.mapred.lib.LongSumReducer; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Before; import org.junit.Test;
mapper = new IdentityMapper<Text, LongWritable>(); reducer = new LongSumReducer<Text>(); driver = new MapReduceDriver<Text, LongWritable, Text, LongWritable, Text, LongWritable>( mapper, reducer); // for shuffle tests driver2 = new MapReduceDriver<Text, Text, Text, Text, Text, Text>(); } @Test public void testRun() { List<Pair<Text, LongWritable>> out = null; try { out = driver .withInput(new Text("foo"), new LongWritable(FOO_IN_A)) .withInput(new Text("foo"), new LongWritable(FOO_IN_B)) .withInput(new Text("bar"), new LongWritable(BAR_IN)) .run(); } catch (IOException ioe) { fail(); } List<Pair<Text, LongWritable>> expected = new ArrayList<Pair<Text, LongWritable>>(); expected.add(new Pair<Text, LongWritable>(new Text("bar"), new LongWritable(BAR_IN))); expected.add(new Pair<Text, LongWritable>(new Text("foo"), new LongWritable(FOO_OUT)));
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/test/java/org/apache/hadoop/mrunit/TestMapReduceDriver.java import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.IdentityMapper; import org.apache.hadoop.mapred.lib.IdentityReducer; import org.apache.hadoop.mapred.lib.LongSumReducer; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Before; import org.junit.Test; mapper = new IdentityMapper<Text, LongWritable>(); reducer = new LongSumReducer<Text>(); driver = new MapReduceDriver<Text, LongWritable, Text, LongWritable, Text, LongWritable>( mapper, reducer); // for shuffle tests driver2 = new MapReduceDriver<Text, Text, Text, Text, Text, Text>(); } @Test public void testRun() { List<Pair<Text, LongWritable>> out = null; try { out = driver .withInput(new Text("foo"), new LongWritable(FOO_IN_A)) .withInput(new Text("foo"), new LongWritable(FOO_IN_B)) .withInput(new Text("bar"), new LongWritable(BAR_IN)) .run(); } catch (IOException ioe) { fail(); } List<Pair<Text, LongWritable>> expected = new ArrayList<Pair<Text, LongWritable>>(); expected.add(new Pair<Text, LongWritable>(new Text("bar"), new LongWritable(BAR_IN))); expected.add(new Pair<Text, LongWritable>(new Text("foo"), new LongWritable(FOO_OUT)));
assertListEquals(out, expected);
apache/mrunit
src/main/java/org/apache/hadoop/mrunit/PipelineMapReduceDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mrunit.types.Pair;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * Harness that allows you to test a dataflow through a set of Mappers and * Reducers. You provide a set of (Mapper, Reducer) "jobs" that make up * a workflow, as well as a set of (key, value) pairs to pass in to the first * Mapper. You can also specify the outputs you expect to be sent to the final * Reducer in the pipeline. * * By calling runTest(), the harness will deliver the input to the first * Mapper, feed the intermediate results to the first Reducer (without checking * them), and proceed to forward this data along to subsequent Mapper/Reducer * jobs in the pipeline until the final Reducer. The last Reducer's outputs are * checked against the expected results. * * This is designed for slightly more complicated integration tests than the * MapReduceDriver, which is for smaller unit tests. * * (K1, V1) in the type signature refer to the types associated with the inputs * to the first Mapper. (K2, V2) refer to the types associated with the final * Reducer's output. No intermediate types are specified. */ public class PipelineMapReduceDriver<K1, V1, K2, V2> extends TestDriver<K1, V1, K2, V2> { public static final Log LOG = LogFactory.getLog(PipelineMapReduceDriver.class);
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/main/java/org/apache/hadoop/mrunit/PipelineMapReduceDriver.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mrunit.types.Pair; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * Harness that allows you to test a dataflow through a set of Mappers and * Reducers. You provide a set of (Mapper, Reducer) "jobs" that make up * a workflow, as well as a set of (key, value) pairs to pass in to the first * Mapper. You can also specify the outputs you expect to be sent to the final * Reducer in the pipeline. * * By calling runTest(), the harness will deliver the input to the first * Mapper, feed the intermediate results to the first Reducer (without checking * them), and proceed to forward this data along to subsequent Mapper/Reducer * jobs in the pipeline until the final Reducer. The last Reducer's outputs are * checked against the expected results. * * This is designed for slightly more complicated integration tests than the * MapReduceDriver, which is for smaller unit tests. * * (K1, V1) in the type signature refer to the types associated with the inputs * to the first Mapper. (K2, V2) refer to the types associated with the final * Reducer's output. No intermediate types are specified. */ public class PipelineMapReduceDriver<K1, V1, K2, V2> extends TestDriver<K1, V1, K2, V2> { public static final Log LOG = LogFactory.getLog(PipelineMapReduceDriver.class);
private List<Pair<Mapper, Reducer>> mapReducePipeline;
apache/mrunit
src/main/java/org/apache/hadoop/mrunit/TestDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.types.Pair;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; public abstract class TestDriver<K1, V1, K2, V2> { public static final Log LOG = LogFactory.getLog(TestDriver.class);
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/main/java/org/apache/hadoop/mrunit/TestDriver.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.types.Pair; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; public abstract class TestDriver<K1, V1, K2, V2> { public static final Log LOG = LogFactory.getLog(TestDriver.class);
protected List<Pair<K2, V2>> expectedOutputs;
apache/mrunit
src/main/java/org/apache/hadoop/mrunit/MapReduceDriverBase.java
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mrunit.types.Pair; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.TreeMap; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Text;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * Harness that allows you to test a Mapper and a Reducer instance together * You provide the input key and value that should be sent to the Mapper, and * outputs you expect to be sent by the Reducer to the collector for those * inputs. By calling runTest(), the harness will deliver the input to the * Mapper, feed the intermediate results to the Reducer (without checking * them), and will check the Reducer's outputs against the expected results. * This is designed to handle a single (k, v)* -> (k, v)* case from the * Mapper/Reducer pair, representing a single unit test. */ public abstract class MapReduceDriverBase<K1, V1, K2 extends Comparable, V2, K3, V3> extends TestDriver<K1, V1, K3, V3> { public static final Log LOG = LogFactory.getLog(MapReduceDriverBase.class);
// Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/main/java/org/apache/hadoop/mrunit/MapReduceDriverBase.java import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mrunit.types.Pair; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.TreeMap; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io.Text; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; /** * Harness that allows you to test a Mapper and a Reducer instance together * You provide the input key and value that should be sent to the Mapper, and * outputs you expect to be sent by the Reducer to the collector for those * inputs. By calling runTest(), the harness will deliver the input to the * Mapper, feed the intermediate results to the Reducer (without checking * them), and will check the Reducer's outputs against the expected results. * This is designed to handle a single (k, v)* -> (k, v)* case from the * Mapper/Reducer pair, representing a single unit test. */ public abstract class MapReduceDriverBase<K1, V1, K2 extends Comparable, V2, K3, V3> extends TestDriver<K1, V1, K3, V3> { public static final Log LOG = LogFactory.getLog(MapReduceDriverBase.class);
protected List<Pair<K1, V1>> inputList;
apache/mrunit
src/test/java/org/apache/hadoop/mrunit/TestReduceDriver.java
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // }
import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.LongSumReducer; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Before; import org.junit.Test; import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; public class TestReduceDriver extends TestCase { private static final int IN_A = 4; private static final int IN_B = 6; private static final int OUT_VAL = 10; private static final int INCORRECT_OUT = 12; private static final int OUT_EMPTY = 0; private Reducer<Text, LongWritable, Text, LongWritable> reducer; private ReduceDriver<Text, LongWritable, Text, LongWritable> driver; @Before public void setUp() throws Exception { reducer = new LongSumReducer<Text>(); driver = new ReduceDriver<Text, LongWritable, Text, LongWritable>( reducer); } @Test public void testRun() {
// Path: src/main/java/org/apache/hadoop/mrunit/testutil/ExtendedAssert.java // public static void assertListEquals(List expected, List actual) { // if (expected.size() != actual.size()) { // fail("Expected list of size " + expected.size() + "; actual size is " // + actual.size()); // } // // for (int i = 0; i < expected.size(); i++) { // Object t1 = expected.get(i); // Object t2 = actual.get(i); // // if (!t1.equals(t2)) { // fail("Expected element " + t1 + " at index " + i // + " != actual element " + t2); // } // } // } // // Path: src/main/java/org/apache/hadoop/mrunit/types/Pair.java // public class Pair<S, T> implements Comparable<Pair<S, T>> { // // private final S first; // private final T second; // // public Pair(final S car, final T cdr) { // first = car; // second = cdr; // } // // public S getFirst() { return first; } // public T getSecond() { return second; } // // @Override // public boolean equals(Object o) { // if (null == o) { // return false; // } else if (o instanceof Pair) { // Pair<S, T> p = (Pair<S, T>) o; // if (first == null && second == null) { // return p.first == null && p.second == null; // } else if (first == null) { // return p.first == null && second.equals(p.second); // } else if (second == null) { // return p.second == null && first.equals(p.first); // } else { // return first.equals(p.first) && second.equals(p.second); // } // } else { // return false; // } // } // // @Override // public int hashCode() { // int code = 0; // // if (null != first) { // code += first.hashCode(); // } // // if (null != second) { // code += second.hashCode() << 1; // } // // return code; // } // // @Override // public int compareTo(Pair<S, T> p) { // if (null == p) { // return 1; // } // // Comparable<S> firstCompare = (Comparable<S>) first; // // int firstResult = firstCompare.compareTo(p.first); // if (firstResult == 0) { // Comparable<T> secondCompare = (Comparable<T>) second; // return secondCompare.compareTo(p.second); // } else { // return firstResult; // } // } // // // TODO: Can this be made static? Same with SecondElemComparator? // public class FirstElemComparator implements Comparator<Pair<S, T>> { // public FirstElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<S> cS = (Comparable<S>) p1.first; // return cS.compareTo(p2.first); // } // } // // public class SecondElemComparator implements Comparator<Pair<S, T>> { // public SecondElemComparator() { // } // // public int compare(Pair<S, T> p1, Pair<S, T> p2) { // Comparable<T> cT = (Comparable<T>) p1.second; // return cT.compareTo(p2.second); // } // } // // @Override // public String toString() { // String firstString = "null"; // String secondString = "null"; // // if (null != first) { // firstString = first.toString(); // } // // if (null != second) { // secondString = second.toString(); // } // // return "(" + firstString + ", " + secondString + ")"; // } // } // Path: src/test/java/org/apache/hadoop/mrunit/TestReduceDriver.java import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.lib.LongSumReducer; import org.apache.hadoop.mrunit.types.Pair; import org.junit.Before; import org.junit.Test; import static org.apache.hadoop.mrunit.testutil.ExtendedAssert.assertListEquals; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.MapReduceBase; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mrunit; public class TestReduceDriver extends TestCase { private static final int IN_A = 4; private static final int IN_B = 6; private static final int OUT_VAL = 10; private static final int INCORRECT_OUT = 12; private static final int OUT_EMPTY = 0; private Reducer<Text, LongWritable, Text, LongWritable> reducer; private ReduceDriver<Text, LongWritable, Text, LongWritable> driver; @Before public void setUp() throws Exception { reducer = new LongSumReducer<Text>(); driver = new ReduceDriver<Text, LongWritable, Text, LongWritable>( reducer); } @Test public void testRun() {
List<Pair<Text, LongWritable>> out = null;
Longri/libgdx-svg
ios/src/org/oscim/ios/backend/IosSvgBitmap.java
// Path: ios-moe/src/svg/SVGRenderer.java // @Generated // @Library("SVGgh") // @Runtime(ObjCRuntime.class) // @ObjCClassBinding // public class SVGRenderer extends SVGParser { // static { // NatJ.register(); // } // // @Generated // public SVGRenderer(Pointer peer) { // super(peer); // } // // // @Generated // @Owned // @Selector("alloc") // public static native SVGRenderer alloc(); // // // @Generated // @Selector("asImageWithSize:andScale:") // public native UIImage asImageWithSizeAndScale(@ByValue CGSize maximumSize, // @NFloat double scale); // // // @Generated // @Selector("viewRect") // @ByValue // public native CGRect viewRect(); // }
import org.oscim.backend.CanvasAdapter; import org.oscim.utils.IOUtils; import org.robovm.apple.coregraphics.CGRect; import org.robovm.apple.coregraphics.CGSize; import org.robovm.apple.uikit.UIImage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import svg.SVGRenderer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
/* * Copyright 2016 Longri * Copyright 2016 devemux86 * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.ios.backend; public class IosSvgBitmap extends IosBitmap { private static final Logger log = LoggerFactory.getLogger(IosSvgBitmap.class); /** * Default size is 20x20px (400px) at 160dpi. */ public static float DEFAULT_SIZE = 400f; private static String getStringFromInputStream(InputStream is) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(br); } return sb.toString(); } public static UIImage getResourceBitmap(InputStream inputStream, float scaleFactor, float defaultSize, int width, int height, int percent) { String svg = getStringFromInputStream(inputStream);
// Path: ios-moe/src/svg/SVGRenderer.java // @Generated // @Library("SVGgh") // @Runtime(ObjCRuntime.class) // @ObjCClassBinding // public class SVGRenderer extends SVGParser { // static { // NatJ.register(); // } // // @Generated // public SVGRenderer(Pointer peer) { // super(peer); // } // // // @Generated // @Owned // @Selector("alloc") // public static native SVGRenderer alloc(); // // // @Generated // @Selector("asImageWithSize:andScale:") // public native UIImage asImageWithSizeAndScale(@ByValue CGSize maximumSize, // @NFloat double scale); // // // @Generated // @Selector("viewRect") // @ByValue // public native CGRect viewRect(); // } // Path: ios/src/org/oscim/ios/backend/IosSvgBitmap.java import org.oscim.backend.CanvasAdapter; import org.oscim.utils.IOUtils; import org.robovm.apple.coregraphics.CGRect; import org.robovm.apple.coregraphics.CGSize; import org.robovm.apple.uikit.UIImage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import svg.SVGRenderer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /* * Copyright 2016 Longri * Copyright 2016 devemux86 * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.ios.backend; public class IosSvgBitmap extends IosBitmap { private static final Logger log = LoggerFactory.getLogger(IosSvgBitmap.class); /** * Default size is 20x20px (400px) at 160dpi. */ public static float DEFAULT_SIZE = 400f; private static String getStringFromInputStream(InputStream is) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(br); } return sb.toString(); } public static UIImage getResourceBitmap(InputStream inputStream, float scaleFactor, float defaultSize, int width, int height, int percent) { String svg = getStringFromInputStream(inputStream);
SVGRenderer renderer = new SVGRenderer(svg);
Longri/libgdx-svg
ios-moe/src/org/oscim/ios_moe/backend/IosSvgBitmap.java
// Path: ios-moe/src/svg/SVGRenderer.java // @Generated // @Library("SVGgh") // @Runtime(ObjCRuntime.class) // @ObjCClassBinding // public class SVGRenderer extends SVGParser { // static { // NatJ.register(); // } // // @Generated // public SVGRenderer(Pointer peer) { // super(peer); // } // // // @Generated // @Owned // @Selector("alloc") // public static native SVGRenderer alloc(); // // // @Generated // @Selector("asImageWithSize:andScale:") // public native UIImage asImageWithSizeAndScale(@ByValue CGSize maximumSize, // @NFloat double scale); // // // @Generated // @Selector("viewRect") // @ByValue // public native CGRect viewRect(); // }
import apple.coregraphics.struct.CGRect; import apple.coregraphics.struct.CGSize; import apple.uikit.UIImage; import org.oscim.backend.CanvasAdapter; import org.oscim.utils.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import svg.SVGRenderer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
/* * Copyright 2016 Longri * Copyright 2016 devemux86 * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.ios_moe.backend; public class IosSvgBitmap extends IosBitmap { private static final Logger log = LoggerFactory.getLogger(IosSvgBitmap.class); /** * Default size is 20x20px (400px) at 160dpi. */ public static float DEFAULT_SIZE = 400f; private static String getStringFromInputStream(InputStream is) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(br); } return sb.toString(); } public static UIImage getResourceBitmap(InputStream inputStream, float scaleFactor, float defaultSize, int width, int height, int percent) { String svg = getStringFromInputStream(inputStream);
// Path: ios-moe/src/svg/SVGRenderer.java // @Generated // @Library("SVGgh") // @Runtime(ObjCRuntime.class) // @ObjCClassBinding // public class SVGRenderer extends SVGParser { // static { // NatJ.register(); // } // // @Generated // public SVGRenderer(Pointer peer) { // super(peer); // } // // // @Generated // @Owned // @Selector("alloc") // public static native SVGRenderer alloc(); // // // @Generated // @Selector("asImageWithSize:andScale:") // public native UIImage asImageWithSizeAndScale(@ByValue CGSize maximumSize, // @NFloat double scale); // // // @Generated // @Selector("viewRect") // @ByValue // public native CGRect viewRect(); // } // Path: ios-moe/src/org/oscim/ios_moe/backend/IosSvgBitmap.java import apple.coregraphics.struct.CGRect; import apple.coregraphics.struct.CGSize; import apple.uikit.UIImage; import org.oscim.backend.CanvasAdapter; import org.oscim.utils.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import svg.SVGRenderer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /* * Copyright 2016 Longri * Copyright 2016 devemux86 * * This program is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.ios_moe.backend; public class IosSvgBitmap extends IosBitmap { private static final Logger log = LoggerFactory.getLogger(IosSvgBitmap.class); /** * Default size is 20x20px (400px) at 160dpi. */ public static float DEFAULT_SIZE = 400f; private static String getStringFromInputStream(InputStream is) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { log.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(br); } return sb.toString(); } public static UIImage getResourceBitmap(InputStream inputStream, float scaleFactor, float defaultSize, int width, int height, int percent) { String svg = getStringFromInputStream(inputStream);
SVGRenderer renderer = SVGRenderer.alloc();
Longri/libgdx-svg
ios-moe/src/org/oscim/ios_moe/backend/IosCanvas.java
// Path: ios-moe/src/org/oscim/ios_moe/backend/IosBitmap.java // static CGColorRef getCGColor(int color) { // // return UIColor.colorWithRedGreenBlueAlpha( // Color.r(color) / 255.0, // Color.g(color) / 255.0, // Color.b(color) / 255.0, // Color.a(color) / 255.0 // ).CGColor(); // }
import apple.coregraphics.opaque.CGContextRef; import apple.coregraphics.struct.CGPoint; import apple.coregraphics.struct.CGRect; import apple.coregraphics.struct.CGSize; import apple.uikit.c.UIKit; import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Canvas; import org.oscim.backend.canvas.Paint; import static apple.coregraphics.c.CoreGraphics.*; import static org.oscim.ios_moe.backend.IosBitmap.getCGColor;
} bmp.createImageFromContext(); } @Override public void drawLine(float x1, float y1, float x2, float y2, Paint paint) { bmp.createContext(); //flip Y-axis y1 = (int) (this.bmp.getHeight() - y1); y2 = (int) (this.bmp.getHeight() - y2); // set Stroke properties CGContextSetLineWidth(bmp.cgBitmapContext, ((IosPaint) paint).strokeWidth); CGContextSetLineCap(bmp.cgBitmapContext, ((IosPaint) paint).getIosStrokeCap()); CGContextSetLineJoin(bmp.cgBitmapContext, ((IosPaint) paint).getIosStrokeJoin()); setStrokeColor(bmp.cgBitmapContext, (paint.getColor())); //draw line CGContextBeginPath(bmp.cgBitmapContext); CGContextMoveToPoint(bmp.cgBitmapContext, x1, y1); CGContextAddLineToPoint(bmp.cgBitmapContext, x2, y2); CGContextStrokePath(bmp.cgBitmapContext); bmp.createImageFromContext(); } @Override public void fillColor(int color) { bmp.createContext(); CGSize size = new CGSize(bmp.width, bmp.height);
// Path: ios-moe/src/org/oscim/ios_moe/backend/IosBitmap.java // static CGColorRef getCGColor(int color) { // // return UIColor.colorWithRedGreenBlueAlpha( // Color.r(color) / 255.0, // Color.g(color) / 255.0, // Color.b(color) / 255.0, // Color.a(color) / 255.0 // ).CGColor(); // } // Path: ios-moe/src/org/oscim/ios_moe/backend/IosCanvas.java import apple.coregraphics.opaque.CGContextRef; import apple.coregraphics.struct.CGPoint; import apple.coregraphics.struct.CGRect; import apple.coregraphics.struct.CGSize; import apple.uikit.c.UIKit; import org.oscim.backend.canvas.Bitmap; import org.oscim.backend.canvas.Canvas; import org.oscim.backend.canvas.Paint; import static apple.coregraphics.c.CoreGraphics.*; import static org.oscim.ios_moe.backend.IosBitmap.getCGColor; } bmp.createImageFromContext(); } @Override public void drawLine(float x1, float y1, float x2, float y2, Paint paint) { bmp.createContext(); //flip Y-axis y1 = (int) (this.bmp.getHeight() - y1); y2 = (int) (this.bmp.getHeight() - y2); // set Stroke properties CGContextSetLineWidth(bmp.cgBitmapContext, ((IosPaint) paint).strokeWidth); CGContextSetLineCap(bmp.cgBitmapContext, ((IosPaint) paint).getIosStrokeCap()); CGContextSetLineJoin(bmp.cgBitmapContext, ((IosPaint) paint).getIosStrokeJoin()); setStrokeColor(bmp.cgBitmapContext, (paint.getColor())); //draw line CGContextBeginPath(bmp.cgBitmapContext); CGContextMoveToPoint(bmp.cgBitmapContext, x1, y1); CGContextAddLineToPoint(bmp.cgBitmapContext, x2, y2); CGContextStrokePath(bmp.cgBitmapContext); bmp.createImageFromContext(); } @Override public void fillColor(int color) { bmp.createContext(); CGSize size = new CGSize(bmp.width, bmp.height);
CGContextSetFillColorWithColor(bmp.cgBitmapContext, getCGColor(color));
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/DisplayUtils.java
// Path: app/src/main/java/nich/work/aequorea/common/ui/activity/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity implements BaseView { // public String currentTheme; // public boolean needToReTheme; // // private boolean isForeground; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // initTheme(); // // setContentView(getContentViewId()); // initModel(); // initView(); // initPresenter(); // } // // protected void initTheme() { // currentTheme = ThemeHelper.getTheme(); // setTheme(ThemeHelper.getThemeStyle(currentTheme)); // } // // @Override // protected void onResume() { // super.onResume(); // // isForeground = true; // if (needToReTheme) { // onThemeSwitchPending(); // } // } // // @Override // protected void onPause() { // super.onPause(); // // isForeground = false; // } // // @Override // protected void onDestroy() { // super.onDestroy(); // } // // public void setStatusBarStyle(boolean isLightStatusBar) { // DisplayUtils.setStatusBarStyle(this, isLightStatusBar); // } // // public void setStatusBarInLowProfileMode(boolean isLightStautsBar) { // DisplayUtils.setStatusInLowProfileMode(this, isLightStautsBar); // } // // public int dp2px(int dp) { // return DisplayUtils.dp2px(this, dp); // } // // protected abstract int getContentViewId(); // // protected abstract void initModel(); // // protected abstract void initView(); // // protected abstract void initPresenter(); // // // For those activity that need to change color when user have changed theme. // @Override // public void onThemeSwitch() { // // do nothing // } // // @Override // public void onThemeSwitchPending() { // // do nothing // } // // public boolean isInLightTheme() { // return currentTheme.equals(Constants.THEME_LIGHT); // } // // public boolean activityInForeground() { // return isForeground; // } // // @Override // public void onBackPressed() { // super.onBackPressed(); // overridePendingTransition(0, R.anim.activity_slide_out_bottom); // } // }
import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.os.Build; import androidx.core.widget.NestedScrollView; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import java.lang.reflect.Field; import java.lang.reflect.Method; import nich.work.aequorea.R; import nich.work.aequorea.common.ui.activity.BaseActivity;
package nich.work.aequorea.common.utils; public class DisplayUtils { public static int getStatusBarHeight(Resources r) { int result = 0; int resourceId = r.getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = r.getDimensionPixelSize(resourceId); } return result; }
// Path: app/src/main/java/nich/work/aequorea/common/ui/activity/BaseActivity.java // public abstract class BaseActivity extends AppCompatActivity implements BaseView { // public String currentTheme; // public boolean needToReTheme; // // private boolean isForeground; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // initTheme(); // // setContentView(getContentViewId()); // initModel(); // initView(); // initPresenter(); // } // // protected void initTheme() { // currentTheme = ThemeHelper.getTheme(); // setTheme(ThemeHelper.getThemeStyle(currentTheme)); // } // // @Override // protected void onResume() { // super.onResume(); // // isForeground = true; // if (needToReTheme) { // onThemeSwitchPending(); // } // } // // @Override // protected void onPause() { // super.onPause(); // // isForeground = false; // } // // @Override // protected void onDestroy() { // super.onDestroy(); // } // // public void setStatusBarStyle(boolean isLightStatusBar) { // DisplayUtils.setStatusBarStyle(this, isLightStatusBar); // } // // public void setStatusBarInLowProfileMode(boolean isLightStautsBar) { // DisplayUtils.setStatusInLowProfileMode(this, isLightStautsBar); // } // // public int dp2px(int dp) { // return DisplayUtils.dp2px(this, dp); // } // // protected abstract int getContentViewId(); // // protected abstract void initModel(); // // protected abstract void initView(); // // protected abstract void initPresenter(); // // // For those activity that need to change color when user have changed theme. // @Override // public void onThemeSwitch() { // // do nothing // } // // @Override // public void onThemeSwitchPending() { // // do nothing // } // // public boolean isInLightTheme() { // return currentTheme.equals(Constants.THEME_LIGHT); // } // // public boolean activityInForeground() { // return isForeground; // } // // @Override // public void onBackPressed() { // super.onBackPressed(); // overridePendingTransition(0, R.anim.activity_slide_out_bottom); // } // } // Path: app/src/main/java/nich/work/aequorea/common/utils/DisplayUtils.java import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.os.Build; import androidx.core.widget.NestedScrollView; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import java.lang.reflect.Field; import java.lang.reflect.Method; import nich.work.aequorea.R; import nich.work.aequorea.common.ui.activity.BaseActivity; package nich.work.aequorea.common.utils; public class DisplayUtils { public static int getStatusBarHeight(Resources r) { int result = 0; int resourceId = r.getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = r.getDimensionPixelSize(resourceId); } return result; }
public static void setStatusBarStyle(BaseActivity activity, boolean isLight) {
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java
// Path: app/src/main/java/nich/work/aequorea/model/entity/Meta.java // public class Meta { // // @SerializedName("current_page") // private Long mCurrentPage; // @SerializedName("next_page") // private Long mNextPage; // @SerializedName("total_count") // private Long mTotalCount; // @SerializedName("total_pages") // private Long mTotalPages; // // public Long getCurrentPage() { // return mCurrentPage; // } // // public void setCurrentPage(Long currentPage) { // mCurrentPage = currentPage; // } // // public Long getNextPage() { // return mNextPage; // } // // public void setNextPage(Long nextPage) { // mNextPage = nextPage; // } // // public Long getTotalCount() { // return mTotalCount; // } // // public void setTotalCount(Long totalCount) { // mTotalCount = totalCount; // } // // public Long getTotalPages() { // return mTotalPages; // } // // public void setTotalPages(Long totalPages) { // mTotalPages = totalPages; // } // // }
import com.google.gson.annotations.SerializedName; import java.util.List; import nich.work.aequorea.model.entity.Meta;
package nich.work.aequorea.model.entity.search; public class SearchData { @SerializedName("data") private List<SearchDatum> mData; @SerializedName("meta")
// Path: app/src/main/java/nich/work/aequorea/model/entity/Meta.java // public class Meta { // // @SerializedName("current_page") // private Long mCurrentPage; // @SerializedName("next_page") // private Long mNextPage; // @SerializedName("total_count") // private Long mTotalCount; // @SerializedName("total_pages") // private Long mTotalPages; // // public Long getCurrentPage() { // return mCurrentPage; // } // // public void setCurrentPage(Long currentPage) { // mCurrentPage = currentPage; // } // // public Long getNextPage() { // return mNextPage; // } // // public void setNextPage(Long nextPage) { // mNextPage = nextPage; // } // // public Long getTotalCount() { // return mTotalCount; // } // // public void setTotalCount(Long totalCount) { // mTotalCount = totalCount; // } // // public Long getTotalPages() { // return mTotalPages; // } // // public void setTotalPages(Long totalPages) { // mTotalPages = totalPages; // } // // } // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java import com.google.gson.annotations.SerializedName; import java.util.List; import nich.work.aequorea.model.entity.Meta; package nich.work.aequorea.model.entity.search; public class SearchData { @SerializedName("data") private List<SearchDatum> mData; @SerializedName("meta")
private Meta mMeta;
nichbar/Aequorea
richtext/src/main/java/com/zzhoujay/richtext/ig/ImageWrapper.java
// Path: richtext/src/main/java/com/zzhoujay/richtext/drawable/GifDrawable.java // public class GifDrawable extends Drawable { // // private static final int what = 0x357; // // private Movie movie; // private long start; // private int height; // private int width; // private boolean running; // private TextView textView; // private float scaleX; // private float scaleY; // private Paint paint; // // private Handler handler; // // public GifDrawable(Movie movie, int height, int width) { // this.movie = movie; // this.height = height; // this.width = width; // setBounds(0, 0, width, height); // scaleX = scaleY = 1.0f; // paint = new Paint(); // handler = new Handler(Looper.getMainLooper()) { // @Override // public void handleMessage(Message msg) { // if (msg.what == what && running && textView != null) { // textView.invalidate(); // sendEmptyMessageDelayed(what, 33); // } // } // }; // } // // @Override // public void draw(@NonNull Canvas canvas) { // long now = android.os.SystemClock.uptimeMillis(); // if (start == 0) { // first time // start = now; // } // if (movie != null) { // int dur = movie.duration(); // if (dur == 0) { // dur = 1000; // } // int relTime = (int) ((now - start) % dur); // movie.setTime(relTime); // Rect bounds = getBounds(); // canvas.scale(scaleX, scaleY); // movie.draw(canvas, bounds.left, bounds.top); // } // } // // @Override // public void setBounds(@NonNull Rect bounds) { // super.setBounds(bounds); // calculateScale(); // } // // @Override // public void setBounds(int left, int top, int right, int bottom) { // super.setBounds(left, top, right, bottom); // calculateScale(); // } // // private void calculateScale() { // scaleX = (float) getBounds().width() / width; // scaleY = (float) getBounds().height() / height; // } // // public void start(TextView textView) { // running = true; // this.textView = textView; // handler.sendEmptyMessage(what); // } // // public void stop() { // running = false; // this.textView = null; // } // // @Override // public void setAlpha(int alpha) { // paint.setAlpha(alpha); // } // // @Override // public void setColorFilter(ColorFilter colorFilter) { // paint.setColorFilter(colorFilter); // } // // @Override // public int getIntrinsicHeight() { // return height; // } // // @Override // public int getIntrinsicWidth() { // return width; // } // // @Override // public int getOpacity() { // return PixelFormat.TRANSLUCENT; // } // // public int getHeight() { // return height; // } // // public int getWidth() { // return width; // } // } // // Path: richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageWrapperMultiSourceException.java // public class ImageWrapperMultiSourceException extends IllegalArgumentException { // // private static final String MESSAGE = "GifDrawable和Bitmap有且只有一个为null"; // // public ImageWrapperMultiSourceException() { // super(MESSAGE); // } // // public ImageWrapperMultiSourceException(Throwable cause) { // super(MESSAGE, cause); // } // // }
import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import com.zzhoujay.richtext.callback.Recyclable; import com.zzhoujay.richtext.drawable.GifDrawable; import com.zzhoujay.richtext.exceptions.ImageWrapperMultiSourceException;
package com.zzhoujay.richtext.ig; /** * Created by zhou on 2017/2/21. * 抽象的图片类,包含Bitmap静态图的Gif动态图 */ class ImageWrapper implements Recyclable { private final GifDrawable gifDrawable; private final Bitmap bitmap; private final int height; private final int width; private ImageWrapper(GifDrawable gifDrawable, Bitmap bitmap) { this.gifDrawable = gifDrawable; this.bitmap = bitmap; if (gifDrawable == null) { if (bitmap == null) {
// Path: richtext/src/main/java/com/zzhoujay/richtext/drawable/GifDrawable.java // public class GifDrawable extends Drawable { // // private static final int what = 0x357; // // private Movie movie; // private long start; // private int height; // private int width; // private boolean running; // private TextView textView; // private float scaleX; // private float scaleY; // private Paint paint; // // private Handler handler; // // public GifDrawable(Movie movie, int height, int width) { // this.movie = movie; // this.height = height; // this.width = width; // setBounds(0, 0, width, height); // scaleX = scaleY = 1.0f; // paint = new Paint(); // handler = new Handler(Looper.getMainLooper()) { // @Override // public void handleMessage(Message msg) { // if (msg.what == what && running && textView != null) { // textView.invalidate(); // sendEmptyMessageDelayed(what, 33); // } // } // }; // } // // @Override // public void draw(@NonNull Canvas canvas) { // long now = android.os.SystemClock.uptimeMillis(); // if (start == 0) { // first time // start = now; // } // if (movie != null) { // int dur = movie.duration(); // if (dur == 0) { // dur = 1000; // } // int relTime = (int) ((now - start) % dur); // movie.setTime(relTime); // Rect bounds = getBounds(); // canvas.scale(scaleX, scaleY); // movie.draw(canvas, bounds.left, bounds.top); // } // } // // @Override // public void setBounds(@NonNull Rect bounds) { // super.setBounds(bounds); // calculateScale(); // } // // @Override // public void setBounds(int left, int top, int right, int bottom) { // super.setBounds(left, top, right, bottom); // calculateScale(); // } // // private void calculateScale() { // scaleX = (float) getBounds().width() / width; // scaleY = (float) getBounds().height() / height; // } // // public void start(TextView textView) { // running = true; // this.textView = textView; // handler.sendEmptyMessage(what); // } // // public void stop() { // running = false; // this.textView = null; // } // // @Override // public void setAlpha(int alpha) { // paint.setAlpha(alpha); // } // // @Override // public void setColorFilter(ColorFilter colorFilter) { // paint.setColorFilter(colorFilter); // } // // @Override // public int getIntrinsicHeight() { // return height; // } // // @Override // public int getIntrinsicWidth() { // return width; // } // // @Override // public int getOpacity() { // return PixelFormat.TRANSLUCENT; // } // // public int getHeight() { // return height; // } // // public int getWidth() { // return width; // } // } // // Path: richtext/src/main/java/com/zzhoujay/richtext/exceptions/ImageWrapperMultiSourceException.java // public class ImageWrapperMultiSourceException extends IllegalArgumentException { // // private static final String MESSAGE = "GifDrawable和Bitmap有且只有一个为null"; // // public ImageWrapperMultiSourceException() { // super(MESSAGE); // } // // public ImageWrapperMultiSourceException(Throwable cause) { // super(MESSAGE, cause); // } // // } // Path: richtext/src/main/java/com/zzhoujay/richtext/ig/ImageWrapper.java import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import com.zzhoujay.richtext.callback.Recyclable; import com.zzhoujay.richtext.drawable.GifDrawable; import com.zzhoujay.richtext.exceptions.ImageWrapperMultiSourceException; package com.zzhoujay.richtext.ig; /** * Created by zhou on 2017/2/21. * 抽象的图片类,包含Bitmap静态图的Gif动态图 */ class ImageWrapper implements Recyclable { private final GifDrawable gifDrawable; private final Bitmap bitmap; private final int height; private final int width; private ImageWrapper(GifDrawable gifDrawable, Bitmap bitmap) { this.gifDrawable = gifDrawable; this.bitmap = bitmap; if (gifDrawable == null) { if (bitmap == null) {
throw new ImageWrapperMultiSourceException();
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/FontHelper.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // }
import android.content.res.Resources; import nich.work.aequorea.Aequorea; import nich.work.aequorea.R;
package nich.work.aequorea.common.utils; public class FontHelper { private static int mDefaultSize = -1; private static int mDefaultFontSpacing = -1; private static final String FONT_SIZE = "font_size"; private static final String FONT_FAMILY = "font_family"; private static final String FONT_SPACING = "font_spacing"; public static final String SERIF = "serif"; public static final String MONOSPACE = "monospace"; public static final String SANS_SERIF = "sans_serif"; private static final int MAX_FONT_SIZE = 24; private static final int MIN_FONT_SIZE = 10; private static final int MAX_SPACING = 10; private static final int MIN_SPACING = 1; public static int getFontSize() { return SPUtils.getInt(FONT_SIZE, getDefaultSize()); } private static int getDefaultSize() { if (mDefaultSize == -1) {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // Path: app/src/main/java/nich/work/aequorea/common/utils/FontHelper.java import android.content.res.Resources; import nich.work.aequorea.Aequorea; import nich.work.aequorea.R; package nich.work.aequorea.common.utils; public class FontHelper { private static int mDefaultSize = -1; private static int mDefaultFontSpacing = -1; private static final String FONT_SIZE = "font_size"; private static final String FONT_FAMILY = "font_family"; private static final String FONT_SPACING = "font_spacing"; public static final String SERIF = "serif"; public static final String MONOSPACE = "monospace"; public static final String SANS_SERIF = "sans_serif"; private static final int MAX_FONT_SIZE = 24; private static final int MIN_FONT_SIZE = 10; private static final int MAX_SPACING = 10; private static final int MIN_SPACING = 1; public static int getFontSize() { return SPUtils.getInt(FONT_SIZE, getDefaultSize()); } private static int getDefaultSize() { if (mDefaultSize == -1) {
Resources r = Aequorea.getApp().getResources();
nichbar/Aequorea
richtext/src/main/java/com/zzhoujay/richtext/ImageHolder.java
// Path: richtext/src/main/java/com/zzhoujay/richtext/ext/MD5.java // public class MD5 { // // public static String generate(String source) { // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(source.getBytes()); // return new BigInteger(1, messageDigest.digest()).toString(16); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return source; // } // // }
import android.graphics.Color; import androidx.annotation.ColorInt; import androidx.annotation.IntDef; import com.zzhoujay.richtext.exceptions.ResetImageSourceException; import com.zzhoujay.richtext.ext.MD5; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;
height = WRAP_CONTENT; scaleType = ScaleType.FIT_AUTO; } else { scaleType = config.scaleType; width = config.width; height = config.height; } this.show = !config.noImage; setShowBorder(config.borderHolder.showBorder); setBorderColor(config.borderHolder.borderColor); setBorderSize(config.borderHolder.borderSize); setBorderRadius(config.borderHolder.radius); configHashCode = config.hashCode(); generateKey(); } private ImageHolder(String source, int position) { this.source = source; this.position = position; width = WRAP_CONTENT; height = WRAP_CONTENT; scaleType = ScaleType.NONE; autoPlay = false; show = true; this.isGif = false; this.borderHolder = new BorderHolder(); generateKey(); } private void generateKey() {
// Path: richtext/src/main/java/com/zzhoujay/richtext/ext/MD5.java // public class MD5 { // // public static String generate(String source) { // try { // MessageDigest messageDigest = MessageDigest.getInstance("MD5"); // messageDigest.update(source.getBytes()); // return new BigInteger(1, messageDigest.digest()).toString(16); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } // return source; // } // // } // Path: richtext/src/main/java/com/zzhoujay/richtext/ImageHolder.java import android.graphics.Color; import androidx.annotation.ColorInt; import androidx.annotation.IntDef; import com.zzhoujay.richtext.exceptions.ResetImageSourceException; import com.zzhoujay.richtext.ext.MD5; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; height = WRAP_CONTENT; scaleType = ScaleType.FIT_AUTO; } else { scaleType = config.scaleType; width = config.width; height = config.height; } this.show = !config.noImage; setShowBorder(config.borderHolder.showBorder); setBorderColor(config.borderHolder.borderColor); setBorderSize(config.borderHolder.borderSize); setBorderRadius(config.borderHolder.radius); configHashCode = config.hashCode(); generateKey(); } private ImageHolder(String source, int position) { this.source = source; this.position = position; width = WRAP_CONTENT; height = WRAP_CONTENT; scaleType = ScaleType.NONE; autoPlay = false; show = true; this.isGif = false; this.borderHolder = new BorderHolder(); generateKey(); } private void generateKey() {
this.key = MD5.generate(source);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/ui/view/SimpleArticleListView.java
// Path: app/src/main/java/nich/work/aequorea/common/ui/view/NetworkView.java // public interface NetworkView extends BaseView { // void onError(Throwable error); // } // // Path: app/src/main/java/nich/work/aequorea/model/SimpleArticleListModel.java // public class SimpleArticleListModel extends BaseModel { // private int mId; // private String mKey; // private String mTitle; // // public int getId() { // return mId; // } // // public void setId(int id) { // this.mId = id; // } // // public String getKey() { // return mKey; // } // // public void setKey(String key) { // this.mKey = key; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // this.mTitle = title; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Author.java // public class Author implements Serializable { // // @SerializedName("avatar") // private String mAvatar; // @SerializedName("data") // private List<Datum> mData; // @SerializedName("id") // private Long mId; // @SerializedName("introduction") // private String mIntroduction; // @SerializedName("meta") // private Meta mMeta; // @SerializedName("name") // private String mName; // @SerializedName("role") // private Object mRole; // @SerializedName("articles_count") // private Long mArticleCount; // // public String getAvatar() { // return mAvatar; // } // // public void setAvatar(String avatar) { // mAvatar = avatar; // } // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Long getId() { // return mId; // } // // public void setId(Long id) { // mId = id; // } // // public String getIntroduction() { // return mIntroduction; // } // // public void setIntroduction(String introduction) { // mIntroduction = introduction; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public Object getRole() { // return mRole; // } // // public void setRole(Object role) { // mRole = role; // } // // public Long getArticleCount() { // return mArticleCount; // } // // public void setArticleCount(Long mArticleCount) { // this.mArticleCount = mArticleCount; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // }
import nich.work.aequorea.common.ui.view.NetworkView; import nich.work.aequorea.model.SimpleArticleListModel; import nich.work.aequorea.model.entity.Author; import nich.work.aequorea.model.entity.Data;
package nich.work.aequorea.ui.view; public interface SimpleArticleListView extends NetworkView { void onDataLoaded(Data data); void onNoData();
// Path: app/src/main/java/nich/work/aequorea/common/ui/view/NetworkView.java // public interface NetworkView extends BaseView { // void onError(Throwable error); // } // // Path: app/src/main/java/nich/work/aequorea/model/SimpleArticleListModel.java // public class SimpleArticleListModel extends BaseModel { // private int mId; // private String mKey; // private String mTitle; // // public int getId() { // return mId; // } // // public void setId(int id) { // this.mId = id; // } // // public String getKey() { // return mKey; // } // // public void setKey(String key) { // this.mKey = key; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // this.mTitle = title; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Author.java // public class Author implements Serializable { // // @SerializedName("avatar") // private String mAvatar; // @SerializedName("data") // private List<Datum> mData; // @SerializedName("id") // private Long mId; // @SerializedName("introduction") // private String mIntroduction; // @SerializedName("meta") // private Meta mMeta; // @SerializedName("name") // private String mName; // @SerializedName("role") // private Object mRole; // @SerializedName("articles_count") // private Long mArticleCount; // // public String getAvatar() { // return mAvatar; // } // // public void setAvatar(String avatar) { // mAvatar = avatar; // } // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Long getId() { // return mId; // } // // public void setId(Long id) { // mId = id; // } // // public String getIntroduction() { // return mIntroduction; // } // // public void setIntroduction(String introduction) { // mIntroduction = introduction; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public Object getRole() { // return mRole; // } // // public void setRole(Object role) { // mRole = role; // } // // public Long getArticleCount() { // return mArticleCount; // } // // public void setArticleCount(Long mArticleCount) { // this.mArticleCount = mArticleCount; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // Path: app/src/main/java/nich/work/aequorea/ui/view/SimpleArticleListView.java import nich.work.aequorea.common.ui.view.NetworkView; import nich.work.aequorea.model.SimpleArticleListModel; import nich.work.aequorea.model.entity.Author; import nich.work.aequorea.model.entity.Data; package nich.work.aequorea.ui.view; public interface SimpleArticleListView extends NetworkView { void onDataLoaded(Data data); void onNoData();
void onUpdateAuthorInfo(Author author);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/ui/view/SimpleArticleListView.java
// Path: app/src/main/java/nich/work/aequorea/common/ui/view/NetworkView.java // public interface NetworkView extends BaseView { // void onError(Throwable error); // } // // Path: app/src/main/java/nich/work/aequorea/model/SimpleArticleListModel.java // public class SimpleArticleListModel extends BaseModel { // private int mId; // private String mKey; // private String mTitle; // // public int getId() { // return mId; // } // // public void setId(int id) { // this.mId = id; // } // // public String getKey() { // return mKey; // } // // public void setKey(String key) { // this.mKey = key; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // this.mTitle = title; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Author.java // public class Author implements Serializable { // // @SerializedName("avatar") // private String mAvatar; // @SerializedName("data") // private List<Datum> mData; // @SerializedName("id") // private Long mId; // @SerializedName("introduction") // private String mIntroduction; // @SerializedName("meta") // private Meta mMeta; // @SerializedName("name") // private String mName; // @SerializedName("role") // private Object mRole; // @SerializedName("articles_count") // private Long mArticleCount; // // public String getAvatar() { // return mAvatar; // } // // public void setAvatar(String avatar) { // mAvatar = avatar; // } // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Long getId() { // return mId; // } // // public void setId(Long id) { // mId = id; // } // // public String getIntroduction() { // return mIntroduction; // } // // public void setIntroduction(String introduction) { // mIntroduction = introduction; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public Object getRole() { // return mRole; // } // // public void setRole(Object role) { // mRole = role; // } // // public Long getArticleCount() { // return mArticleCount; // } // // public void setArticleCount(Long mArticleCount) { // this.mArticleCount = mArticleCount; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // }
import nich.work.aequorea.common.ui.view.NetworkView; import nich.work.aequorea.model.SimpleArticleListModel; import nich.work.aequorea.model.entity.Author; import nich.work.aequorea.model.entity.Data;
package nich.work.aequorea.ui.view; public interface SimpleArticleListView extends NetworkView { void onDataLoaded(Data data); void onNoData(); void onUpdateAuthorInfo(Author author);
// Path: app/src/main/java/nich/work/aequorea/common/ui/view/NetworkView.java // public interface NetworkView extends BaseView { // void onError(Throwable error); // } // // Path: app/src/main/java/nich/work/aequorea/model/SimpleArticleListModel.java // public class SimpleArticleListModel extends BaseModel { // private int mId; // private String mKey; // private String mTitle; // // public int getId() { // return mId; // } // // public void setId(int id) { // this.mId = id; // } // // public String getKey() { // return mKey; // } // // public void setKey(String key) { // this.mKey = key; // } // // public String getTitle() { // return mTitle; // } // // public void setTitle(String title) { // this.mTitle = title; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Author.java // public class Author implements Serializable { // // @SerializedName("avatar") // private String mAvatar; // @SerializedName("data") // private List<Datum> mData; // @SerializedName("id") // private Long mId; // @SerializedName("introduction") // private String mIntroduction; // @SerializedName("meta") // private Meta mMeta; // @SerializedName("name") // private String mName; // @SerializedName("role") // private Object mRole; // @SerializedName("articles_count") // private Long mArticleCount; // // public String getAvatar() { // return mAvatar; // } // // public void setAvatar(String avatar) { // mAvatar = avatar; // } // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Long getId() { // return mId; // } // // public void setId(Long id) { // mId = id; // } // // public String getIntroduction() { // return mIntroduction; // } // // public void setIntroduction(String introduction) { // mIntroduction = introduction; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public Object getRole() { // return mRole; // } // // public void setRole(Object role) { // mRole = role; // } // // public Long getArticleCount() { // return mArticleCount; // } // // public void setArticleCount(Long mArticleCount) { // this.mArticleCount = mArticleCount; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // Path: app/src/main/java/nich/work/aequorea/ui/view/SimpleArticleListView.java import nich.work.aequorea.common.ui.view.NetworkView; import nich.work.aequorea.model.SimpleArticleListModel; import nich.work.aequorea.model.entity.Author; import nich.work.aequorea.model.entity.Data; package nich.work.aequorea.ui.view; public interface SimpleArticleListView extends NetworkView { void onDataLoaded(Data data); void onNoData(); void onUpdateAuthorInfo(Author author);
SimpleArticleListModel getModel();
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/network/NetworkService.java
// Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/DataWrapper.java // public class DataWrapper { // // @SerializedName("data") // private Datum mData; // // public Datum getData() { // return mData; // } // // public void setData(Datum data) { // mData = data; // } // // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java // public class SearchData { // // @SerializedName("data") // private List<SearchDatum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<SearchDatum> getData() { // return mData; // } // // public void setData(List<SearchDatum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // }
import io.reactivex.Observable; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.DataWrapper; import nich.work.aequorea.model.entity.search.SearchData; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query;
package nich.work.aequorea.common.network; public interface NetworkService { // main page @GET("/v4/first_page_infos")
// Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/DataWrapper.java // public class DataWrapper { // // @SerializedName("data") // private Datum mData; // // public Datum getData() { // return mData; // } // // public void setData(Datum data) { // mData = data; // } // // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java // public class SearchData { // // @SerializedName("data") // private List<SearchDatum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<SearchDatum> getData() { // return mData; // } // // public void setData(List<SearchDatum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // } // Path: app/src/main/java/nich/work/aequorea/common/network/NetworkService.java import io.reactivex.Observable; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.DataWrapper; import nich.work.aequorea.model.entity.search.SearchData; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; package nich.work.aequorea.common.network; public interface NetworkService { // main page @GET("/v4/first_page_infos")
Observable<Data> getMainPageInfo(@Query("page") int page, @Query("per") int per);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/network/NetworkService.java
// Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/DataWrapper.java // public class DataWrapper { // // @SerializedName("data") // private Datum mData; // // public Datum getData() { // return mData; // } // // public void setData(Datum data) { // mData = data; // } // // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java // public class SearchData { // // @SerializedName("data") // private List<SearchDatum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<SearchDatum> getData() { // return mData; // } // // public void setData(List<SearchDatum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // }
import io.reactivex.Observable; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.DataWrapper; import nich.work.aequorea.model.entity.search.SearchData; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query;
package nich.work.aequorea.common.network; public interface NetworkService { // main page @GET("/v4/first_page_infos") Observable<Data> getMainPageInfo(@Query("page") int page, @Query("per") int per); // article details @GET("/v4/articles/{article_id}/")
// Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/DataWrapper.java // public class DataWrapper { // // @SerializedName("data") // private Datum mData; // // public Datum getData() { // return mData; // } // // public void setData(Datum data) { // mData = data; // } // // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java // public class SearchData { // // @SerializedName("data") // private List<SearchDatum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<SearchDatum> getData() { // return mData; // } // // public void setData(List<SearchDatum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // } // Path: app/src/main/java/nich/work/aequorea/common/network/NetworkService.java import io.reactivex.Observable; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.DataWrapper; import nich.work.aequorea.model.entity.search.SearchData; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; package nich.work.aequorea.common.network; public interface NetworkService { // main page @GET("/v4/first_page_infos") Observable<Data> getMainPageInfo(@Query("page") int page, @Query("per") int per); // article details @GET("/v4/articles/{article_id}/")
Observable<DataWrapper> getArticleDetailInfo(@Path("article_id") long articleId);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/network/NetworkService.java
// Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/DataWrapper.java // public class DataWrapper { // // @SerializedName("data") // private Datum mData; // // public Datum getData() { // return mData; // } // // public void setData(Datum data) { // mData = data; // } // // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java // public class SearchData { // // @SerializedName("data") // private List<SearchDatum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<SearchDatum> getData() { // return mData; // } // // public void setData(List<SearchDatum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // }
import io.reactivex.Observable; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.DataWrapper; import nich.work.aequorea.model.entity.search.SearchData; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query;
package nich.work.aequorea.common.network; public interface NetworkService { // main page @GET("/v4/first_page_infos") Observable<Data> getMainPageInfo(@Query("page") int page, @Query("per") int per); // article details @GET("/v4/articles/{article_id}/") Observable<DataWrapper> getArticleDetailInfo(@Path("article_id") long articleId); // article that belonging to specific author @GET("/v4/authors/{author_id}/articles") Observable<Data> getArticleList(@Path("author_id") long authorId, @Query("page") int page, @Query("per") int per); // recommended article @GET("/v4/articles/{article_id}/recommendations") Observable<Data> getRecommendedArticle(@Path("article_id") long articleId); // article with tags @GET("v4/topics/{tag_id}/articles") Observable<Data> getTagsList(@Path("tag_id") long id, @Query("page") int page, @Query("per") int per); // article with keyword @GET("v4/pg_search_documents")
// Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/DataWrapper.java // public class DataWrapper { // // @SerializedName("data") // private Datum mData; // // public Datum getData() { // return mData; // } // // public void setData(Datum data) { // mData = data; // } // // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/search/SearchData.java // public class SearchData { // // @SerializedName("data") // private List<SearchDatum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<SearchDatum> getData() { // return mData; // } // // public void setData(List<SearchDatum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // } // Path: app/src/main/java/nich/work/aequorea/common/network/NetworkService.java import io.reactivex.Observable; import nich.work.aequorea.model.entity.Data; import nich.work.aequorea.model.entity.DataWrapper; import nich.work.aequorea.model.entity.search.SearchData; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; package nich.work.aequorea.common.network; public interface NetworkService { // main page @GET("/v4/first_page_infos") Observable<Data> getMainPageInfo(@Query("page") int page, @Query("per") int per); // article details @GET("/v4/articles/{article_id}/") Observable<DataWrapper> getArticleDetailInfo(@Path("article_id") long articleId); // article that belonging to specific author @GET("/v4/authors/{author_id}/articles") Observable<Data> getArticleList(@Path("author_id") long authorId, @Query("page") int page, @Query("per") int per); // recommended article @GET("/v4/articles/{article_id}/recommendations") Observable<Data> getRecommendedArticle(@Path("article_id") long articleId); // article with tags @GET("v4/topics/{tag_id}/articles") Observable<Data> getTagsList(@Path("tag_id") long id, @Query("page") int page, @Query("per") int per); // article with keyword @GET("v4/pg_search_documents")
Observable<SearchData> getArticleListWithKeyword(@Query("page") int page, @Query("per") int per, @Query("query") String keyword, @Query("group") boolean group, @Query("type") String type);
nichbar/Aequorea
richtext/src/main/java/com/zzhoujay/richtext/spans/LongClickableURLSpan.java
// Path: richtext/src/main/java/com/zzhoujay/richtext/LinkHolder.java // @SuppressWarnings("unused") // public class LinkHolder { // // private final String url; // @ColorInt // private int color; // private boolean underLine; // // public LinkHolder(String url, int linkColor) { // this.url = url; // this.color = linkColor; // } // // @ColorInt // public int getColor() { // return color; // } // // public void setColor(@ColorInt int color) { // this.color = color; // } // // public boolean isUnderLine() { // return underLine; // } // // public void setUnderLine(boolean underLine) { // this.underLine = underLine; // } // // public String getUrl() { // return url; // } // }
import android.annotation.SuppressLint; import android.text.TextPaint; import android.text.style.URLSpan; import android.view.View; import com.zzhoujay.richtext.LinkHolder; import com.zzhoujay.richtext.callback.OnUrlClickListener; import com.zzhoujay.richtext.callback.OnUrlLongClickListener; import java.lang.ref.WeakReference;
package com.zzhoujay.richtext.spans; /** * Created by zhou on 16-5-28. * LongClickableURLSpan */ @SuppressLint("ParcelCreator") public class LongClickableURLSpan extends URLSpan implements LongClickableSpan { private final WeakReference<OnUrlClickListener> onUrlClickListenerWeakReference; private final WeakReference<OnUrlLongClickListener> onUrlLongClickListenerWeakReference;
// Path: richtext/src/main/java/com/zzhoujay/richtext/LinkHolder.java // @SuppressWarnings("unused") // public class LinkHolder { // // private final String url; // @ColorInt // private int color; // private boolean underLine; // // public LinkHolder(String url, int linkColor) { // this.url = url; // this.color = linkColor; // } // // @ColorInt // public int getColor() { // return color; // } // // public void setColor(@ColorInt int color) { // this.color = color; // } // // public boolean isUnderLine() { // return underLine; // } // // public void setUnderLine(boolean underLine) { // this.underLine = underLine; // } // // public String getUrl() { // return url; // } // } // Path: richtext/src/main/java/com/zzhoujay/richtext/spans/LongClickableURLSpan.java import android.annotation.SuppressLint; import android.text.TextPaint; import android.text.style.URLSpan; import android.view.View; import com.zzhoujay.richtext.LinkHolder; import com.zzhoujay.richtext.callback.OnUrlClickListener; import com.zzhoujay.richtext.callback.OnUrlLongClickListener; import java.lang.ref.WeakReference; package com.zzhoujay.richtext.spans; /** * Created by zhou on 16-5-28. * LongClickableURLSpan */ @SuppressLint("ParcelCreator") public class LongClickableURLSpan extends URLSpan implements LongClickableSpan { private final WeakReference<OnUrlClickListener> onUrlClickListenerWeakReference; private final WeakReference<OnUrlLongClickListener> onUrlLongClickListenerWeakReference;
private final LinkHolder linkHolder;
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/ToastUtils.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // }
import android.widget.Toast; import nich.work.aequorea.Aequorea;
package nich.work.aequorea.common.utils; public class ToastUtils { private static Toast mToast; public static void showShortToast(String text) { if (mToast == null) {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // Path: app/src/main/java/nich/work/aequorea/common/utils/ToastUtils.java import android.widget.Toast; import nich.work.aequorea.Aequorea; package nich.work.aequorea.common.utils; public class ToastUtils { private static Toast mToast; public static void showShortToast(String text) { if (mToast == null) {
mToast = Toast.makeText(Aequorea.getApp(), text, Toast.LENGTH_SHORT);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/presenter/TagPresenter.java
// Path: app/src/main/java/nich/work/aequorea/common/utils/NetworkUtils.java // public class NetworkUtils { // // public static boolean isNetworkAvailable() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // return info != null && info.isAvailable(); // } // // public static boolean isWiFiNetwork() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // // return info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isAvailable(); // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // }
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import nich.work.aequorea.R; import nich.work.aequorea.common.utils.NetworkUtils; import nich.work.aequorea.model.entity.Data;
package nich.work.aequorea.presenter; public class TagPresenter extends SimpleArticleListPresenter { @Override public void load() {
// Path: app/src/main/java/nich/work/aequorea/common/utils/NetworkUtils.java // public class NetworkUtils { // // public static boolean isNetworkAvailable() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // return info != null && info.isAvailable(); // } // // public static boolean isWiFiNetwork() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // // return info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isAvailable(); // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // Path: app/src/main/java/nich/work/aequorea/presenter/TagPresenter.java import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import nich.work.aequorea.R; import nich.work.aequorea.common.utils.NetworkUtils; import nich.work.aequorea.model.entity.Data; package nich.work.aequorea.presenter; public class TagPresenter extends SimpleArticleListPresenter { @Override public void load() {
if (!NetworkUtils.isNetworkAvailable()) {
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/presenter/TagPresenter.java
// Path: app/src/main/java/nich/work/aequorea/common/utils/NetworkUtils.java // public class NetworkUtils { // // public static boolean isNetworkAvailable() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // return info != null && info.isAvailable(); // } // // public static boolean isWiFiNetwork() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // // return info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isAvailable(); // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // }
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import nich.work.aequorea.R; import nich.work.aequorea.common.utils.NetworkUtils; import nich.work.aequorea.model.entity.Data;
package nich.work.aequorea.presenter; public class TagPresenter extends SimpleArticleListPresenter { @Override public void load() { if (!NetworkUtils.isNetworkAvailable()) { onError(new Throwable(getString(R.string.please_connect_to_the_internet))); return; } if (mPage > mTotalPage || mBaseView.getModel().isLoading()) { return; } mBaseView.getModel().setLoading(true); mComposite.add(mService.getTagsList(mBaseView.getModel().getId(), mPage, mPer) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())
// Path: app/src/main/java/nich/work/aequorea/common/utils/NetworkUtils.java // public class NetworkUtils { // // public static boolean isNetworkAvailable() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // return info != null && info.isAvailable(); // } // // public static boolean isWiFiNetwork() { // Context context = Aequorea.getApp(); // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // // NetworkInfo info = null; // if (connectivityManager != null) { // info = connectivityManager.getActiveNetworkInfo(); // } // // return info != null && info.getType() == ConnectivityManager.TYPE_WIFI && info.isAvailable(); // } // } // // Path: app/src/main/java/nich/work/aequorea/model/entity/Data.java // public class Data { // // @SerializedName("data") // private List<Datum> mData; // @SerializedName("meta") // private Meta mMeta; // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // } // Path: app/src/main/java/nich/work/aequorea/presenter/TagPresenter.java import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import nich.work.aequorea.R; import nich.work.aequorea.common.utils.NetworkUtils; import nich.work.aequorea.model.entity.Data; package nich.work.aequorea.presenter; public class TagPresenter extends SimpleArticleListPresenter { @Override public void load() { if (!NetworkUtils.isNetworkAvailable()) { onError(new Throwable(getString(R.string.please_connect_to_the_internet))); return; } if (mPage > mTotalPage || mBaseView.getModel().isLoading()) { return; } mBaseView.getModel().setLoading(true); mComposite.add(mService.getTagsList(mBaseView.getModel().getId(), mPage, mPer) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Data>() {
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/cache/ArticleCache.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // }
import android.util.LruCache; import com.jakewharton.disklrucache.DiskLruCache; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import nich.work.aequorea.Aequorea; import nich.work.aequorea.BuildConfig; import nich.work.aequorea.common.Constants;
package nich.work.aequorea.common.cache; public class ArticleCache { private static final int MAX_CACHED_MEMORY_ARTICLE_SIZE = 20; private static final int MAX_CACHED_DISK_ARTICLE_SIZE = 1024 * 1024 * 10; // 10M private final LruCache<Long, String> mCache; private DiskLruCache mDiskCache; private ArticleCache() { this.mCache = new LruCache<>(MAX_CACHED_MEMORY_ARTICLE_SIZE); initDiskCache(); } private void initDiskCache() {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // Path: app/src/main/java/nich/work/aequorea/common/cache/ArticleCache.java import android.util.LruCache; import com.jakewharton.disklrucache.DiskLruCache; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import nich.work.aequorea.Aequorea; import nich.work.aequorea.BuildConfig; import nich.work.aequorea.common.Constants; package nich.work.aequorea.common.cache; public class ArticleCache { private static final int MAX_CACHED_MEMORY_ARTICLE_SIZE = 20; private static final int MAX_CACHED_DISK_ARTICLE_SIZE = 1024 * 1024 * 10; // 10M private final LruCache<Long, String> mCache; private DiskLruCache mDiskCache; private ArticleCache() { this.mCache = new LruCache<>(MAX_CACHED_MEMORY_ARTICLE_SIZE); initDiskCache(); } private void initDiskCache() {
Aequorea.getExecutor().execute(new Runnable() {
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/cache/ArticleCache.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // }
import android.util.LruCache; import com.jakewharton.disklrucache.DiskLruCache; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import nich.work.aequorea.Aequorea; import nich.work.aequorea.BuildConfig; import nich.work.aequorea.common.Constants;
package nich.work.aequorea.common.cache; public class ArticleCache { private static final int MAX_CACHED_MEMORY_ARTICLE_SIZE = 20; private static final int MAX_CACHED_DISK_ARTICLE_SIZE = 1024 * 1024 * 10; // 10M private final LruCache<Long, String> mCache; private DiskLruCache mDiskCache; private ArticleCache() { this.mCache = new LruCache<>(MAX_CACHED_MEMORY_ARTICLE_SIZE); initDiskCache(); } private void initDiskCache() { Aequorea.getExecutor().execute(new Runnable() { @Override public void run() { try {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // Path: app/src/main/java/nich/work/aequorea/common/cache/ArticleCache.java import android.util.LruCache; import com.jakewharton.disklrucache.DiskLruCache; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import nich.work.aequorea.Aequorea; import nich.work.aequorea.BuildConfig; import nich.work.aequorea.common.Constants; package nich.work.aequorea.common.cache; public class ArticleCache { private static final int MAX_CACHED_MEMORY_ARTICLE_SIZE = 20; private static final int MAX_CACHED_DISK_ARTICLE_SIZE = 1024 * 1024 * 10; // 10M private final LruCache<Long, String> mCache; private DiskLruCache mDiskCache; private ArticleCache() { this.mCache = new LruCache<>(MAX_CACHED_MEMORY_ARTICLE_SIZE); initDiskCache(); } private void initDiskCache() { Aequorea.getExecutor().execute(new Runnable() { @Override public void run() { try {
File cacheDir = new File(Aequorea.getApp().getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_CACHE);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/ThemeHelper.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // }
import android.content.Context; import androidx.core.content.ContextCompat; import android.util.TypedValue; import nich.work.aequorea.Aequorea; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants;
package nich.work.aequorea.common.utils; public class ThemeHelper { public static String getTheme() {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // Path: app/src/main/java/nich/work/aequorea/common/utils/ThemeHelper.java import android.content.Context; import androidx.core.content.ContextCompat; import android.util.TypedValue; import nich.work.aequorea.Aequorea; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; package nich.work.aequorea.common.utils; public class ThemeHelper { public static String getTheme() {
String theme = SPUtils.getString(Constants.THEME);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/ThemeHelper.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // }
import android.content.Context; import androidx.core.content.ContextCompat; import android.util.TypedValue; import nich.work.aequorea.Aequorea; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants;
package nich.work.aequorea.common.utils; public class ThemeHelper { public static String getTheme() { String theme = SPUtils.getString(Constants.THEME); return "".equals(theme) ? Constants.THEME_LIGHT : theme; } public static void setTheme(String theme) { SPUtils.setString(Constants.THEME, theme);
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // Path: app/src/main/java/nich/work/aequorea/common/utils/ThemeHelper.java import android.content.Context; import androidx.core.content.ContextCompat; import android.util.TypedValue; import nich.work.aequorea.Aequorea; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; package nich.work.aequorea.common.utils; public class ThemeHelper { public static String getTheme() { String theme = SPUtils.getString(Constants.THEME); return "".equals(theme) ? Constants.THEME_LIGHT : theme; } public static void setTheme(String theme) { SPUtils.setString(Constants.THEME, theme);
Aequorea.setCurrentTheme(theme);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/presenter/BasePresenter.java
// Path: app/src/main/java/nich/work/aequorea/common/rx/RxBus.java // public class RxBus { // private final Subject<Object> mBus; // // private RxBus() { // mBus = PublishSubject.create().toSerialized(); // } // // public static RxBus getInstance() { // return RxBusHolder.RX_BUS_INSTANCE; // } // // public void post(int type) { // post(type, null); // } // // public void post(int type, @Nullable Object data) { // mBus.onNext(new RxEvent<>(type, data)); // } // // public Observable<Object> toObservable() { // return mBus; // } // // public <T> Observable<T> toObservable(Class<T> type) { // return mBus.ofType(type); // } // // public <T> Observable<T> toObservable(final int type, final Class<T> clazz) { // return mBus.ofType(RxEvent.class).filter(new Predicate<RxEvent>() { // @Override // public boolean test(@NonNull RxEvent event) throws Exception { // return event.getType() == type; // } // }).cast(clazz).observeOn(AndroidSchedulers.mainThread()); // } // // private static class RxBusHolder { // private static final RxBus RX_BUS_INSTANCE = new RxBus(); // } // } // // Path: app/src/main/java/nich/work/aequorea/common/rx/RxEvent.java // public class RxEvent<T> { // public static final int EVENT_TYPE_CHANGE_THEME = 1; // // private int mCode; // private T mData; // // public RxEvent(int type, T data) { // mCode = type; // mData = data; // } // // public int getType() { // return mCode; // } // // public void setType(int mCode) { // this.mCode = mCode; // } // // public T getData() { // return mData; // } // // public void setData(T data) { // mData = data; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/ui/view/BaseView.java // public interface BaseView { // void onThemeSwitch(); // void onThemeSwitchPending(); // }
import android.content.Context; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import nich.work.aequorea.common.rx.RxBus; import nich.work.aequorea.common.rx.RxEvent; import nich.work.aequorea.common.ui.view.BaseView;
package nich.work.aequorea.common.presenter; public abstract class BasePresenter<T extends BaseView> { protected T mBaseView; protected CompositeDisposable mComposite; public void attach(T view) { mBaseView = view; mComposite = new CompositeDisposable();
// Path: app/src/main/java/nich/work/aequorea/common/rx/RxBus.java // public class RxBus { // private final Subject<Object> mBus; // // private RxBus() { // mBus = PublishSubject.create().toSerialized(); // } // // public static RxBus getInstance() { // return RxBusHolder.RX_BUS_INSTANCE; // } // // public void post(int type) { // post(type, null); // } // // public void post(int type, @Nullable Object data) { // mBus.onNext(new RxEvent<>(type, data)); // } // // public Observable<Object> toObservable() { // return mBus; // } // // public <T> Observable<T> toObservable(Class<T> type) { // return mBus.ofType(type); // } // // public <T> Observable<T> toObservable(final int type, final Class<T> clazz) { // return mBus.ofType(RxEvent.class).filter(new Predicate<RxEvent>() { // @Override // public boolean test(@NonNull RxEvent event) throws Exception { // return event.getType() == type; // } // }).cast(clazz).observeOn(AndroidSchedulers.mainThread()); // } // // private static class RxBusHolder { // private static final RxBus RX_BUS_INSTANCE = new RxBus(); // } // } // // Path: app/src/main/java/nich/work/aequorea/common/rx/RxEvent.java // public class RxEvent<T> { // public static final int EVENT_TYPE_CHANGE_THEME = 1; // // private int mCode; // private T mData; // // public RxEvent(int type, T data) { // mCode = type; // mData = data; // } // // public int getType() { // return mCode; // } // // public void setType(int mCode) { // this.mCode = mCode; // } // // public T getData() { // return mData; // } // // public void setData(T data) { // mData = data; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/ui/view/BaseView.java // public interface BaseView { // void onThemeSwitch(); // void onThemeSwitchPending(); // } // Path: app/src/main/java/nich/work/aequorea/common/presenter/BasePresenter.java import android.content.Context; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import nich.work.aequorea.common.rx.RxBus; import nich.work.aequorea.common.rx.RxEvent; import nich.work.aequorea.common.ui.view.BaseView; package nich.work.aequorea.common.presenter; public abstract class BasePresenter<T extends BaseView> { protected T mBaseView; protected CompositeDisposable mComposite; public void attach(T view) { mBaseView = view; mComposite = new CompositeDisposable();
addSubscription(RxEvent.EVENT_TYPE_CHANGE_THEME, new Consumer<RxEvent>() {
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/presenter/BasePresenter.java
// Path: app/src/main/java/nich/work/aequorea/common/rx/RxBus.java // public class RxBus { // private final Subject<Object> mBus; // // private RxBus() { // mBus = PublishSubject.create().toSerialized(); // } // // public static RxBus getInstance() { // return RxBusHolder.RX_BUS_INSTANCE; // } // // public void post(int type) { // post(type, null); // } // // public void post(int type, @Nullable Object data) { // mBus.onNext(new RxEvent<>(type, data)); // } // // public Observable<Object> toObservable() { // return mBus; // } // // public <T> Observable<T> toObservable(Class<T> type) { // return mBus.ofType(type); // } // // public <T> Observable<T> toObservable(final int type, final Class<T> clazz) { // return mBus.ofType(RxEvent.class).filter(new Predicate<RxEvent>() { // @Override // public boolean test(@NonNull RxEvent event) throws Exception { // return event.getType() == type; // } // }).cast(clazz).observeOn(AndroidSchedulers.mainThread()); // } // // private static class RxBusHolder { // private static final RxBus RX_BUS_INSTANCE = new RxBus(); // } // } // // Path: app/src/main/java/nich/work/aequorea/common/rx/RxEvent.java // public class RxEvent<T> { // public static final int EVENT_TYPE_CHANGE_THEME = 1; // // private int mCode; // private T mData; // // public RxEvent(int type, T data) { // mCode = type; // mData = data; // } // // public int getType() { // return mCode; // } // // public void setType(int mCode) { // this.mCode = mCode; // } // // public T getData() { // return mData; // } // // public void setData(T data) { // mData = data; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/ui/view/BaseView.java // public interface BaseView { // void onThemeSwitch(); // void onThemeSwitchPending(); // }
import android.content.Context; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import nich.work.aequorea.common.rx.RxBus; import nich.work.aequorea.common.rx.RxEvent; import nich.work.aequorea.common.ui.view.BaseView;
package nich.work.aequorea.common.presenter; public abstract class BasePresenter<T extends BaseView> { protected T mBaseView; protected CompositeDisposable mComposite; public void attach(T view) { mBaseView = view; mComposite = new CompositeDisposable(); addSubscription(RxEvent.EVENT_TYPE_CHANGE_THEME, new Consumer<RxEvent>() { @Override public void accept(RxEvent rxEvent) throws Exception { mBaseView.onThemeSwitch(); } }); onAttach(); } protected void onAttach() { // do nothing } protected void addSubscription(int type, Consumer<RxEvent> consumer) {
// Path: app/src/main/java/nich/work/aequorea/common/rx/RxBus.java // public class RxBus { // private final Subject<Object> mBus; // // private RxBus() { // mBus = PublishSubject.create().toSerialized(); // } // // public static RxBus getInstance() { // return RxBusHolder.RX_BUS_INSTANCE; // } // // public void post(int type) { // post(type, null); // } // // public void post(int type, @Nullable Object data) { // mBus.onNext(new RxEvent<>(type, data)); // } // // public Observable<Object> toObservable() { // return mBus; // } // // public <T> Observable<T> toObservable(Class<T> type) { // return mBus.ofType(type); // } // // public <T> Observable<T> toObservable(final int type, final Class<T> clazz) { // return mBus.ofType(RxEvent.class).filter(new Predicate<RxEvent>() { // @Override // public boolean test(@NonNull RxEvent event) throws Exception { // return event.getType() == type; // } // }).cast(clazz).observeOn(AndroidSchedulers.mainThread()); // } // // private static class RxBusHolder { // private static final RxBus RX_BUS_INSTANCE = new RxBus(); // } // } // // Path: app/src/main/java/nich/work/aequorea/common/rx/RxEvent.java // public class RxEvent<T> { // public static final int EVENT_TYPE_CHANGE_THEME = 1; // // private int mCode; // private T mData; // // public RxEvent(int type, T data) { // mCode = type; // mData = data; // } // // public int getType() { // return mCode; // } // // public void setType(int mCode) { // this.mCode = mCode; // } // // public T getData() { // return mData; // } // // public void setData(T data) { // mData = data; // } // } // // Path: app/src/main/java/nich/work/aequorea/common/ui/view/BaseView.java // public interface BaseView { // void onThemeSwitch(); // void onThemeSwitchPending(); // } // Path: app/src/main/java/nich/work/aequorea/common/presenter/BasePresenter.java import android.content.Context; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import nich.work.aequorea.common.rx.RxBus; import nich.work.aequorea.common.rx.RxEvent; import nich.work.aequorea.common.ui.view.BaseView; package nich.work.aequorea.common.presenter; public abstract class BasePresenter<T extends BaseView> { protected T mBaseView; protected CompositeDisposable mComposite; public void attach(T view) { mBaseView = view; mComposite = new CompositeDisposable(); addSubscription(RxEvent.EVENT_TYPE_CHANGE_THEME, new Consumer<RxEvent>() { @Override public void accept(RxEvent rxEvent) throws Exception { mBaseView.onThemeSwitch(); } }); onAttach(); } protected void onAttach() { // do nothing } protected void addSubscription(int type, Consumer<RxEvent> consumer) {
mComposite.add(RxBus.getInstance()
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/ui/widget/ACheckBox.java
// Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // // Path: app/src/main/java/nich/work/aequorea/common/utils/SPUtils.java // public class SPUtils { // private static SharedPreferences mSp; // // private static SharedPreferences getSp() { // if (mSp == null) { // mSp = Aequorea.getApp().getSharedPreferences("Aequorea", Context.MODE_PRIVATE); // } // return mSp; // } // // public static void setString(String key, String value) { // getSp().edit().putString(key, value).apply(); // } // // public static String getString(String key) { // return getSp().getString(key, ""); // } // // public static String getString(String key, String defaultValue) { // return getSp().getString(key, defaultValue); // } // // public static void setInt(String key, int value) { // getSp().edit().putInt(key, value).apply(); // } // // public static int getInt(String key) { // return getSp().getInt(key, 0); // } // // public static int getInt(String key, int defaultValue) { // return getSp().getInt(key, defaultValue); // } // // public static void setBoolean(String key, boolean value) { // getSp().edit().putBoolean(key, value).apply(); // } // // public static boolean getBoolean(String key) { // return getSp().getBoolean(key, false); // } // }
import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatCheckBox; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; import nich.work.aequorea.common.utils.SPUtils;
} public ACheckBox(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); View.inflate(context, R.layout.layout_custom_checkbox, this); init(context, attrs); setOnClickListener(this); } private void init(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ACheckBox); String title = typedArray.getString(R.styleable.ACheckBox_title); String summary = typedArray.getString(R.styleable.ACheckBox_summary); mCheckBox = findViewById(R.id.cb); mTitle = findViewById(R.id.tv_title); mSummary =findViewById(R.id.tv_summary); mTitle.setText(title); mSummary.setText(summary); typedArray.recycle(); } @Override public void onClick(View view) { if (mKey != null) { boolean checked = !mCheckBox.isChecked(); mCheckBox.setChecked(checked);
// Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // // Path: app/src/main/java/nich/work/aequorea/common/utils/SPUtils.java // public class SPUtils { // private static SharedPreferences mSp; // // private static SharedPreferences getSp() { // if (mSp == null) { // mSp = Aequorea.getApp().getSharedPreferences("Aequorea", Context.MODE_PRIVATE); // } // return mSp; // } // // public static void setString(String key, String value) { // getSp().edit().putString(key, value).apply(); // } // // public static String getString(String key) { // return getSp().getString(key, ""); // } // // public static String getString(String key, String defaultValue) { // return getSp().getString(key, defaultValue); // } // // public static void setInt(String key, int value) { // getSp().edit().putInt(key, value).apply(); // } // // public static int getInt(String key) { // return getSp().getInt(key, 0); // } // // public static int getInt(String key, int defaultValue) { // return getSp().getInt(key, defaultValue); // } // // public static void setBoolean(String key, boolean value) { // getSp().edit().putBoolean(key, value).apply(); // } // // public static boolean getBoolean(String key) { // return getSp().getBoolean(key, false); // } // } // Path: app/src/main/java/nich/work/aequorea/common/ui/widget/ACheckBox.java import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatCheckBox; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; import nich.work.aequorea.common.utils.SPUtils; } public ACheckBox(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); View.inflate(context, R.layout.layout_custom_checkbox, this); init(context, attrs); setOnClickListener(this); } private void init(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ACheckBox); String title = typedArray.getString(R.styleable.ACheckBox_title); String summary = typedArray.getString(R.styleable.ACheckBox_summary); mCheckBox = findViewById(R.id.cb); mTitle = findViewById(R.id.tv_title); mSummary =findViewById(R.id.tv_summary); mTitle.setText(title); mSummary.setText(summary); typedArray.recycle(); } @Override public void onClick(View view) { if (mKey != null) { boolean checked = !mCheckBox.isChecked(); mCheckBox.setChecked(checked);
if (!mKey.equals(Constants.THEME)) {
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/ui/widget/ACheckBox.java
// Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // // Path: app/src/main/java/nich/work/aequorea/common/utils/SPUtils.java // public class SPUtils { // private static SharedPreferences mSp; // // private static SharedPreferences getSp() { // if (mSp == null) { // mSp = Aequorea.getApp().getSharedPreferences("Aequorea", Context.MODE_PRIVATE); // } // return mSp; // } // // public static void setString(String key, String value) { // getSp().edit().putString(key, value).apply(); // } // // public static String getString(String key) { // return getSp().getString(key, ""); // } // // public static String getString(String key, String defaultValue) { // return getSp().getString(key, defaultValue); // } // // public static void setInt(String key, int value) { // getSp().edit().putInt(key, value).apply(); // } // // public static int getInt(String key) { // return getSp().getInt(key, 0); // } // // public static int getInt(String key, int defaultValue) { // return getSp().getInt(key, defaultValue); // } // // public static void setBoolean(String key, boolean value) { // getSp().edit().putBoolean(key, value).apply(); // } // // public static boolean getBoolean(String key) { // return getSp().getBoolean(key, false); // } // }
import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatCheckBox; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; import nich.work.aequorea.common.utils.SPUtils;
public ACheckBox(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); View.inflate(context, R.layout.layout_custom_checkbox, this); init(context, attrs); setOnClickListener(this); } private void init(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ACheckBox); String title = typedArray.getString(R.styleable.ACheckBox_title); String summary = typedArray.getString(R.styleable.ACheckBox_summary); mCheckBox = findViewById(R.id.cb); mTitle = findViewById(R.id.tv_title); mSummary =findViewById(R.id.tv_summary); mTitle.setText(title); mSummary.setText(summary); typedArray.recycle(); } @Override public void onClick(View view) { if (mKey != null) { boolean checked = !mCheckBox.isChecked(); mCheckBox.setChecked(checked); if (!mKey.equals(Constants.THEME)) {
// Path: app/src/main/java/nich/work/aequorea/common/Constants.java // public class Constants { // public static final String AUTHOR = "author"; // public static final String TAG = "tag"; // public static final String ARTICLE_ID = "article_id"; // public static final String AUTHOR_ID = "author_id"; // public static final String TAG_ID = "tag_id"; // public static final String SEARCH_KEY = "search_key"; // public static final String PHOTO = "photo"; // public static final String ARG_URL = "arg_url"; // // // Article Type // public static final String ARTICLE_TYPE_MAGAZINE = "magazine_article"; // 封面故事 // public static final String ARTICLE_TYPE_MAGAZINE_V2 = "magazine"; // 封面故事 // public static final String ARTICLE_TYPE_NORMAL = "normal_article"; // 一般文章 // public static final String ARTICLE_TYPE_NORMAL_V2 = "normal"; // 一般文章 // public static final String ARTICLE_TYPE_THEME = "theme"; // 专题 // public static final String ARTICLE_TYPE_TOP_ARTICLE = "top_article"; // 头条故事 // public static final String ARTICLE_TYPE_SUBJECT = "subject"; // 单行本 // // // public static final int TYPE_MAGAZINE = 1; // public static final int TYPE_NORMAL = 2; // public static final int TYPE_THEME = 3; // public static final int TYPE_TOP_ARTICLE = 4; // public static final int TYPE_SUBJECT = 5; // // // Theme // public static final String THEME = "theme"; // public static final String THEME_LIGHT = "theme_light"; // public static final String THEME_DARK = "theme_dark"; // // // Trigger // public static final int AUTO_LOAD_TRIGGER = 30; // // // Key of SharePreference // public static final String SP_LATEST_MAIN_PAGE = "sp_latest_main_page"; // public static final String SP_HD_SCREENSHOT = "sp_hd_screenshot"; // public static final String SP_ENABLE_SELECTION = "sp_enable_selection"; // public static final String SP_OFFLINE_CACHE = "sp_offline_cache"; // public static final String SP_DISABLE_RECOMMEND_ARTICLE = "sp_disable_recommend_article"; // // // Cache dir // public static final String ARTICLE_CACHE = "article_cache"; // public static final String ARTICLE_PIC_CACHE = "article_pic_cache"; // } // // Path: app/src/main/java/nich/work/aequorea/common/utils/SPUtils.java // public class SPUtils { // private static SharedPreferences mSp; // // private static SharedPreferences getSp() { // if (mSp == null) { // mSp = Aequorea.getApp().getSharedPreferences("Aequorea", Context.MODE_PRIVATE); // } // return mSp; // } // // public static void setString(String key, String value) { // getSp().edit().putString(key, value).apply(); // } // // public static String getString(String key) { // return getSp().getString(key, ""); // } // // public static String getString(String key, String defaultValue) { // return getSp().getString(key, defaultValue); // } // // public static void setInt(String key, int value) { // getSp().edit().putInt(key, value).apply(); // } // // public static int getInt(String key) { // return getSp().getInt(key, 0); // } // // public static int getInt(String key, int defaultValue) { // return getSp().getInt(key, defaultValue); // } // // public static void setBoolean(String key, boolean value) { // getSp().edit().putBoolean(key, value).apply(); // } // // public static boolean getBoolean(String key) { // return getSp().getBoolean(key, false); // } // } // Path: app/src/main/java/nich/work/aequorea/common/ui/widget/ACheckBox.java import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import android.widget.TextView; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatCheckBox; import nich.work.aequorea.R; import nich.work.aequorea.common.Constants; import nich.work.aequorea.common.utils.SPUtils; public ACheckBox(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); View.inflate(context, R.layout.layout_custom_checkbox, this); init(context, attrs); setOnClickListener(this); } private void init(Context context, AttributeSet attrs) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ACheckBox); String title = typedArray.getString(R.styleable.ACheckBox_title); String summary = typedArray.getString(R.styleable.ACheckBox_summary); mCheckBox = findViewById(R.id.cb); mTitle = findViewById(R.id.tv_title); mSummary =findViewById(R.id.tv_summary); mTitle.setText(title); mSummary.setText(summary); typedArray.recycle(); } @Override public void onClick(View view) { if (mKey != null) { boolean checked = !mCheckBox.isChecked(); mCheckBox.setChecked(checked); if (!mKey.equals(Constants.THEME)) {
SPUtils.setBoolean(mKey, checked);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/NetworkUtils.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import nich.work.aequorea.Aequorea;
package nich.work.aequorea.common.utils; public class NetworkUtils { public static boolean isNetworkAvailable() {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // Path: app/src/main/java/nich/work/aequorea/common/utils/NetworkUtils.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import nich.work.aequorea.Aequorea; package nich.work.aequorea.common.utils; public class NetworkUtils { public static boolean isNetworkAvailable() {
Context context = Aequorea.getApp();
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/model/entity/search/Content.java
// Path: app/src/main/java/nich/work/aequorea/model/entity/Author.java // public class Author implements Serializable { // // @SerializedName("avatar") // private String mAvatar; // @SerializedName("data") // private List<Datum> mData; // @SerializedName("id") // private Long mId; // @SerializedName("introduction") // private String mIntroduction; // @SerializedName("meta") // private Meta mMeta; // @SerializedName("name") // private String mName; // @SerializedName("role") // private Object mRole; // @SerializedName("articles_count") // private Long mArticleCount; // // public String getAvatar() { // return mAvatar; // } // // public void setAvatar(String avatar) { // mAvatar = avatar; // } // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Long getId() { // return mId; // } // // public void setId(Long id) { // mId = id; // } // // public String getIntroduction() { // return mIntroduction; // } // // public void setIntroduction(String introduction) { // mIntroduction = introduction; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public Object getRole() { // return mRole; // } // // public void setRole(Object role) { // mRole = role; // } // // public Long getArticleCount() { // return mArticleCount; // } // // public void setArticleCount(Long mArticleCount) { // this.mArticleCount = mArticleCount; // } // }
import com.google.gson.annotations.SerializedName; import java.util.List; import nich.work.aequorea.model.entity.Author;
package nich.work.aequorea.model.entity.search; public class Content { @SerializedName("article_type") private String mArticleType; @SerializedName("authors")
// Path: app/src/main/java/nich/work/aequorea/model/entity/Author.java // public class Author implements Serializable { // // @SerializedName("avatar") // private String mAvatar; // @SerializedName("data") // private List<Datum> mData; // @SerializedName("id") // private Long mId; // @SerializedName("introduction") // private String mIntroduction; // @SerializedName("meta") // private Meta mMeta; // @SerializedName("name") // private String mName; // @SerializedName("role") // private Object mRole; // @SerializedName("articles_count") // private Long mArticleCount; // // public String getAvatar() { // return mAvatar; // } // // public void setAvatar(String avatar) { // mAvatar = avatar; // } // // public List<Datum> getData() { // return mData; // } // // public void setData(List<Datum> data) { // mData = data; // } // // public Long getId() { // return mId; // } // // public void setId(Long id) { // mId = id; // } // // public String getIntroduction() { // return mIntroduction; // } // // public void setIntroduction(String introduction) { // mIntroduction = introduction; // } // // public Meta getMeta() { // return mMeta; // } // // public void setMeta(Meta meta) { // mMeta = meta; // } // // public String getName() { // return mName; // } // // public void setName(String name) { // mName = name; // } // // public Object getRole() { // return mRole; // } // // public void setRole(Object role) { // mRole = role; // } // // public Long getArticleCount() { // return mArticleCount; // } // // public void setArticleCount(Long mArticleCount) { // this.mArticleCount = mArticleCount; // } // } // Path: app/src/main/java/nich/work/aequorea/model/entity/search/Content.java import com.google.gson.annotations.SerializedName; import java.util.List; import nich.work.aequorea.model.entity.Author; package nich.work.aequorea.model.entity.search; public class Content { @SerializedName("article_type") private String mArticleType; @SerializedName("authors")
private List<Author> mAuthors;
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/SPUtils.java
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // }
import android.content.Context; import android.content.SharedPreferences; import nich.work.aequorea.Aequorea;
package nich.work.aequorea.common.utils; public class SPUtils { private static SharedPreferences mSp; private static SharedPreferences getSp() { if (mSp == null) {
// Path: app/src/main/java/nich/work/aequorea/Aequorea.java // public class Aequorea extends Application { // private static Aequorea mApp; // private static String mCurrentTheme; // private static ExecutorService mExecutor; // // @Override // public void onCreate() { // super.onCreate(); // // mApp = this; // mCurrentTheme = ThemeHelper.getTheme(); // mExecutor = Executors.newCachedThreadPool(); // // initCache(); // initFlurry(); // } // // private void initFlurry() { // new FlurryAgent.Builder() // .withDataSaleOptOut(false) //CCPA - the default value is false // .withCaptureUncaughtExceptions(true) // .withIncludeBackgroundSessionsInMetrics(true) // .withLogLevel(Log.VERBOSE) // .withPerformanceMetrics(FlurryPerformance.ALL) // .build(this, "CXH6FJ9VS4P8K3K8BFN9"); // } // // private void initCache() { // File cacheDir = new File(getCacheDir().getAbsolutePath() + File.separator + Constants.ARTICLE_PIC_CACHE); // RichText.initCacheDir(cacheDir); // ArticleCache.getCache(); // } // // public static Application getApp() { // return mApp; // } // // public static String getCurrentTheme() { // return mCurrentTheme; // } // // public static boolean isLightTheme() { // return mCurrentTheme.equals(Constants.THEME_LIGHT); // } // // public static void setCurrentTheme(String theme) { // mCurrentTheme = theme; // } // // public static ExecutorService getExecutor(){ // return mExecutor; // } // } // Path: app/src/main/java/nich/work/aequorea/common/utils/SPUtils.java import android.content.Context; import android.content.SharedPreferences; import nich.work.aequorea.Aequorea; package nich.work.aequorea.common.utils; public class SPUtils { private static SharedPreferences mSp; private static SharedPreferences getSp() { if (mSp == null) {
mSp = Aequorea.getApp().getSharedPreferences("Aequorea", Context.MODE_PRIVATE);
nichbar/Aequorea
app/src/main/java/nich/work/aequorea/common/utils/ImageHelper.java
// Path: app/src/main/java/nich/work/aequorea/common/ui/widget/glide/CircleTransformation.java // public class CircleTransformation extends BitmapTransformation { // // public CircleTransformation(Context context) { // super(context); // } // // private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { // if (source == null) return null; // // int size = Math.min(source.getWidth(), source.getHeight()); // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); // // Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); // } // // Canvas canvas = new Canvas(result); // Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG | Paint // .ANTI_ALIAS_FLAG); // paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader // .TileMode.CLAMP)); // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // return result; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return circleCrop(pool, toTransform); // } // // @Override // public String getId() { // return getClass().getName(); // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.Target; import nich.work.aequorea.common.ui.widget.glide.CircleTransformation;
package nich.work.aequorea.common.utils; public class ImageHelper { public static Target setImage(Context context, String url, ImageView imageView) { return setImage(context, url, imageView, false, -1); } public static Target setImage(Context context, String url, ImageView imageView, boolean isRound) { return setImage(context, url, imageView, isRound, -1); } public static Target setImage(Context context, String url, ImageView imageView, int placeHolder) { return setImage(context, url, imageView, false, placeHolder); } public static Target setImage(Context context, String url, ImageView imageView, Drawable placeHolder) { return setImage(context, url, imageView, false, placeHolder); } public static Target setImage(Context context, String url, ImageView imageView, boolean isRound, int placeHolder) { if (isRound) { return Glide.with(context) .load(url)
// Path: app/src/main/java/nich/work/aequorea/common/ui/widget/glide/CircleTransformation.java // public class CircleTransformation extends BitmapTransformation { // // public CircleTransformation(Context context) { // super(context); // } // // private static Bitmap circleCrop(BitmapPool pool, Bitmap source) { // if (source == null) return null; // // int size = Math.min(source.getWidth(), source.getHeight()); // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squared = Bitmap.createBitmap(source, x, y, size, size); // // Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888); // if (result == null) { // result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); // } // // Canvas canvas = new Canvas(result); // Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG | Paint // .ANTI_ALIAS_FLAG); // paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader // .TileMode.CLAMP)); // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // return result; // } // // @Override // protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) { // return circleCrop(pool, toTransform); // } // // @Override // public String getId() { // return getClass().getName(); // } // } // Path: app/src/main/java/nich/work/aequorea/common/utils/ImageHelper.java import android.content.Context; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.Target; import nich.work.aequorea.common.ui.widget.glide.CircleTransformation; package nich.work.aequorea.common.utils; public class ImageHelper { public static Target setImage(Context context, String url, ImageView imageView) { return setImage(context, url, imageView, false, -1); } public static Target setImage(Context context, String url, ImageView imageView, boolean isRound) { return setImage(context, url, imageView, isRound, -1); } public static Target setImage(Context context, String url, ImageView imageView, int placeHolder) { return setImage(context, url, imageView, false, placeHolder); } public static Target setImage(Context context, String url, ImageView imageView, Drawable placeHolder) { return setImage(context, url, imageView, false, placeHolder); } public static Target setImage(Context context, String url, ImageView imageView, boolean isRound, int placeHolder) { if (isRound) { return Glide.with(context) .load(url)
.transform(new CircleTransformation(context))
nichbar/Aequorea
richtext/src/main/java/com/zzhoujay/richtext/ext/LongClickableLinkMovementMethod.java
// Path: richtext/src/main/java/com/zzhoujay/richtext/spans/ClickableImageSpan.java // public class ClickableImageSpan extends ImageSpan implements LongClickableSpan { // // private float x; // private final int position; // private final List<String> imageUrls; // private final WeakReference<OnImageLongClickListener> onImageLongClickListenerWeakReference; // private final WeakReference<OnImageClickListener> onImageClickListenerWeakReference; // // public ClickableImageSpan(Drawable drawable, ClickableImageSpan clickableImageSpan, OnImageClickListener onImageClickListener, OnImageLongClickListener onImageLongClickListener) { // super(drawable, clickableImageSpan.getSource()); // this.imageUrls = clickableImageSpan.imageUrls; // this.position = clickableImageSpan.position; // this.onImageClickListenerWeakReference = new WeakReference<>(onImageClickListener); // this.onImageLongClickListenerWeakReference = new WeakReference<>(onImageLongClickListener); // } // // public ClickableImageSpan(Drawable drawable, List<String> imageUrls, int position, OnImageClickListener onImageClickListener, OnImageLongClickListener onImageLongClickListener) { // super(drawable, imageUrls.get(position)); // this.imageUrls = imageUrls; // this.position = position; // this.onImageClickListenerWeakReference = new WeakReference<>(onImageClickListener); // this.onImageLongClickListenerWeakReference = new WeakReference<>(onImageLongClickListener); // } // // // @Override // public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { // super.draw(canvas, text, start, end, x, top, y, bottom, paint); // this.x = x; // } // // public boolean clicked(int position) { // Drawable drawable = getDrawable(); // if (drawable != null) { // Rect rect = drawable.getBounds(); // if (position <= rect.right + x && position >= rect.left + x) { // return true; // } // } // return false; // } // // // @Override // public void onClick(View widget) { // OnImageClickListener onImageClickListener = onImageClickListenerWeakReference.get(); // if (onImageClickListener != null) { // boolean isDefaultDrawable = false; // // Drawable drawable; // if (getDrawable() instanceof DrawableWrapper) { // drawable = ((DrawableWrapper) getDrawable()).getDrawable(); // isDefaultDrawable = drawable instanceof ColorDrawable; // } // onImageClickListener.imageClicked(imageUrls, position, isDefaultDrawable); // } // } // // @Override // public boolean onLongClick(View widget) { // OnImageLongClickListener onImageLongClickListener = onImageLongClickListenerWeakReference.get(); // return onImageLongClickListener != null && onImageLongClickListener.imageLongClicked(imageUrls, position); // } // }
import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.view.MotionEvent; import android.widget.TextView; import com.zzhoujay.richtext.spans.ClickableImageSpan; import com.zzhoujay.richtext.spans.LongClickableSpan;
package com.zzhoujay.richtext.ext; /** * Created by zhou on 16-8-4. * 支持长按的MovementMethod */ public class LongClickableLinkMovementMethod extends LinkMovementMethod { private static final int MIN_INTERVAL = 500; private long lastTime; @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); LongClickableSpan[] link = buffer.getSpans(off, off, LongClickableSpan.class); if (link.length != 0) { long currTime = System.currentTimeMillis(); LongClickableSpan l = link[0]; int ls = buffer.getSpanStart(l); int le = buffer.getSpanEnd(l); // 判断点击的点是否在Image范围内
// Path: richtext/src/main/java/com/zzhoujay/richtext/spans/ClickableImageSpan.java // public class ClickableImageSpan extends ImageSpan implements LongClickableSpan { // // private float x; // private final int position; // private final List<String> imageUrls; // private final WeakReference<OnImageLongClickListener> onImageLongClickListenerWeakReference; // private final WeakReference<OnImageClickListener> onImageClickListenerWeakReference; // // public ClickableImageSpan(Drawable drawable, ClickableImageSpan clickableImageSpan, OnImageClickListener onImageClickListener, OnImageLongClickListener onImageLongClickListener) { // super(drawable, clickableImageSpan.getSource()); // this.imageUrls = clickableImageSpan.imageUrls; // this.position = clickableImageSpan.position; // this.onImageClickListenerWeakReference = new WeakReference<>(onImageClickListener); // this.onImageLongClickListenerWeakReference = new WeakReference<>(onImageLongClickListener); // } // // public ClickableImageSpan(Drawable drawable, List<String> imageUrls, int position, OnImageClickListener onImageClickListener, OnImageLongClickListener onImageLongClickListener) { // super(drawable, imageUrls.get(position)); // this.imageUrls = imageUrls; // this.position = position; // this.onImageClickListenerWeakReference = new WeakReference<>(onImageClickListener); // this.onImageLongClickListenerWeakReference = new WeakReference<>(onImageLongClickListener); // } // // // @Override // public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { // super.draw(canvas, text, start, end, x, top, y, bottom, paint); // this.x = x; // } // // public boolean clicked(int position) { // Drawable drawable = getDrawable(); // if (drawable != null) { // Rect rect = drawable.getBounds(); // if (position <= rect.right + x && position >= rect.left + x) { // return true; // } // } // return false; // } // // // @Override // public void onClick(View widget) { // OnImageClickListener onImageClickListener = onImageClickListenerWeakReference.get(); // if (onImageClickListener != null) { // boolean isDefaultDrawable = false; // // Drawable drawable; // if (getDrawable() instanceof DrawableWrapper) { // drawable = ((DrawableWrapper) getDrawable()).getDrawable(); // isDefaultDrawable = drawable instanceof ColorDrawable; // } // onImageClickListener.imageClicked(imageUrls, position, isDefaultDrawable); // } // } // // @Override // public boolean onLongClick(View widget) { // OnImageLongClickListener onImageLongClickListener = onImageLongClickListenerWeakReference.get(); // return onImageLongClickListener != null && onImageLongClickListener.imageLongClicked(imageUrls, position); // } // } // Path: richtext/src/main/java/com/zzhoujay/richtext/ext/LongClickableLinkMovementMethod.java import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.view.MotionEvent; import android.widget.TextView; import com.zzhoujay.richtext.spans.ClickableImageSpan; import com.zzhoujay.richtext.spans.LongClickableSpan; package com.zzhoujay.richtext.ext; /** * Created by zhou on 16-8-4. * 支持长按的MovementMethod */ public class LongClickableLinkMovementMethod extends LinkMovementMethod { private static final int MIN_INTERVAL = 500; private long lastTime; @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); LongClickableSpan[] link = buffer.getSpans(off, off, LongClickableSpan.class); if (link.length != 0) { long currTime = System.currentTimeMillis(); LongClickableSpan l = link[0]; int ls = buffer.getSpanStart(l); int le = buffer.getSpanEnd(l); // 判断点击的点是否在Image范围内
ClickableImageSpan[] is = buffer.getSpans(ls, le, ClickableImageSpan.class);
jmimo/netty-icap
src/main/java/ch/mimo/netty/example/icap/preview/IcapClientChannelPipeline.java
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestEncoder.java // public class IcapRequestEncoder extends IcapMessageEncoder { // // public IcapRequestEncoder() { // super(); // } // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) throws Exception { // IcapRequest request = (IcapRequest) message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getMethod().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getUri().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseDecoder.java // public class IcapResponseDecoder extends IcapMessageDecoder { // // public IcapResponseDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapResponseDecoder (int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapMessage createMessage(String[] initialLine) { // return new DefaultIcapResponse(IcapVersion.valueOf(initialLine[0]),IcapResponseStatus.fromCode(initialLine[1])); // } // // @Override // public boolean isDecodingResponse() { // return true; // } // }
import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestEncoder; import ch.mimo.netty.handler.codec.icap.IcapResponseDecoder;
/******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapClientChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline();
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestEncoder.java // public class IcapRequestEncoder extends IcapMessageEncoder { // // public IcapRequestEncoder() { // super(); // } // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) throws Exception { // IcapRequest request = (IcapRequest) message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getMethod().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getUri().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseDecoder.java // public class IcapResponseDecoder extends IcapMessageDecoder { // // public IcapResponseDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapResponseDecoder (int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapMessage createMessage(String[] initialLine) { // return new DefaultIcapResponse(IcapVersion.valueOf(initialLine[0]),IcapResponseStatus.fromCode(initialLine[1])); // } // // @Override // public boolean isDecodingResponse() { // return true; // } // } // Path: src/main/java/ch/mimo/netty/example/icap/preview/IcapClientChannelPipeline.java import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestEncoder; import ch.mimo.netty.handler.codec.icap.IcapResponseDecoder; /******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapClientChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline();
pipeline.addLast("encoder",new IcapRequestEncoder());
jmimo/netty-icap
src/main/java/ch/mimo/netty/example/icap/preview/IcapClientChannelPipeline.java
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestEncoder.java // public class IcapRequestEncoder extends IcapMessageEncoder { // // public IcapRequestEncoder() { // super(); // } // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) throws Exception { // IcapRequest request = (IcapRequest) message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getMethod().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getUri().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseDecoder.java // public class IcapResponseDecoder extends IcapMessageDecoder { // // public IcapResponseDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapResponseDecoder (int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapMessage createMessage(String[] initialLine) { // return new DefaultIcapResponse(IcapVersion.valueOf(initialLine[0]),IcapResponseStatus.fromCode(initialLine[1])); // } // // @Override // public boolean isDecodingResponse() { // return true; // } // }
import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestEncoder; import ch.mimo.netty.handler.codec.icap.IcapResponseDecoder;
/******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapClientChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("encoder",new IcapRequestEncoder());
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestEncoder.java // public class IcapRequestEncoder extends IcapMessageEncoder { // // public IcapRequestEncoder() { // super(); // } // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) throws Exception { // IcapRequest request = (IcapRequest) message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getMethod().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getUri().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseDecoder.java // public class IcapResponseDecoder extends IcapMessageDecoder { // // public IcapResponseDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapResponseDecoder (int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapMessage createMessage(String[] initialLine) { // return new DefaultIcapResponse(IcapVersion.valueOf(initialLine[0]),IcapResponseStatus.fromCode(initialLine[1])); // } // // @Override // public boolean isDecodingResponse() { // return true; // } // } // Path: src/main/java/ch/mimo/netty/example/icap/preview/IcapClientChannelPipeline.java import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestEncoder; import ch.mimo.netty.handler.codec.icap.IcapResponseDecoder; /******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapClientChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("encoder",new IcapRequestEncoder());
pipeline.addLast("decoder",new IcapResponseDecoder());
jmimo/netty-icap
src/main/java/ch/mimo/netty/example/icap/preview/IcapServerChannelPipeline.java
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestDecoder.java // public class IcapRequestDecoder extends IcapMessageDecoder { // // public IcapRequestDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapRequestDecoder(int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapRequest createMessage(String[] initialLine) { // return new DefaultIcapRequest(IcapVersion.valueOf(initialLine[2]),IcapMethod.valueOf(initialLine[0]),initialLine[1],""); // } // // @Override // public boolean isDecodingResponse() { // return false; // } // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseEncoder.java // public class IcapResponseEncoder extends IcapMessageEncoder { // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) { // IcapResponse request = (IcapResponse)message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // request.getStatus().toResponseInitialLineValue(buffer); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // }
import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestDecoder; import ch.mimo.netty.handler.codec.icap.IcapResponseEncoder;
/******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapServerChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline();
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestDecoder.java // public class IcapRequestDecoder extends IcapMessageDecoder { // // public IcapRequestDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapRequestDecoder(int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapRequest createMessage(String[] initialLine) { // return new DefaultIcapRequest(IcapVersion.valueOf(initialLine[2]),IcapMethod.valueOf(initialLine[0]),initialLine[1],""); // } // // @Override // public boolean isDecodingResponse() { // return false; // } // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseEncoder.java // public class IcapResponseEncoder extends IcapMessageEncoder { // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) { // IcapResponse request = (IcapResponse)message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // request.getStatus().toResponseInitialLineValue(buffer); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // } // Path: src/main/java/ch/mimo/netty/example/icap/preview/IcapServerChannelPipeline.java import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestDecoder; import ch.mimo.netty.handler.codec.icap.IcapResponseEncoder; /******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapServerChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline();
pipeline.addLast("decoder",new IcapRequestDecoder());
jmimo/netty-icap
src/main/java/ch/mimo/netty/example/icap/preview/IcapServerChannelPipeline.java
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestDecoder.java // public class IcapRequestDecoder extends IcapMessageDecoder { // // public IcapRequestDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapRequestDecoder(int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapRequest createMessage(String[] initialLine) { // return new DefaultIcapRequest(IcapVersion.valueOf(initialLine[2]),IcapMethod.valueOf(initialLine[0]),initialLine[1],""); // } // // @Override // public boolean isDecodingResponse() { // return false; // } // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseEncoder.java // public class IcapResponseEncoder extends IcapMessageEncoder { // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) { // IcapResponse request = (IcapResponse)message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // request.getStatus().toResponseInitialLineValue(buffer); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // }
import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestDecoder; import ch.mimo.netty.handler.codec.icap.IcapResponseEncoder;
/******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapServerChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder",new IcapRequestDecoder());
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapRequestDecoder.java // public class IcapRequestDecoder extends IcapMessageDecoder { // // public IcapRequestDecoder() { // super(); // } // // /** // * @see IcapMessageDecoder IcapMessageDecoder constructor for more details. // * // * @param maxInitialLineLength // * @param maxIcapHeaderSize // * @param maxHttpHeaderSize // * @param maxChunkSize // */ // public IcapRequestDecoder(int maxInitialLineLength, int maxIcapHeaderSize, int maxHttpHeaderSize, int maxChunkSize) { // super(maxInitialLineLength, maxIcapHeaderSize, maxHttpHeaderSize, maxChunkSize); // } // // @Override // protected IcapRequest createMessage(String[] initialLine) { // return new DefaultIcapRequest(IcapVersion.valueOf(initialLine[2]),IcapMethod.valueOf(initialLine[0]),initialLine[1],""); // } // // @Override // public boolean isDecodingResponse() { // return false; // } // } // // Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponseEncoder.java // public class IcapResponseEncoder extends IcapMessageEncoder { // // @Override // protected int encodeInitialLine(ChannelBuffer buffer, IcapMessage message) { // IcapResponse request = (IcapResponse)message; // int index = buffer.readableBytes(); // buffer.writeBytes(request.getProtocolVersion().toString().getBytes(IcapCodecUtil.ASCII_CHARSET)); // buffer.writeByte(IcapCodecUtil.SPACE); // request.getStatus().toResponseInitialLineValue(buffer); // buffer.writeBytes(IcapCodecUtil.CRLF); // return buffer.readableBytes() - index; // } // } // Path: src/main/java/ch/mimo/netty/example/icap/preview/IcapServerChannelPipeline.java import static org.jboss.netty.channel.Channels.pipeline; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import ch.mimo.netty.handler.codec.icap.IcapRequestDecoder; import ch.mimo.netty.handler.codec.icap.IcapResponseEncoder; /******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.preview; public class IcapServerChannelPipeline implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder",new IcapRequestDecoder());
pipeline.addLast("encoder",new IcapResponseEncoder());
jmimo/netty-icap
src/main/java/ch/mimo/netty/example/icap/simple/IcapClientHandler.java
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponse.java // public interface IcapResponse extends IcapMessage { // // /** // * Sets the response status // * @param status @see {@link IcapResponseStatus} value like 200 OK. // */ // void setStatus(IcapResponseStatus status); // // /** // * Gets the response status for this message. // * // * @return the response status as @see {@link IcapResponseStatus} // */ // IcapResponseStatus getStatus(); // // /** // * Sets an OPTIONS body to this message. // * @param optionsContent @see {@link ChannelBuffer} containing the body. // */ // void setContent(ChannelBuffer optionsContent); // // /** // * Gets an OPTIONS body if present // * @return @see {@link ChannelBuffer} or null // */ // ChannelBuffer getContent(); // }
import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import ch.mimo.netty.handler.codec.icap.IcapResponse;
/******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.simple; public class IcapClientHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
// Path: src/main/java/ch/mimo/netty/handler/codec/icap/IcapResponse.java // public interface IcapResponse extends IcapMessage { // // /** // * Sets the response status // * @param status @see {@link IcapResponseStatus} value like 200 OK. // */ // void setStatus(IcapResponseStatus status); // // /** // * Gets the response status for this message. // * // * @return the response status as @see {@link IcapResponseStatus} // */ // IcapResponseStatus getStatus(); // // /** // * Sets an OPTIONS body to this message. // * @param optionsContent @see {@link ChannelBuffer} containing the body. // */ // void setContent(ChannelBuffer optionsContent); // // /** // * Gets an OPTIONS body if present // * @return @see {@link ChannelBuffer} or null // */ // ChannelBuffer getContent(); // } // Path: src/main/java/ch/mimo/netty/example/icap/simple/IcapClientHandler.java import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import ch.mimo.netty.handler.codec.icap.IcapResponse; /******************************************************************************* * Copyright 2012 Michael Mimo Moratti * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ch.mimo.netty.example.icap.simple; public class IcapClientHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
IcapResponse response = (IcapResponse)e.getMessage();
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/OnViewPagerChangeListener.java
// Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // }
import android.support.v4.view.ViewPager; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Change listener for easy integration between {@link CutoutViewIndicator} * and {@link android.support.v4.view.ViewPager}. * * @author Philip Cohn-Cort (Fuzz) */ public class OnViewPagerChangeListener implements ViewPager.OnPageChangeListener { private CutoutViewIndicator cvi; public OnViewPagerChangeListener(CutoutViewIndicator cutoutViewIndicator) { this.cvi = cutoutViewIndicator; } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (cvi.getIndicatorDrawableId() != 0) { position = cvi.fixPosition(position); // Cover the provided position... cvi.showOffsetIndicator(position, positionOffset); if (positionOffset > 0) { // ...and cover the next one too int next = position + 1; if (next >= cvi.getChildCount()) { next = 0; } cvi.showOffsetIndicator(next, positionOffset - 1); } } } @Override public void onPageSelected(int position) { createEventFrom(cvi, position); } /** * Integration implementation of {@link #onPageSelected(int)} for use with * {@link ViewPagerStateProxy#resendPositionInfo(ProxyReference, float)}. * @param cvi which CutoutViewIndicator to call methods on. * @param position a specified position within the indicator. */
// Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // Path: indicator/src/main/java/com/fuzz/indicator/OnViewPagerChangeListener.java import android.support.v4.view.ViewPager; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Change listener for easy integration between {@link CutoutViewIndicator} * and {@link android.support.v4.view.ViewPager}. * * @author Philip Cohn-Cort (Fuzz) */ public class OnViewPagerChangeListener implements ViewPager.OnPageChangeListener { private CutoutViewIndicator cvi; public OnViewPagerChangeListener(CutoutViewIndicator cutoutViewIndicator) { this.cvi = cutoutViewIndicator; } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if (cvi.getIndicatorDrawableId() != 0) { position = cvi.fixPosition(position); // Cover the provided position... cvi.showOffsetIndicator(position, positionOffset); if (positionOffset > 0) { // ...and cover the next one too int next = position + 1; if (next >= cvi.getChildCount()) { next = 0; } cvi.showOffsetIndicator(next, positionOffset - 1); } } } @Override public void onPageSelected(int position) { createEventFrom(cvi, position); } /** * Integration implementation of {@link #onPageSelected(int)} for use with * {@link ViewPagerStateProxy#resendPositionInfo(ProxyReference, float)}. * @param cvi which CutoutViewIndicator to call methods on. * @param position a specified position within the indicator. */
public IndicatorOffsetEvent createEventFrom(ProxyReference cvi, float position) {
fuzz-productions/CutoutViewIndicator
mobile/src/main/java/com/fuzz/emptyhusk/BoldTextCellGenerator.java
// Path: indicator/src/main/java/com/fuzz/indicator/style/MigratoryRange.java // public final class MigratoryRange<T extends Number & Comparable<T>> { // // public static abstract class Operator<T> { // @NonNull // public abstract T add(T lower, T offset); // } // // public static final Operator<Float> FLOAT_OPERATOR // = new Operator<Float>() { // @NonNull // @Override // public Float add(Float lower, Float offset) { // return lower + offset; // } // }; // // public static final Operator<Integer> INTEGER_OPERATOR // = new Operator<Integer>() { // @NonNull // @Override // public Integer add(Integer lower, Integer offset) { // return lower + offset; // } // }; // // public static MigratoryRange<Float> from(float lower, float upper) { // return new MigratoryRange<>(lower, upper, FLOAT_OPERATOR); // } // // public static MigratoryRange<Integer> from(int lower, int upper) { // return new MigratoryRange<>(lower, upper, INTEGER_OPERATOR); // } // // @NonNull // private final T lower; // @NonNull // private final T upper; // @NonNull // private final Operator<T> operator; // // public MigratoryRange(@NonNull T lower, @NonNull T upper, @NonNull Operator<T> operator) { // this.lower = lower; // this.upper = upper; // this.operator = operator; // // if (lower.compareTo(upper) > 0) { // throw new IllegalArgumentException("Migratory ranges may not have an upper bound below their lower bound."); // } // } // // @NonNull // public T getLower() { // return lower; // } // // @NonNull // public T getUpper() { // return upper; // } // // /** // * If the parameter is within this range it will be // * returned unaltered. If it isn't, the closest value // * within the range (e.g. {@link #getLower()} or // * {@link #getUpper()}) will be returned. // * // * @param value any non-null value of type T // * @return a value guaranteed to be within this range // */ // @NonNull // public T clamp(@NonNull T value) { // if (value.compareTo(lower) < 0) { // return lower; // } else if (value.compareTo(upper) > 0) { // return upper; // } else { // return value; // } // } // // public double diff() { // return upper.doubleValue() - lower.doubleValue(); // } // // public MigratoryRange<T> translate(@NonNull T offset) { // T newLower = operator.add(lower, offset); // T newUpper = operator.add(upper, offset); // return new MigratoryRange<>(newLower, newUpper, operator); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/text/TextCellGenerator.java // public abstract class TextCellGenerator implements CutoutCellGenerator { // @NonNull // @Override // public CutoutCell createCellFor(@NonNull ViewGroup parent, int position) { // CutoutViewLayoutParams lp = ((CutoutViewIndicator) parent).generateDefaultLayoutParams(); // // TextView child = new TextView(parent.getContext()); // child.setText(getTextFor(parent.getContext(), position)); // child.setLayoutParams(lp); // // return new CutoutTextCell(child); // } // // @NonNull // protected abstract Spannable getTextFor(@NonNull Context context, int position); // // @Override // public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) { // child.setBackgroundResource(lp.cellBackgroundId); // } // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import com.fuzz.indicator.style.MigratoryRange; import com.fuzz.indicator.style.MigratoryStyleSpan; import com.fuzz.indicator.text.TextCellGenerator; import static android.graphics.Typeface.BOLD;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.emptyhusk; /** * Simple TextViewGenerator that styles text in a bold sort of way. * * @author Philip Cohn-Cort (Fuzz) */ public class BoldTextCellGenerator extends TextCellGenerator { @NonNull @Override protected Spannable getTextFor(@NonNull Context context, int position) { String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages); SpannableString ssb = new SpannableString(introStrings[position]); MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD); // Order matters when setting spans. The base color must be in place first ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorSecondary)); ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // Only then should custom MigratorySpans be set.
// Path: indicator/src/main/java/com/fuzz/indicator/style/MigratoryRange.java // public final class MigratoryRange<T extends Number & Comparable<T>> { // // public static abstract class Operator<T> { // @NonNull // public abstract T add(T lower, T offset); // } // // public static final Operator<Float> FLOAT_OPERATOR // = new Operator<Float>() { // @NonNull // @Override // public Float add(Float lower, Float offset) { // return lower + offset; // } // }; // // public static final Operator<Integer> INTEGER_OPERATOR // = new Operator<Integer>() { // @NonNull // @Override // public Integer add(Integer lower, Integer offset) { // return lower + offset; // } // }; // // public static MigratoryRange<Float> from(float lower, float upper) { // return new MigratoryRange<>(lower, upper, FLOAT_OPERATOR); // } // // public static MigratoryRange<Integer> from(int lower, int upper) { // return new MigratoryRange<>(lower, upper, INTEGER_OPERATOR); // } // // @NonNull // private final T lower; // @NonNull // private final T upper; // @NonNull // private final Operator<T> operator; // // public MigratoryRange(@NonNull T lower, @NonNull T upper, @NonNull Operator<T> operator) { // this.lower = lower; // this.upper = upper; // this.operator = operator; // // if (lower.compareTo(upper) > 0) { // throw new IllegalArgumentException("Migratory ranges may not have an upper bound below their lower bound."); // } // } // // @NonNull // public T getLower() { // return lower; // } // // @NonNull // public T getUpper() { // return upper; // } // // /** // * If the parameter is within this range it will be // * returned unaltered. If it isn't, the closest value // * within the range (e.g. {@link #getLower()} or // * {@link #getUpper()}) will be returned. // * // * @param value any non-null value of type T // * @return a value guaranteed to be within this range // */ // @NonNull // public T clamp(@NonNull T value) { // if (value.compareTo(lower) < 0) { // return lower; // } else if (value.compareTo(upper) > 0) { // return upper; // } else { // return value; // } // } // // public double diff() { // return upper.doubleValue() - lower.doubleValue(); // } // // public MigratoryRange<T> translate(@NonNull T offset) { // T newLower = operator.add(lower, offset); // T newUpper = operator.add(upper, offset); // return new MigratoryRange<>(newLower, newUpper, operator); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/text/TextCellGenerator.java // public abstract class TextCellGenerator implements CutoutCellGenerator { // @NonNull // @Override // public CutoutCell createCellFor(@NonNull ViewGroup parent, int position) { // CutoutViewLayoutParams lp = ((CutoutViewIndicator) parent).generateDefaultLayoutParams(); // // TextView child = new TextView(parent.getContext()); // child.setText(getTextFor(parent.getContext(), position)); // child.setLayoutParams(lp); // // return new CutoutTextCell(child); // } // // @NonNull // protected abstract Spannable getTextFor(@NonNull Context context, int position); // // @Override // public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) { // child.setBackgroundResource(lp.cellBackgroundId); // } // } // Path: mobile/src/main/java/com/fuzz/emptyhusk/BoldTextCellGenerator.java import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import com.fuzz.indicator.style.MigratoryRange; import com.fuzz.indicator.style.MigratoryStyleSpan; import com.fuzz.indicator.text.TextCellGenerator; import static android.graphics.Typeface.BOLD; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.emptyhusk; /** * Simple TextViewGenerator that styles text in a bold sort of way. * * @author Philip Cohn-Cort (Fuzz) */ public class BoldTextCellGenerator extends TextCellGenerator { @NonNull @Override protected Spannable getTextFor(@NonNull Context context, int position) { String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages); SpannableString ssb = new SpannableString(introStrings[position]); MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD); // Order matters when setting spans. The base color must be in place first ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorSecondary)); ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // Only then should custom MigratorySpans be set.
MigratoryRange<Integer> coverage = span.getCoverage(ssb);
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/CutoutViewLayoutParams.java
// Path: indicator/src/main/java/com/fuzz/indicator/cell/CutoutCell.java // public interface CutoutCell { // // /** // * Perform some arbitrary action to represent the provided OffsetEvent. // * // * @param offsetEvent whatever just happened // * @see OffSetters // */ // void offsetContentBy(@NonNull IndicatorOffsetEvent offsetEvent); // // /** // * @return the actual view represented by this object // */ // @NonNull // View getItemView(); // }
import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.widget.LinearLayout; import com.fuzz.indicator.cell.CutoutCell; import java.lang.ref.WeakReference;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Plain Old Java Object representing the configuration of the child views inside * {@link CutoutViewIndicator}. * * @author Philip Cohn-Cort (Fuzz) */ public class CutoutViewLayoutParams extends LinearLayout.LayoutParams { @DrawableRes public int cellBackgroundId; /** * This is the id of the drawable currently acting as indicator. If 0, no indicator will be shown. */ @DrawableRes public int indicatorDrawableId; @NonNull
// Path: indicator/src/main/java/com/fuzz/indicator/cell/CutoutCell.java // public interface CutoutCell { // // /** // * Perform some arbitrary action to represent the provided OffsetEvent. // * // * @param offsetEvent whatever just happened // * @see OffSetters // */ // void offsetContentBy(@NonNull IndicatorOffsetEvent offsetEvent); // // /** // * @return the actual view represented by this object // */ // @NonNull // View getItemView(); // } // Path: indicator/src/main/java/com/fuzz/indicator/CutoutViewLayoutParams.java import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.widget.LinearLayout; import com.fuzz.indicator.cell.CutoutCell; import java.lang.ref.WeakReference; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Plain Old Java Object representing the configuration of the child views inside * {@link CutoutViewIndicator}. * * @author Philip Cohn-Cort (Fuzz) */ public class CutoutViewLayoutParams extends LinearLayout.LayoutParams { @DrawableRes public int cellBackgroundId; /** * This is the id of the drawable currently acting as indicator. If 0, no indicator will be shown. */ @DrawableRes public int indicatorDrawableId; @NonNull
protected WeakReference<CutoutCell> cutoutCell = new WeakReference<>(null);
fuzz-productions/CutoutViewIndicator
mobile/src/androidTest/java/com/fuzz/indicator/OverlapTest.java
// Path: mobile/src/main/java/com/fuzz/emptyhusk/InstrumentationAwareActivity.java // public class InstrumentationAwareActivity extends AppCompatActivity { // // public MainViewBinding binding; // public PickerDelegate pickerDelegate; // // public ViewGroup inflationFrame; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // binding = new MainViewBinding(findViewById(R.id.root)); // pickerDelegate = new PickerDelegate(binding); // // setSupportActionBar(binding.toolbar); // // inflationFrame = (ViewGroup) getLayoutInflater().inflate(R.layout.test_frame, binding.root, false); // } // // public <T extends View> T inflateLayout(@LayoutRes int layoutId, Class<T> clazz) { // View inflated = getLayoutInflater().inflate(layoutId, inflationFrame, false); // return clazz.cast(inflated); // } // } // // Path: mobile/src/main/java/com/fuzz/emptyhusk/MainViewBinding.java // public class MainViewBinding { // public final Toolbar toolbar; // public final ViewPager mainViewPager; // public final FloatingActionButton fab; // // public final NumberPicker spacing; // public final NumberPicker width; // public final NumberPicker height; // public final GridLayout gridLayout; // // public final CutoutViewIndicator cvi; // public final CompoundButton unifiedButton; // public final CompoundButton orientationButton; // // public final ViewGroup root; // // public MainViewBinding(View root) { // this.root = (ViewGroup) root; // // toolbar = (Toolbar) root.findViewById(R.id.toolbar); // mainViewPager = (ViewPager) root.findViewById(R.id.mainViewPager); // fab = (FloatingActionButton) root.findViewById(R.id.fab); // // cvi = (CutoutViewIndicator) root.findViewById(R.id.cutoutViewIndicator); // // spacing = (NumberPicker) root.findViewById(R.id.spacingPicker); // width = (NumberPicker) root.findViewById(R.id.widthPicker); // height = (NumberPicker) root.findViewById(R.id.heightPicker); // // gridLayout = (GridLayout) root.findViewById(R.id.gridLayout); // // unifiedButton = (CompoundButton) root.findViewById(R.id.unifiedSwitch); // orientationButton = (CompoundButton) root.findViewById(R.id.orientationSwitch); // } // }
import java.util.List; import java.util.concurrent.TimeUnit; import static com.fuzz.indicator.BetterLayoutAssertions.verifyNoOverlaps; import static com.fuzz.indicator.Proxies.proxyForXCells; import static org.junit.Assert.assertEquals; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import com.fuzz.emptyhusk.InstrumentationAwareActivity; import com.fuzz.emptyhusk.MainViewBinding; import com.fuzz.indicator.proxy.StateProxy; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Test to make sure that the {@link com.fuzz.indicator.CutoutViewIndicator} * doesn't let any of its children overlap. The test runner will instantiate * a new instance of this test for every array returned by {@link #data()}. * * @author Philip Cohn-Cort (Fuzz) */ @RunWith(Parameterized.class) public class OverlapTest { protected static int maxCellCount = 30; @Parameterized.Parameters(name = "With {0} cells") public static Iterable<? extends Number[]> data() { List<Integer[]> retVal = new ArrayList<>(maxCellCount); for (int i = 0; i < maxCellCount; i++) { retVal.add(new Integer[]{i}); } return retVal; } @Rule
// Path: mobile/src/main/java/com/fuzz/emptyhusk/InstrumentationAwareActivity.java // public class InstrumentationAwareActivity extends AppCompatActivity { // // public MainViewBinding binding; // public PickerDelegate pickerDelegate; // // public ViewGroup inflationFrame; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // binding = new MainViewBinding(findViewById(R.id.root)); // pickerDelegate = new PickerDelegate(binding); // // setSupportActionBar(binding.toolbar); // // inflationFrame = (ViewGroup) getLayoutInflater().inflate(R.layout.test_frame, binding.root, false); // } // // public <T extends View> T inflateLayout(@LayoutRes int layoutId, Class<T> clazz) { // View inflated = getLayoutInflater().inflate(layoutId, inflationFrame, false); // return clazz.cast(inflated); // } // } // // Path: mobile/src/main/java/com/fuzz/emptyhusk/MainViewBinding.java // public class MainViewBinding { // public final Toolbar toolbar; // public final ViewPager mainViewPager; // public final FloatingActionButton fab; // // public final NumberPicker spacing; // public final NumberPicker width; // public final NumberPicker height; // public final GridLayout gridLayout; // // public final CutoutViewIndicator cvi; // public final CompoundButton unifiedButton; // public final CompoundButton orientationButton; // // public final ViewGroup root; // // public MainViewBinding(View root) { // this.root = (ViewGroup) root; // // toolbar = (Toolbar) root.findViewById(R.id.toolbar); // mainViewPager = (ViewPager) root.findViewById(R.id.mainViewPager); // fab = (FloatingActionButton) root.findViewById(R.id.fab); // // cvi = (CutoutViewIndicator) root.findViewById(R.id.cutoutViewIndicator); // // spacing = (NumberPicker) root.findViewById(R.id.spacingPicker); // width = (NumberPicker) root.findViewById(R.id.widthPicker); // height = (NumberPicker) root.findViewById(R.id.heightPicker); // // gridLayout = (GridLayout) root.findViewById(R.id.gridLayout); // // unifiedButton = (CompoundButton) root.findViewById(R.id.unifiedSwitch); // orientationButton = (CompoundButton) root.findViewById(R.id.orientationSwitch); // } // } // Path: mobile/src/androidTest/java/com/fuzz/indicator/OverlapTest.java import java.util.List; import java.util.concurrent.TimeUnit; import static com.fuzz.indicator.BetterLayoutAssertions.verifyNoOverlaps; import static com.fuzz.indicator.Proxies.proxyForXCells; import static org.junit.Assert.assertEquals; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import com.fuzz.emptyhusk.InstrumentationAwareActivity; import com.fuzz.emptyhusk.MainViewBinding; import com.fuzz.indicator.proxy.StateProxy; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Test to make sure that the {@link com.fuzz.indicator.CutoutViewIndicator} * doesn't let any of its children overlap. The test runner will instantiate * a new instance of this test for every array returned by {@link #data()}. * * @author Philip Cohn-Cort (Fuzz) */ @RunWith(Parameterized.class) public class OverlapTest { protected static int maxCellCount = 30; @Parameterized.Parameters(name = "With {0} cells") public static Iterable<? extends Number[]> data() { List<Integer[]> retVal = new ArrayList<>(maxCellCount); for (int i = 0; i < maxCellCount; i++) { retVal.add(new Integer[]{i}); } return retVal; } @Rule
public ActivityTestRule<InstrumentationAwareActivity> actRule
fuzz-productions/CutoutViewIndicator
mobile/src/androidTest/java/com/fuzz/indicator/OverlapTest.java
// Path: mobile/src/main/java/com/fuzz/emptyhusk/InstrumentationAwareActivity.java // public class InstrumentationAwareActivity extends AppCompatActivity { // // public MainViewBinding binding; // public PickerDelegate pickerDelegate; // // public ViewGroup inflationFrame; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // binding = new MainViewBinding(findViewById(R.id.root)); // pickerDelegate = new PickerDelegate(binding); // // setSupportActionBar(binding.toolbar); // // inflationFrame = (ViewGroup) getLayoutInflater().inflate(R.layout.test_frame, binding.root, false); // } // // public <T extends View> T inflateLayout(@LayoutRes int layoutId, Class<T> clazz) { // View inflated = getLayoutInflater().inflate(layoutId, inflationFrame, false); // return clazz.cast(inflated); // } // } // // Path: mobile/src/main/java/com/fuzz/emptyhusk/MainViewBinding.java // public class MainViewBinding { // public final Toolbar toolbar; // public final ViewPager mainViewPager; // public final FloatingActionButton fab; // // public final NumberPicker spacing; // public final NumberPicker width; // public final NumberPicker height; // public final GridLayout gridLayout; // // public final CutoutViewIndicator cvi; // public final CompoundButton unifiedButton; // public final CompoundButton orientationButton; // // public final ViewGroup root; // // public MainViewBinding(View root) { // this.root = (ViewGroup) root; // // toolbar = (Toolbar) root.findViewById(R.id.toolbar); // mainViewPager = (ViewPager) root.findViewById(R.id.mainViewPager); // fab = (FloatingActionButton) root.findViewById(R.id.fab); // // cvi = (CutoutViewIndicator) root.findViewById(R.id.cutoutViewIndicator); // // spacing = (NumberPicker) root.findViewById(R.id.spacingPicker); // width = (NumberPicker) root.findViewById(R.id.widthPicker); // height = (NumberPicker) root.findViewById(R.id.heightPicker); // // gridLayout = (GridLayout) root.findViewById(R.id.gridLayout); // // unifiedButton = (CompoundButton) root.findViewById(R.id.unifiedSwitch); // orientationButton = (CompoundButton) root.findViewById(R.id.orientationSwitch); // } // }
import java.util.List; import java.util.concurrent.TimeUnit; import static com.fuzz.indicator.BetterLayoutAssertions.verifyNoOverlaps; import static com.fuzz.indicator.Proxies.proxyForXCells; import static org.junit.Assert.assertEquals; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import com.fuzz.emptyhusk.InstrumentationAwareActivity; import com.fuzz.emptyhusk.MainViewBinding; import com.fuzz.indicator.proxy.StateProxy; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Test to make sure that the {@link com.fuzz.indicator.CutoutViewIndicator} * doesn't let any of its children overlap. The test runner will instantiate * a new instance of this test for every array returned by {@link #data()}. * * @author Philip Cohn-Cort (Fuzz) */ @RunWith(Parameterized.class) public class OverlapTest { protected static int maxCellCount = 30; @Parameterized.Parameters(name = "With {0} cells") public static Iterable<? extends Number[]> data() { List<Integer[]> retVal = new ArrayList<>(maxCellCount); for (int i = 0; i < maxCellCount; i++) { retVal.add(new Integer[]{i}); } return retVal; } @Rule public ActivityTestRule<InstrumentationAwareActivity> actRule = new ActivityTestRule<>(InstrumentationAwareActivity.class); @Rule public Timeout timeout = new Timeout(1, TimeUnit.MINUTES);
// Path: mobile/src/main/java/com/fuzz/emptyhusk/InstrumentationAwareActivity.java // public class InstrumentationAwareActivity extends AppCompatActivity { // // public MainViewBinding binding; // public PickerDelegate pickerDelegate; // // public ViewGroup inflationFrame; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // binding = new MainViewBinding(findViewById(R.id.root)); // pickerDelegate = new PickerDelegate(binding); // // setSupportActionBar(binding.toolbar); // // inflationFrame = (ViewGroup) getLayoutInflater().inflate(R.layout.test_frame, binding.root, false); // } // // public <T extends View> T inflateLayout(@LayoutRes int layoutId, Class<T> clazz) { // View inflated = getLayoutInflater().inflate(layoutId, inflationFrame, false); // return clazz.cast(inflated); // } // } // // Path: mobile/src/main/java/com/fuzz/emptyhusk/MainViewBinding.java // public class MainViewBinding { // public final Toolbar toolbar; // public final ViewPager mainViewPager; // public final FloatingActionButton fab; // // public final NumberPicker spacing; // public final NumberPicker width; // public final NumberPicker height; // public final GridLayout gridLayout; // // public final CutoutViewIndicator cvi; // public final CompoundButton unifiedButton; // public final CompoundButton orientationButton; // // public final ViewGroup root; // // public MainViewBinding(View root) { // this.root = (ViewGroup) root; // // toolbar = (Toolbar) root.findViewById(R.id.toolbar); // mainViewPager = (ViewPager) root.findViewById(R.id.mainViewPager); // fab = (FloatingActionButton) root.findViewById(R.id.fab); // // cvi = (CutoutViewIndicator) root.findViewById(R.id.cutoutViewIndicator); // // spacing = (NumberPicker) root.findViewById(R.id.spacingPicker); // width = (NumberPicker) root.findViewById(R.id.widthPicker); // height = (NumberPicker) root.findViewById(R.id.heightPicker); // // gridLayout = (GridLayout) root.findViewById(R.id.gridLayout); // // unifiedButton = (CompoundButton) root.findViewById(R.id.unifiedSwitch); // orientationButton = (CompoundButton) root.findViewById(R.id.orientationSwitch); // } // } // Path: mobile/src/androidTest/java/com/fuzz/indicator/OverlapTest.java import java.util.List; import java.util.concurrent.TimeUnit; import static com.fuzz.indicator.BetterLayoutAssertions.verifyNoOverlaps; import static com.fuzz.indicator.Proxies.proxyForXCells; import static org.junit.Assert.assertEquals; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import com.fuzz.emptyhusk.InstrumentationAwareActivity; import com.fuzz.emptyhusk.MainViewBinding; import com.fuzz.indicator.proxy.StateProxy; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.ArrayList; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Test to make sure that the {@link com.fuzz.indicator.CutoutViewIndicator} * doesn't let any of its children overlap. The test runner will instantiate * a new instance of this test for every array returned by {@link #data()}. * * @author Philip Cohn-Cort (Fuzz) */ @RunWith(Parameterized.class) public class OverlapTest { protected static int maxCellCount = 30; @Parameterized.Parameters(name = "With {0} cells") public static Iterable<? extends Number[]> data() { List<Integer[]> retVal = new ArrayList<>(maxCellCount); for (int i = 0; i < maxCellCount; i++) { retVal.add(new Integer[]{i}); } return retVal; } @Rule public ActivityTestRule<InstrumentationAwareActivity> actRule = new ActivityTestRule<>(InstrumentationAwareActivity.class); @Rule public Timeout timeout = new Timeout(1, TimeUnit.MINUTES);
private MainViewBinding binding;
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/cell/OffSetters.java
// Path: indicator/src/main/java/com/fuzz/indicator/style/MigratoryRange.java // public final class MigratoryRange<T extends Number & Comparable<T>> { // // public static abstract class Operator<T> { // @NonNull // public abstract T add(T lower, T offset); // } // // public static final Operator<Float> FLOAT_OPERATOR // = new Operator<Float>() { // @NonNull // @Override // public Float add(Float lower, Float offset) { // return lower + offset; // } // }; // // public static final Operator<Integer> INTEGER_OPERATOR // = new Operator<Integer>() { // @NonNull // @Override // public Integer add(Integer lower, Integer offset) { // return lower + offset; // } // }; // // public static MigratoryRange<Float> from(float lower, float upper) { // return new MigratoryRange<>(lower, upper, FLOAT_OPERATOR); // } // // public static MigratoryRange<Integer> from(int lower, int upper) { // return new MigratoryRange<>(lower, upper, INTEGER_OPERATOR); // } // // @NonNull // private final T lower; // @NonNull // private final T upper; // @NonNull // private final Operator<T> operator; // // public MigratoryRange(@NonNull T lower, @NonNull T upper, @NonNull Operator<T> operator) { // this.lower = lower; // this.upper = upper; // this.operator = operator; // // if (lower.compareTo(upper) > 0) { // throw new IllegalArgumentException("Migratory ranges may not have an upper bound below their lower bound."); // } // } // // @NonNull // public T getLower() { // return lower; // } // // @NonNull // public T getUpper() { // return upper; // } // // /** // * If the parameter is within this range it will be // * returned unaltered. If it isn't, the closest value // * within the range (e.g. {@link #getLower()} or // * {@link #getUpper()}) will be returned. // * // * @param value any non-null value of type T // * @return a value guaranteed to be within this range // */ // @NonNull // public T clamp(@NonNull T value) { // if (value.compareTo(lower) < 0) { // return lower; // } else if (value.compareTo(upper) > 0) { // return upper; // } else { // return value; // } // } // // public double diff() { // return upper.doubleValue() - lower.doubleValue(); // } // // public MigratoryRange<T> translate(@NonNull T offset) { // T newLower = operator.add(lower, offset); // T newUpper = operator.add(upper, offset); // return new MigratoryRange<>(newLower, newUpper, operator); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/style/MigratorySpan.java // public interface MigratorySpan { // // /** // * Consider a Spannable sequence which has a defined start and end. // * The MigratoryRange returned by this method represents some portion // * of indices within that sequence. Implementations are asked to // * <i>NOT</i> modify the parameter within this method. // * <p> // * Sample caller code may be as follows: // * <pre> // * MigratorySpan ms; // * Spannable target; // * // * //... // * // * MigratoryRange&lt;Integer&gt; bounds = ms.getCoverage(target); // * // * int start = bounds.getLower(); // * int end = bounds.getUpper(); // * // * target.setSpan(ms, start, end, ms.preferredFlags(0)); // * </pre> // * </p> // * // * @return a range which can be used to figure out what // * characters in the Spannable are covered. // * @param enclosingSequence the sequence of characters wherein this span // */ // @NonNull // MigratoryRange<Integer> getCoverage(Spannable enclosingSequence); // // /** // * Whatever is returned here should be a valid argument into // * {@link android.text.Spannable#setSpan(Object, int, int, int)}'s // * {@code flags} argument. Feel free to return the parameter directly // * if they don't need to change. // * // * @return a combination of valid span-laying-out flags // * @param previousFlags flags used for the previous layout - will // * be 0 if not currently attached to a // * {@link android.text.Spannable Spannable} // */ // int preferredFlags(int previousFlags); // }
import android.graphics.Matrix; import android.os.Build; import android.support.annotation.NonNull; import android.text.Spannable; import android.util.Property; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.style.MigratoryRange; import com.fuzz.indicator.style.MigratorySpan; import static android.os.Build.VERSION_CODES.KITKAT;
public static void offsetAlphaBy(@NonNull View imageView, float fraction) { setAlpha.set(imageView, fraction); } public static void offsetImageScaleBy(@NonNull ImageView imageView, float fraction) { Matrix matrix = new Matrix(imageView.getImageMatrix()); matrix.preScale(fraction, fraction); } public static void offsetScaleBy(@NonNull View imageView, float fraction) { imageView.setScaleX(fraction); imageView.setScaleY(fraction); } /** * Ensures that all spans of type {@link MigratorySpan} within {@code spannable} are * translated a proportional quantity of characters from their baseline position. Each * span's implementation of {@link MigratorySpan#getCoverage(Spannable)} is responsible * for reporting the correct baseline coverage prior to translation. * * @param spannable the text to which the spans are attached * @param fraction what proportion of the spannable should be considered offset. * values outside the range of 0..1 will be clamped into that * range. */ public static void offsetSpansBy(@NonNull Spannable spannable, float fraction) { int length = spannable.length(); int offset = (int) (fraction * length);
// Path: indicator/src/main/java/com/fuzz/indicator/style/MigratoryRange.java // public final class MigratoryRange<T extends Number & Comparable<T>> { // // public static abstract class Operator<T> { // @NonNull // public abstract T add(T lower, T offset); // } // // public static final Operator<Float> FLOAT_OPERATOR // = new Operator<Float>() { // @NonNull // @Override // public Float add(Float lower, Float offset) { // return lower + offset; // } // }; // // public static final Operator<Integer> INTEGER_OPERATOR // = new Operator<Integer>() { // @NonNull // @Override // public Integer add(Integer lower, Integer offset) { // return lower + offset; // } // }; // // public static MigratoryRange<Float> from(float lower, float upper) { // return new MigratoryRange<>(lower, upper, FLOAT_OPERATOR); // } // // public static MigratoryRange<Integer> from(int lower, int upper) { // return new MigratoryRange<>(lower, upper, INTEGER_OPERATOR); // } // // @NonNull // private final T lower; // @NonNull // private final T upper; // @NonNull // private final Operator<T> operator; // // public MigratoryRange(@NonNull T lower, @NonNull T upper, @NonNull Operator<T> operator) { // this.lower = lower; // this.upper = upper; // this.operator = operator; // // if (lower.compareTo(upper) > 0) { // throw new IllegalArgumentException("Migratory ranges may not have an upper bound below their lower bound."); // } // } // // @NonNull // public T getLower() { // return lower; // } // // @NonNull // public T getUpper() { // return upper; // } // // /** // * If the parameter is within this range it will be // * returned unaltered. If it isn't, the closest value // * within the range (e.g. {@link #getLower()} or // * {@link #getUpper()}) will be returned. // * // * @param value any non-null value of type T // * @return a value guaranteed to be within this range // */ // @NonNull // public T clamp(@NonNull T value) { // if (value.compareTo(lower) < 0) { // return lower; // } else if (value.compareTo(upper) > 0) { // return upper; // } else { // return value; // } // } // // public double diff() { // return upper.doubleValue() - lower.doubleValue(); // } // // public MigratoryRange<T> translate(@NonNull T offset) { // T newLower = operator.add(lower, offset); // T newUpper = operator.add(upper, offset); // return new MigratoryRange<>(newLower, newUpper, operator); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/style/MigratorySpan.java // public interface MigratorySpan { // // /** // * Consider a Spannable sequence which has a defined start and end. // * The MigratoryRange returned by this method represents some portion // * of indices within that sequence. Implementations are asked to // * <i>NOT</i> modify the parameter within this method. // * <p> // * Sample caller code may be as follows: // * <pre> // * MigratorySpan ms; // * Spannable target; // * // * //... // * // * MigratoryRange&lt;Integer&gt; bounds = ms.getCoverage(target); // * // * int start = bounds.getLower(); // * int end = bounds.getUpper(); // * // * target.setSpan(ms, start, end, ms.preferredFlags(0)); // * </pre> // * </p> // * // * @return a range which can be used to figure out what // * characters in the Spannable are covered. // * @param enclosingSequence the sequence of characters wherein this span // */ // @NonNull // MigratoryRange<Integer> getCoverage(Spannable enclosingSequence); // // /** // * Whatever is returned here should be a valid argument into // * {@link android.text.Spannable#setSpan(Object, int, int, int)}'s // * {@code flags} argument. Feel free to return the parameter directly // * if they don't need to change. // * // * @return a combination of valid span-laying-out flags // * @param previousFlags flags used for the previous layout - will // * be 0 if not currently attached to a // * {@link android.text.Spannable Spannable} // */ // int preferredFlags(int previousFlags); // } // Path: indicator/src/main/java/com/fuzz/indicator/cell/OffSetters.java import android.graphics.Matrix; import android.os.Build; import android.support.annotation.NonNull; import android.text.Spannable; import android.util.Property; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.style.MigratoryRange; import com.fuzz.indicator.style.MigratorySpan; import static android.os.Build.VERSION_CODES.KITKAT; public static void offsetAlphaBy(@NonNull View imageView, float fraction) { setAlpha.set(imageView, fraction); } public static void offsetImageScaleBy(@NonNull ImageView imageView, float fraction) { Matrix matrix = new Matrix(imageView.getImageMatrix()); matrix.preScale(fraction, fraction); } public static void offsetScaleBy(@NonNull View imageView, float fraction) { imageView.setScaleX(fraction); imageView.setScaleY(fraction); } /** * Ensures that all spans of type {@link MigratorySpan} within {@code spannable} are * translated a proportional quantity of characters from their baseline position. Each * span's implementation of {@link MigratorySpan#getCoverage(Spannable)} is responsible * for reporting the correct baseline coverage prior to translation. * * @param spannable the text to which the spans are attached * @param fraction what proportion of the spannable should be considered offset. * values outside the range of 0..1 will be clamped into that * range. */ public static void offsetSpansBy(@NonNull Spannable spannable, float fraction) { int length = spannable.length(); int offset = (int) (fraction * length);
MigratorySpan[] knownSpans = spannable.getSpans(0, length, MigratorySpan.class);
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/cell/OffSetters.java
// Path: indicator/src/main/java/com/fuzz/indicator/style/MigratoryRange.java // public final class MigratoryRange<T extends Number & Comparable<T>> { // // public static abstract class Operator<T> { // @NonNull // public abstract T add(T lower, T offset); // } // // public static final Operator<Float> FLOAT_OPERATOR // = new Operator<Float>() { // @NonNull // @Override // public Float add(Float lower, Float offset) { // return lower + offset; // } // }; // // public static final Operator<Integer> INTEGER_OPERATOR // = new Operator<Integer>() { // @NonNull // @Override // public Integer add(Integer lower, Integer offset) { // return lower + offset; // } // }; // // public static MigratoryRange<Float> from(float lower, float upper) { // return new MigratoryRange<>(lower, upper, FLOAT_OPERATOR); // } // // public static MigratoryRange<Integer> from(int lower, int upper) { // return new MigratoryRange<>(lower, upper, INTEGER_OPERATOR); // } // // @NonNull // private final T lower; // @NonNull // private final T upper; // @NonNull // private final Operator<T> operator; // // public MigratoryRange(@NonNull T lower, @NonNull T upper, @NonNull Operator<T> operator) { // this.lower = lower; // this.upper = upper; // this.operator = operator; // // if (lower.compareTo(upper) > 0) { // throw new IllegalArgumentException("Migratory ranges may not have an upper bound below their lower bound."); // } // } // // @NonNull // public T getLower() { // return lower; // } // // @NonNull // public T getUpper() { // return upper; // } // // /** // * If the parameter is within this range it will be // * returned unaltered. If it isn't, the closest value // * within the range (e.g. {@link #getLower()} or // * {@link #getUpper()}) will be returned. // * // * @param value any non-null value of type T // * @return a value guaranteed to be within this range // */ // @NonNull // public T clamp(@NonNull T value) { // if (value.compareTo(lower) < 0) { // return lower; // } else if (value.compareTo(upper) > 0) { // return upper; // } else { // return value; // } // } // // public double diff() { // return upper.doubleValue() - lower.doubleValue(); // } // // public MigratoryRange<T> translate(@NonNull T offset) { // T newLower = operator.add(lower, offset); // T newUpper = operator.add(upper, offset); // return new MigratoryRange<>(newLower, newUpper, operator); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/style/MigratorySpan.java // public interface MigratorySpan { // // /** // * Consider a Spannable sequence which has a defined start and end. // * The MigratoryRange returned by this method represents some portion // * of indices within that sequence. Implementations are asked to // * <i>NOT</i> modify the parameter within this method. // * <p> // * Sample caller code may be as follows: // * <pre> // * MigratorySpan ms; // * Spannable target; // * // * //... // * // * MigratoryRange&lt;Integer&gt; bounds = ms.getCoverage(target); // * // * int start = bounds.getLower(); // * int end = bounds.getUpper(); // * // * target.setSpan(ms, start, end, ms.preferredFlags(0)); // * </pre> // * </p> // * // * @return a range which can be used to figure out what // * characters in the Spannable are covered. // * @param enclosingSequence the sequence of characters wherein this span // */ // @NonNull // MigratoryRange<Integer> getCoverage(Spannable enclosingSequence); // // /** // * Whatever is returned here should be a valid argument into // * {@link android.text.Spannable#setSpan(Object, int, int, int)}'s // * {@code flags} argument. Feel free to return the parameter directly // * if they don't need to change. // * // * @return a combination of valid span-laying-out flags // * @param previousFlags flags used for the previous layout - will // * be 0 if not currently attached to a // * {@link android.text.Spannable Spannable} // */ // int preferredFlags(int previousFlags); // }
import android.graphics.Matrix; import android.os.Build; import android.support.annotation.NonNull; import android.text.Spannable; import android.util.Property; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.style.MigratoryRange; import com.fuzz.indicator.style.MigratorySpan; import static android.os.Build.VERSION_CODES.KITKAT;
setAlpha.set(imageView, fraction); } public static void offsetImageScaleBy(@NonNull ImageView imageView, float fraction) { Matrix matrix = new Matrix(imageView.getImageMatrix()); matrix.preScale(fraction, fraction); } public static void offsetScaleBy(@NonNull View imageView, float fraction) { imageView.setScaleX(fraction); imageView.setScaleY(fraction); } /** * Ensures that all spans of type {@link MigratorySpan} within {@code spannable} are * translated a proportional quantity of characters from their baseline position. Each * span's implementation of {@link MigratorySpan#getCoverage(Spannable)} is responsible * for reporting the correct baseline coverage prior to translation. * * @param spannable the text to which the spans are attached * @param fraction what proportion of the spannable should be considered offset. * values outside the range of 0..1 will be clamped into that * range. */ public static void offsetSpansBy(@NonNull Spannable spannable, float fraction) { int length = spannable.length(); int offset = (int) (fraction * length); MigratorySpan[] knownSpans = spannable.getSpans(0, length, MigratorySpan.class); if (knownSpans.length > 0) {
// Path: indicator/src/main/java/com/fuzz/indicator/style/MigratoryRange.java // public final class MigratoryRange<T extends Number & Comparable<T>> { // // public static abstract class Operator<T> { // @NonNull // public abstract T add(T lower, T offset); // } // // public static final Operator<Float> FLOAT_OPERATOR // = new Operator<Float>() { // @NonNull // @Override // public Float add(Float lower, Float offset) { // return lower + offset; // } // }; // // public static final Operator<Integer> INTEGER_OPERATOR // = new Operator<Integer>() { // @NonNull // @Override // public Integer add(Integer lower, Integer offset) { // return lower + offset; // } // }; // // public static MigratoryRange<Float> from(float lower, float upper) { // return new MigratoryRange<>(lower, upper, FLOAT_OPERATOR); // } // // public static MigratoryRange<Integer> from(int lower, int upper) { // return new MigratoryRange<>(lower, upper, INTEGER_OPERATOR); // } // // @NonNull // private final T lower; // @NonNull // private final T upper; // @NonNull // private final Operator<T> operator; // // public MigratoryRange(@NonNull T lower, @NonNull T upper, @NonNull Operator<T> operator) { // this.lower = lower; // this.upper = upper; // this.operator = operator; // // if (lower.compareTo(upper) > 0) { // throw new IllegalArgumentException("Migratory ranges may not have an upper bound below their lower bound."); // } // } // // @NonNull // public T getLower() { // return lower; // } // // @NonNull // public T getUpper() { // return upper; // } // // /** // * If the parameter is within this range it will be // * returned unaltered. If it isn't, the closest value // * within the range (e.g. {@link #getLower()} or // * {@link #getUpper()}) will be returned. // * // * @param value any non-null value of type T // * @return a value guaranteed to be within this range // */ // @NonNull // public T clamp(@NonNull T value) { // if (value.compareTo(lower) < 0) { // return lower; // } else if (value.compareTo(upper) > 0) { // return upper; // } else { // return value; // } // } // // public double diff() { // return upper.doubleValue() - lower.doubleValue(); // } // // public MigratoryRange<T> translate(@NonNull T offset) { // T newLower = operator.add(lower, offset); // T newUpper = operator.add(upper, offset); // return new MigratoryRange<>(newLower, newUpper, operator); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/style/MigratorySpan.java // public interface MigratorySpan { // // /** // * Consider a Spannable sequence which has a defined start and end. // * The MigratoryRange returned by this method represents some portion // * of indices within that sequence. Implementations are asked to // * <i>NOT</i> modify the parameter within this method. // * <p> // * Sample caller code may be as follows: // * <pre> // * MigratorySpan ms; // * Spannable target; // * // * //... // * // * MigratoryRange&lt;Integer&gt; bounds = ms.getCoverage(target); // * // * int start = bounds.getLower(); // * int end = bounds.getUpper(); // * // * target.setSpan(ms, start, end, ms.preferredFlags(0)); // * </pre> // * </p> // * // * @return a range which can be used to figure out what // * characters in the Spannable are covered. // * @param enclosingSequence the sequence of characters wherein this span // */ // @NonNull // MigratoryRange<Integer> getCoverage(Spannable enclosingSequence); // // /** // * Whatever is returned here should be a valid argument into // * {@link android.text.Spannable#setSpan(Object, int, int, int)}'s // * {@code flags} argument. Feel free to return the parameter directly // * if they don't need to change. // * // * @return a combination of valid span-laying-out flags // * @param previousFlags flags used for the previous layout - will // * be 0 if not currently attached to a // * {@link android.text.Spannable Spannable} // */ // int preferredFlags(int previousFlags); // } // Path: indicator/src/main/java/com/fuzz/indicator/cell/OffSetters.java import android.graphics.Matrix; import android.os.Build; import android.support.annotation.NonNull; import android.text.Spannable; import android.util.Property; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.style.MigratoryRange; import com.fuzz.indicator.style.MigratorySpan; import static android.os.Build.VERSION_CODES.KITKAT; setAlpha.set(imageView, fraction); } public static void offsetImageScaleBy(@NonNull ImageView imageView, float fraction) { Matrix matrix = new Matrix(imageView.getImageMatrix()); matrix.preScale(fraction, fraction); } public static void offsetScaleBy(@NonNull View imageView, float fraction) { imageView.setScaleX(fraction); imageView.setScaleY(fraction); } /** * Ensures that all spans of type {@link MigratorySpan} within {@code spannable} are * translated a proportional quantity of characters from their baseline position. Each * span's implementation of {@link MigratorySpan#getCoverage(Spannable)} is responsible * for reporting the correct baseline coverage prior to translation. * * @param spannable the text to which the spans are attached * @param fraction what proportion of the spannable should be considered offset. * values outside the range of 0..1 will be clamped into that * range. */ public static void offsetSpansBy(@NonNull Spannable spannable, float fraction) { int length = spannable.length(); int offset = (int) (fraction * length); MigratorySpan[] knownSpans = spannable.getSpans(0, length, MigratorySpan.class); if (knownSpans.length > 0) {
MigratoryRange<Integer> fullSize = MigratoryRange.from(0, length);
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/CutoutViewIndicator.java
// Path: indicator/src/main/java/com/fuzz/indicator/cell/CutoutCell.java // public interface CutoutCell { // // /** // * Perform some arbitrary action to represent the provided OffsetEvent. // * // * @param offsetEvent whatever just happened // * @see OffSetters // */ // void offsetContentBy(@NonNull IndicatorOffsetEvent offsetEvent); // // /** // * @return the actual view represented by this object // */ // @NonNull // View getItemView(); // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ViewProvidingStateProxy.java // public interface ViewProvidingStateProxy extends StateProxy { // /** // * In some use cases, it may be handy to have a reference to the original // * View when binding a representation thereof. See // * {@link CutoutCellGenerator#onBindChild(View, CutoutViewLayoutParams, View)} // * for details. // * // * @param cviPosition position of a child within the CutoutViewIndicator // * @return the view which directly inspired the indicator's child // */ // @Nullable // View getOriginalViewFor(int cviPosition); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.database.DataSetObserver; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.cell.CutoutCell; import com.fuzz.indicator.cell.CutoutTextCell; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; import com.fuzz.indicator.proxy.StateProxy; import com.fuzz.indicator.proxy.UnavailableProxy; import com.fuzz.indicator.proxy.ViewProvidingStateProxy; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * A RecyclerView-inspired ViewGroup for showing an indicator traversing multiple child Views ('cells'). * <p> * There's a nice monospace line drawing in the javadoc for {@link #showOffsetIndicator(int, float)} that basically sums up * its appearance when operating under an {@link ImageCellGenerator}. * </p> * * @author Philip Cohn-Cort (Fuzz) */ public class CutoutViewIndicator extends LinearLayout implements ProxyReference { private static final String TAG = CutoutViewIndicator.class.getSimpleName(); /** * Specialised implementation of {@link UnavailableProxy} for use with * {@linkplain #isInEditMode() the preview tools}. */ protected static final UnavailableProxy EDIT_MODE_PROXY = new UnavailableProxy() { @Override public IndicatorOffsetEvent resendPositionInfo(ProxyReference cvi, float pos) { return IndicatorOffsetEvent.from(cvi, pos); } }; /** * This holds onto the views that may be attached to this ViewGroup. It's initialised * with space for 5 values because practical experience says that space for 10 would * be excessive. * <p> * This is kinda micro-optimising since it can expand automatically later. * </p> */ @NonNull
// Path: indicator/src/main/java/com/fuzz/indicator/cell/CutoutCell.java // public interface CutoutCell { // // /** // * Perform some arbitrary action to represent the provided OffsetEvent. // * // * @param offsetEvent whatever just happened // * @see OffSetters // */ // void offsetContentBy(@NonNull IndicatorOffsetEvent offsetEvent); // // /** // * @return the actual view represented by this object // */ // @NonNull // View getItemView(); // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ViewProvidingStateProxy.java // public interface ViewProvidingStateProxy extends StateProxy { // /** // * In some use cases, it may be handy to have a reference to the original // * View when binding a representation thereof. See // * {@link CutoutCellGenerator#onBindChild(View, CutoutViewLayoutParams, View)} // * for details. // * // * @param cviPosition position of a child within the CutoutViewIndicator // * @return the view which directly inspired the indicator's child // */ // @Nullable // View getOriginalViewFor(int cviPosition); // } // Path: indicator/src/main/java/com/fuzz/indicator/CutoutViewIndicator.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.database.DataSetObserver; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.cell.CutoutCell; import com.fuzz.indicator.cell.CutoutTextCell; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; import com.fuzz.indicator.proxy.StateProxy; import com.fuzz.indicator.proxy.UnavailableProxy; import com.fuzz.indicator.proxy.ViewProvidingStateProxy; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * A RecyclerView-inspired ViewGroup for showing an indicator traversing multiple child Views ('cells'). * <p> * There's a nice monospace line drawing in the javadoc for {@link #showOffsetIndicator(int, float)} that basically sums up * its appearance when operating under an {@link ImageCellGenerator}. * </p> * * @author Philip Cohn-Cort (Fuzz) */ public class CutoutViewIndicator extends LinearLayout implements ProxyReference { private static final String TAG = CutoutViewIndicator.class.getSimpleName(); /** * Specialised implementation of {@link UnavailableProxy} for use with * {@linkplain #isInEditMode() the preview tools}. */ protected static final UnavailableProxy EDIT_MODE_PROXY = new UnavailableProxy() { @Override public IndicatorOffsetEvent resendPositionInfo(ProxyReference cvi, float pos) { return IndicatorOffsetEvent.from(cvi, pos); } }; /** * This holds onto the views that may be attached to this ViewGroup. It's initialised * with space for 5 values because practical experience says that space for 10 would * be excessive. * <p> * This is kinda micro-optimising since it can expand automatically later. * </p> */ @NonNull
protected SparseArray<CutoutCell> cells = new SparseArray<>(5);
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/CutoutViewIndicator.java
// Path: indicator/src/main/java/com/fuzz/indicator/cell/CutoutCell.java // public interface CutoutCell { // // /** // * Perform some arbitrary action to represent the provided OffsetEvent. // * // * @param offsetEvent whatever just happened // * @see OffSetters // */ // void offsetContentBy(@NonNull IndicatorOffsetEvent offsetEvent); // // /** // * @return the actual view represented by this object // */ // @NonNull // View getItemView(); // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ViewProvidingStateProxy.java // public interface ViewProvidingStateProxy extends StateProxy { // /** // * In some use cases, it may be handy to have a reference to the original // * View when binding a representation thereof. See // * {@link CutoutCellGenerator#onBindChild(View, CutoutViewLayoutParams, View)} // * for details. // * // * @param cviPosition position of a child within the CutoutViewIndicator // * @return the view which directly inspired the indicator's child // */ // @Nullable // View getOriginalViewFor(int cviPosition); // }
import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.database.DataSetObserver; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.cell.CutoutCell; import com.fuzz.indicator.cell.CutoutTextCell; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; import com.fuzz.indicator.proxy.StateProxy; import com.fuzz.indicator.proxy.UnavailableProxy; import com.fuzz.indicator.proxy.ViewProvidingStateProxy; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
} else { cellLength = lp.cellLength; perpendicularLength = lp.perpendicularLength; internalSpacing = lp.internalSpacing; } final int left, top; if (getOrientation() == HORIZONTAL) { lp.width = cellLength; lp.height = perpendicularLength; left = (position == 0) ? 0 : internalSpacing; top = 0; } else { lp.width = perpendicularLength; lp.height = cellLength; left = 0; top = (position == 0) ? 0 : internalSpacing; } lp.setMargins(left, top, 0, 0); lp.gravity = Gravity.CENTER; if (isInEditMode() && lp.cellBackgroundId <= 0 && lp.indicatorDrawableId <= 0) { String tag = "resources.unusual"; String message = "Note that CutoutViewIndicator's generated views will not appear" + " unless you provide it with a positive drawable id" + " (i.e. for the attribute rcv_drawable)."; logger.logToLayoutLib(tag, message); } View originator;
// Path: indicator/src/main/java/com/fuzz/indicator/cell/CutoutCell.java // public interface CutoutCell { // // /** // * Perform some arbitrary action to represent the provided OffsetEvent. // * // * @param offsetEvent whatever just happened // * @see OffSetters // */ // void offsetContentBy(@NonNull IndicatorOffsetEvent offsetEvent); // // /** // * @return the actual view represented by this object // */ // @NonNull // View getItemView(); // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ViewProvidingStateProxy.java // public interface ViewProvidingStateProxy extends StateProxy { // /** // * In some use cases, it may be handy to have a reference to the original // * View when binding a representation thereof. See // * {@link CutoutCellGenerator#onBindChild(View, CutoutViewLayoutParams, View)} // * for details. // * // * @param cviPosition position of a child within the CutoutViewIndicator // * @return the view which directly inspired the indicator's child // */ // @Nullable // View getOriginalViewFor(int cviPosition); // } // Path: indicator/src/main/java/com/fuzz/indicator/CutoutViewIndicator.java import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.database.Cursor; import android.database.DataSetObserver; import android.os.Build; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.Log; import android.util.SparseArray; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fuzz.indicator.cell.CutoutCell; import com.fuzz.indicator.cell.CutoutTextCell; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; import com.fuzz.indicator.proxy.StateProxy; import com.fuzz.indicator.proxy.UnavailableProxy; import com.fuzz.indicator.proxy.ViewProvidingStateProxy; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; } else { cellLength = lp.cellLength; perpendicularLength = lp.perpendicularLength; internalSpacing = lp.internalSpacing; } final int left, top; if (getOrientation() == HORIZONTAL) { lp.width = cellLength; lp.height = perpendicularLength; left = (position == 0) ? 0 : internalSpacing; top = 0; } else { lp.width = perpendicularLength; lp.height = cellLength; left = 0; top = (position == 0) ? 0 : internalSpacing; } lp.setMargins(left, top, 0, 0); lp.gravity = Gravity.CENTER; if (isInEditMode() && lp.cellBackgroundId <= 0 && lp.indicatorDrawableId <= 0) { String tag = "resources.unusual"; String message = "Note that CutoutViewIndicator's generated views will not appear" + " unless you provide it with a positive drawable id" + " (i.e. for the attribute rcv_drawable)."; logger.logToLayoutLib(tag, message); } View originator;
if (stateProxy instanceof ViewProvidingStateProxy) {
fuzz-productions/CutoutViewIndicator
indicator/src/main/java/com/fuzz/indicator/ViewPagerStateProxy.java
// Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ViewProvidingStateProxy.java // public interface ViewProvidingStateProxy extends StateProxy { // /** // * In some use cases, it may be handy to have a reference to the original // * View when binding a representation thereof. See // * {@link CutoutCellGenerator#onBindChild(View, CutoutViewLayoutParams, View)} // * for details. // * // * @param cviPosition position of a child within the CutoutViewIndicator // * @return the view which directly inspired the indicator's child // */ // @Nullable // View getOriginalViewFor(int cviPosition); // }
import android.database.DataSetObserver; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; import com.fuzz.indicator.proxy.StateProxy; import com.fuzz.indicator.proxy.ViewProvidingStateProxy;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * {@link StateProxy} wrapper around a {@link ViewPager}. All calls * are delegated to this object. * <p> * Due to the rather strict register/unregister nature of the * {@link android.database.Observable Observable} object backing each * {@link PagerAdapter}, every call to * {@link #associateWith(DataSetObserver)} must be paired with one to * {@link #disassociateFrom(DataSetObserver)}. * </p> * * @author Philip Cohn-Cort (Fuzz) */ public class ViewPagerStateProxy implements ViewProvidingStateProxy { @NonNull private final ViewPager pager; @NonNull private OnViewPagerChangeListener pageChangeListener; public ViewPagerStateProxy(@NonNull ViewPager pager, @NonNull CutoutViewIndicator cvi) { this.pager = pager; this.pageChangeListener = new OnViewPagerChangeListener(cvi); } @Override public float getCurrentPosition() { // Seriously. They called this the 'CurrentItem'. Can you believe it? return pager.getCurrentItem(); } @Override public int getCellCount() { return pager.getAdapter().getCount(); } @Override
// Path: indicator/src/main/java/com/fuzz/indicator/proxy/ProxyReference.java // public interface ProxyReference { // /** // * Modifies the passed-in value to represent a valid child position in this // * {@link CutoutViewIndicator}. // * @param proposed a proposed position index // * @return the corrected value // */ // int fixPosition(int proposed); // // } // // Path: indicator/src/main/java/com/fuzz/indicator/proxy/ViewProvidingStateProxy.java // public interface ViewProvidingStateProxy extends StateProxy { // /** // * In some use cases, it may be handy to have a reference to the original // * View when binding a representation thereof. See // * {@link CutoutCellGenerator#onBindChild(View, CutoutViewLayoutParams, View)} // * for details. // * // * @param cviPosition position of a child within the CutoutViewIndicator // * @return the view which directly inspired the indicator's child // */ // @Nullable // View getOriginalViewFor(int cviPosition); // } // Path: indicator/src/main/java/com/fuzz/indicator/ViewPagerStateProxy.java import android.database.DataSetObserver; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import com.fuzz.indicator.proxy.IndicatorOffsetEvent; import com.fuzz.indicator.proxy.ProxyReference; import com.fuzz.indicator.proxy.StateProxy; import com.fuzz.indicator.proxy.ViewProvidingStateProxy; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * {@link StateProxy} wrapper around a {@link ViewPager}. All calls * are delegated to this object. * <p> * Due to the rather strict register/unregister nature of the * {@link android.database.Observable Observable} object backing each * {@link PagerAdapter}, every call to * {@link #associateWith(DataSetObserver)} must be paired with one to * {@link #disassociateFrom(DataSetObserver)}. * </p> * * @author Philip Cohn-Cort (Fuzz) */ public class ViewPagerStateProxy implements ViewProvidingStateProxy { @NonNull private final ViewPager pager; @NonNull private OnViewPagerChangeListener pageChangeListener; public ViewPagerStateProxy(@NonNull ViewPager pager, @NonNull CutoutViewIndicator cvi) { this.pager = pager; this.pageChangeListener = new OnViewPagerChangeListener(cvi); } @Override public float getCurrentPosition() { // Seriously. They called this the 'CurrentItem'. Can you believe it? return pager.getCurrentItem(); } @Override public int getCellCount() { return pager.getAdapter().getCount(); } @Override
public IndicatorOffsetEvent resendPositionInfo(ProxyReference cvi, float assumedIndicatorPosition) {
fuzz-productions/CutoutViewIndicator
mobile/src/androidTest/java/com/fuzz/indicator/CutoutViewIndicatorAttributesTest.java
// Path: mobile/src/main/java/com/fuzz/emptyhusk/InstrumentationAwareActivity.java // public class InstrumentationAwareActivity extends AppCompatActivity { // // public MainViewBinding binding; // public PickerDelegate pickerDelegate; // // public ViewGroup inflationFrame; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // binding = new MainViewBinding(findViewById(R.id.root)); // pickerDelegate = new PickerDelegate(binding); // // setSupportActionBar(binding.toolbar); // // inflationFrame = (ViewGroup) getLayoutInflater().inflate(R.layout.test_frame, binding.root, false); // } // // public <T extends View> T inflateLayout(@LayoutRes int layoutId, Class<T> clazz) { // View inflated = getLayoutInflater().inflate(layoutId, inflationFrame, false); // return clazz.cast(inflated); // } // }
import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.widget.FrameLayout; import com.fuzz.emptyhusk.InstrumentationAwareActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import java.util.concurrent.TimeUnit; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON; import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD; import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; import static android.view.WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Tests to make sure that the {@link com.fuzz.indicator.CutoutViewIndicator} * is inflated correctly. * * @author Philip Cohn-Cort (Fuzz) */ public class CutoutViewIndicatorAttributesTest { @Rule
// Path: mobile/src/main/java/com/fuzz/emptyhusk/InstrumentationAwareActivity.java // public class InstrumentationAwareActivity extends AppCompatActivity { // // public MainViewBinding binding; // public PickerDelegate pickerDelegate; // // public ViewGroup inflationFrame; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // // binding = new MainViewBinding(findViewById(R.id.root)); // pickerDelegate = new PickerDelegate(binding); // // setSupportActionBar(binding.toolbar); // // inflationFrame = (ViewGroup) getLayoutInflater().inflate(R.layout.test_frame, binding.root, false); // } // // public <T extends View> T inflateLayout(@LayoutRes int layoutId, Class<T> clazz) { // View inflated = getLayoutInflater().inflate(layoutId, inflationFrame, false); // return clazz.cast(inflated); // } // } // Path: mobile/src/androidTest/java/com/fuzz/indicator/CutoutViewIndicatorAttributesTest.java import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import android.widget.FrameLayout; import com.fuzz.emptyhusk.InstrumentationAwareActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import java.util.concurrent.TimeUnit; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON; import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD; import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; import static android.view.WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON; import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.indicator; /** * Tests to make sure that the {@link com.fuzz.indicator.CutoutViewIndicator} * is inflated correctly. * * @author Philip Cohn-Cort (Fuzz) */ public class CutoutViewIndicatorAttributesTest { @Rule
public ActivityTestRule<InstrumentationAwareActivity> actRule
fuzz-productions/CutoutViewIndicator
mobile/src/main/java/com/fuzz/emptyhusk/choosegenerator/GeneratorChoiceAdapter.java
// Path: mobile/src/main/java/com/fuzz/emptyhusk/BoldTextCellGenerator.java // public class BoldTextCellGenerator extends TextCellGenerator { // @NonNull // @Override // protected Spannable getTextFor(@NonNull Context context, int position) { // String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages); // // SpannableString ssb = new SpannableString(introStrings[position]); // MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD); // // // Order matters when setting spans. The base color must be in place first // // ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorSecondary)); // ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // // // Only then should custom MigratorySpans be set. // // MigratoryRange<Integer> coverage = span.getCoverage(ssb); // int start = coverage.getLower(); // int end = coverage.getUpper(); // ssb.setSpan(span, start, end, span.preferredFlags(0)); // // MigratoryForegroundColorSpan boldColorSpan = new MigratoryForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent)); // ssb.setSpan(boldColorSpan, start, end, boldColorSpan.preferredFlags(0)); // // return ssb; // } // // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/SequentialCellGenerator.java // public class SequentialCellGenerator extends ImageCellGenerator { // // @NonNull // private String textMask = "~|%d|~"; // // public SequentialCellGenerator() { // } // // public SequentialCellGenerator(@NonNull Context context, @NonNull AttributeSet attrs, int defAttr) { // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CutoutViewIndicator, defAttr, 0); // String textMask = a.getString(R.styleable.CutoutViewIndicator_rcv_generator_text_mask); // if (textMask != null) { // setTextMask(textMask); // } // a.recycle(); // } // // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new TextClippedImageView(parent.getContext()); // } // // @Override // public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) { // child.setBackgroundResource(lp.cellBackgroundId); // if (child instanceof TextClippedImageView) { // if (!((TextClippedImageView)child).hasTextMask()) { // // Child mask is not set - propagate our default value // String mask = getMaskFor(lp); // ((TextClippedImageView) child).setTextMaskPath(mask); // } // bindImageToChild((ImageView) child, lp); // } else { // super.onBindChild(child, lp, originator); // } // } // // /** // * Set a new string to be used as base mask by {@link #getMaskFor(CutoutViewLayoutParams)}. // * // * @param textMask a string, with at most one {@code %d} where the position should go. // */ // public void setTextMask(@NonNull String textMask) { // this.textMask = textMask; // } // // /** // * The returned string will be used as a sort of clipping path for child views, // * provided that the children are instances of {@link TextClippedImageView}. // * // * @param lp the layout params of the associated view // * @return a string used for masking. return an empty string and // * the child view will draw absolutely nothing // * @see TextClippedImageView#setTextMaskPath(String) // */ // @NonNull // public String getMaskFor(@NonNull CutoutViewLayoutParams lp) { // return String.format(Locale.getDefault(), textMask, lp.position); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/ClippedImageCellGenerator.java // public class ClippedImageCellGenerator extends ImageCellGenerator { // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new ClippedImageView(parent.getContext()); // } // }
import java.util.List; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.fuzz.emptyhusk.BoldTextCellGenerator; import com.fuzz.emptyhusk.R; import com.fuzz.indicator.ImageCellGenerator; import com.fuzz.indicator.CutoutCellGenerator; import com.fuzz.indicator.clip.SequentialCellGenerator; import com.fuzz.indicator.clip.ClippedImageCellGenerator; import java.util.ArrayList;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.emptyhusk.choosegenerator; /** * @author Philip Cohn-Cort (Fuzz) */ public class GeneratorChoiceAdapter extends RecyclerView.Adapter { @NonNull private List<GeneratorChoice> choices = new ArrayList<>(); @NonNull private Class<? extends CutoutCellGenerator> chosen = ImageCellGenerator.class; public GeneratorChoiceAdapter() { choices.add(new GeneratorChoice(ImageCellGenerator.class, "Creates simple ImageViews. These are offset with X or Y translations. A classic choice with static background and dynamic content."));
// Path: mobile/src/main/java/com/fuzz/emptyhusk/BoldTextCellGenerator.java // public class BoldTextCellGenerator extends TextCellGenerator { // @NonNull // @Override // protected Spannable getTextFor(@NonNull Context context, int position) { // String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages); // // SpannableString ssb = new SpannableString(introStrings[position]); // MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD); // // // Order matters when setting spans. The base color must be in place first // // ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorSecondary)); // ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // // // Only then should custom MigratorySpans be set. // // MigratoryRange<Integer> coverage = span.getCoverage(ssb); // int start = coverage.getLower(); // int end = coverage.getUpper(); // ssb.setSpan(span, start, end, span.preferredFlags(0)); // // MigratoryForegroundColorSpan boldColorSpan = new MigratoryForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent)); // ssb.setSpan(boldColorSpan, start, end, boldColorSpan.preferredFlags(0)); // // return ssb; // } // // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/SequentialCellGenerator.java // public class SequentialCellGenerator extends ImageCellGenerator { // // @NonNull // private String textMask = "~|%d|~"; // // public SequentialCellGenerator() { // } // // public SequentialCellGenerator(@NonNull Context context, @NonNull AttributeSet attrs, int defAttr) { // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CutoutViewIndicator, defAttr, 0); // String textMask = a.getString(R.styleable.CutoutViewIndicator_rcv_generator_text_mask); // if (textMask != null) { // setTextMask(textMask); // } // a.recycle(); // } // // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new TextClippedImageView(parent.getContext()); // } // // @Override // public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) { // child.setBackgroundResource(lp.cellBackgroundId); // if (child instanceof TextClippedImageView) { // if (!((TextClippedImageView)child).hasTextMask()) { // // Child mask is not set - propagate our default value // String mask = getMaskFor(lp); // ((TextClippedImageView) child).setTextMaskPath(mask); // } // bindImageToChild((ImageView) child, lp); // } else { // super.onBindChild(child, lp, originator); // } // } // // /** // * Set a new string to be used as base mask by {@link #getMaskFor(CutoutViewLayoutParams)}. // * // * @param textMask a string, with at most one {@code %d} where the position should go. // */ // public void setTextMask(@NonNull String textMask) { // this.textMask = textMask; // } // // /** // * The returned string will be used as a sort of clipping path for child views, // * provided that the children are instances of {@link TextClippedImageView}. // * // * @param lp the layout params of the associated view // * @return a string used for masking. return an empty string and // * the child view will draw absolutely nothing // * @see TextClippedImageView#setTextMaskPath(String) // */ // @NonNull // public String getMaskFor(@NonNull CutoutViewLayoutParams lp) { // return String.format(Locale.getDefault(), textMask, lp.position); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/ClippedImageCellGenerator.java // public class ClippedImageCellGenerator extends ImageCellGenerator { // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new ClippedImageView(parent.getContext()); // } // } // Path: mobile/src/main/java/com/fuzz/emptyhusk/choosegenerator/GeneratorChoiceAdapter.java import java.util.List; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.fuzz.emptyhusk.BoldTextCellGenerator; import com.fuzz.emptyhusk.R; import com.fuzz.indicator.ImageCellGenerator; import com.fuzz.indicator.CutoutCellGenerator; import com.fuzz.indicator.clip.SequentialCellGenerator; import com.fuzz.indicator.clip.ClippedImageCellGenerator; import java.util.ArrayList; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.emptyhusk.choosegenerator; /** * @author Philip Cohn-Cort (Fuzz) */ public class GeneratorChoiceAdapter extends RecyclerView.Adapter { @NonNull private List<GeneratorChoice> choices = new ArrayList<>(); @NonNull private Class<? extends CutoutCellGenerator> chosen = ImageCellGenerator.class; public GeneratorChoiceAdapter() { choices.add(new GeneratorChoice(ImageCellGenerator.class, "Creates simple ImageViews. These are offset with X or Y translations. A classic choice with static background and dynamic content."));
choices.add(new GeneratorChoice(ClippedImageCellGenerator.class, "Creates ClippedImageViews. These are offset with X or Y translations. Stylish, yet ever so slightly heavier memory-wise than ImageCellGenerator."));
fuzz-productions/CutoutViewIndicator
mobile/src/main/java/com/fuzz/emptyhusk/choosegenerator/GeneratorChoiceAdapter.java
// Path: mobile/src/main/java/com/fuzz/emptyhusk/BoldTextCellGenerator.java // public class BoldTextCellGenerator extends TextCellGenerator { // @NonNull // @Override // protected Spannable getTextFor(@NonNull Context context, int position) { // String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages); // // SpannableString ssb = new SpannableString(introStrings[position]); // MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD); // // // Order matters when setting spans. The base color must be in place first // // ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorSecondary)); // ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // // // Only then should custom MigratorySpans be set. // // MigratoryRange<Integer> coverage = span.getCoverage(ssb); // int start = coverage.getLower(); // int end = coverage.getUpper(); // ssb.setSpan(span, start, end, span.preferredFlags(0)); // // MigratoryForegroundColorSpan boldColorSpan = new MigratoryForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent)); // ssb.setSpan(boldColorSpan, start, end, boldColorSpan.preferredFlags(0)); // // return ssb; // } // // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/SequentialCellGenerator.java // public class SequentialCellGenerator extends ImageCellGenerator { // // @NonNull // private String textMask = "~|%d|~"; // // public SequentialCellGenerator() { // } // // public SequentialCellGenerator(@NonNull Context context, @NonNull AttributeSet attrs, int defAttr) { // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CutoutViewIndicator, defAttr, 0); // String textMask = a.getString(R.styleable.CutoutViewIndicator_rcv_generator_text_mask); // if (textMask != null) { // setTextMask(textMask); // } // a.recycle(); // } // // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new TextClippedImageView(parent.getContext()); // } // // @Override // public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) { // child.setBackgroundResource(lp.cellBackgroundId); // if (child instanceof TextClippedImageView) { // if (!((TextClippedImageView)child).hasTextMask()) { // // Child mask is not set - propagate our default value // String mask = getMaskFor(lp); // ((TextClippedImageView) child).setTextMaskPath(mask); // } // bindImageToChild((ImageView) child, lp); // } else { // super.onBindChild(child, lp, originator); // } // } // // /** // * Set a new string to be used as base mask by {@link #getMaskFor(CutoutViewLayoutParams)}. // * // * @param textMask a string, with at most one {@code %d} where the position should go. // */ // public void setTextMask(@NonNull String textMask) { // this.textMask = textMask; // } // // /** // * The returned string will be used as a sort of clipping path for child views, // * provided that the children are instances of {@link TextClippedImageView}. // * // * @param lp the layout params of the associated view // * @return a string used for masking. return an empty string and // * the child view will draw absolutely nothing // * @see TextClippedImageView#setTextMaskPath(String) // */ // @NonNull // public String getMaskFor(@NonNull CutoutViewLayoutParams lp) { // return String.format(Locale.getDefault(), textMask, lp.position); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/ClippedImageCellGenerator.java // public class ClippedImageCellGenerator extends ImageCellGenerator { // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new ClippedImageView(parent.getContext()); // } // }
import java.util.List; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.fuzz.emptyhusk.BoldTextCellGenerator; import com.fuzz.emptyhusk.R; import com.fuzz.indicator.ImageCellGenerator; import com.fuzz.indicator.CutoutCellGenerator; import com.fuzz.indicator.clip.SequentialCellGenerator; import com.fuzz.indicator.clip.ClippedImageCellGenerator; import java.util.ArrayList;
/* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.emptyhusk.choosegenerator; /** * @author Philip Cohn-Cort (Fuzz) */ public class GeneratorChoiceAdapter extends RecyclerView.Adapter { @NonNull private List<GeneratorChoice> choices = new ArrayList<>(); @NonNull private Class<? extends CutoutCellGenerator> chosen = ImageCellGenerator.class; public GeneratorChoiceAdapter() { choices.add(new GeneratorChoice(ImageCellGenerator.class, "Creates simple ImageViews. These are offset with X or Y translations. A classic choice with static background and dynamic content.")); choices.add(new GeneratorChoice(ClippedImageCellGenerator.class, "Creates ClippedImageViews. These are offset with X or Y translations. Stylish, yet ever so slightly heavier memory-wise than ImageCellGenerator."));
// Path: mobile/src/main/java/com/fuzz/emptyhusk/BoldTextCellGenerator.java // public class BoldTextCellGenerator extends TextCellGenerator { // @NonNull // @Override // protected Spannable getTextFor(@NonNull Context context, int position) { // String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages); // // SpannableString ssb = new SpannableString(introStrings[position]); // MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD); // // // Order matters when setting spans. The base color must be in place first // // ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorSecondary)); // ssb.setSpan(colorSpan, 0, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // // // Only then should custom MigratorySpans be set. // // MigratoryRange<Integer> coverage = span.getCoverage(ssb); // int start = coverage.getLower(); // int end = coverage.getUpper(); // ssb.setSpan(span, start, end, span.preferredFlags(0)); // // MigratoryForegroundColorSpan boldColorSpan = new MigratoryForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent)); // ssb.setSpan(boldColorSpan, start, end, boldColorSpan.preferredFlags(0)); // // return ssb; // } // // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/SequentialCellGenerator.java // public class SequentialCellGenerator extends ImageCellGenerator { // // @NonNull // private String textMask = "~|%d|~"; // // public SequentialCellGenerator() { // } // // public SequentialCellGenerator(@NonNull Context context, @NonNull AttributeSet attrs, int defAttr) { // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CutoutViewIndicator, defAttr, 0); // String textMask = a.getString(R.styleable.CutoutViewIndicator_rcv_generator_text_mask); // if (textMask != null) { // setTextMask(textMask); // } // a.recycle(); // } // // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new TextClippedImageView(parent.getContext()); // } // // @Override // public void onBindChild(@NonNull View child, @NonNull CutoutViewLayoutParams lp, @Nullable View originator) { // child.setBackgroundResource(lp.cellBackgroundId); // if (child instanceof TextClippedImageView) { // if (!((TextClippedImageView)child).hasTextMask()) { // // Child mask is not set - propagate our default value // String mask = getMaskFor(lp); // ((TextClippedImageView) child).setTextMaskPath(mask); // } // bindImageToChild((ImageView) child, lp); // } else { // super.onBindChild(child, lp, originator); // } // } // // /** // * Set a new string to be used as base mask by {@link #getMaskFor(CutoutViewLayoutParams)}. // * // * @param textMask a string, with at most one {@code %d} where the position should go. // */ // public void setTextMask(@NonNull String textMask) { // this.textMask = textMask; // } // // /** // * The returned string will be used as a sort of clipping path for child views, // * provided that the children are instances of {@link TextClippedImageView}. // * // * @param lp the layout params of the associated view // * @return a string used for masking. return an empty string and // * the child view will draw absolutely nothing // * @see TextClippedImageView#setTextMaskPath(String) // */ // @NonNull // public String getMaskFor(@NonNull CutoutViewLayoutParams lp) { // return String.format(Locale.getDefault(), textMask, lp.position); // } // } // // Path: indicator/src/main/java/com/fuzz/indicator/clip/ClippedImageCellGenerator.java // public class ClippedImageCellGenerator extends ImageCellGenerator { // @NonNull // @Override // protected ImageView createChildFor(@NonNull ViewGroup parent, int position) { // return new ClippedImageView(parent.getContext()); // } // } // Path: mobile/src/main/java/com/fuzz/emptyhusk/choosegenerator/GeneratorChoiceAdapter.java import java.util.List; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.fuzz.emptyhusk.BoldTextCellGenerator; import com.fuzz.emptyhusk.R; import com.fuzz.indicator.ImageCellGenerator; import com.fuzz.indicator.CutoutCellGenerator; import com.fuzz.indicator.clip.SequentialCellGenerator; import com.fuzz.indicator.clip.ClippedImageCellGenerator; import java.util.ArrayList; /* * Copyright 2016 Philip Cohn-Cort * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fuzz.emptyhusk.choosegenerator; /** * @author Philip Cohn-Cort (Fuzz) */ public class GeneratorChoiceAdapter extends RecyclerView.Adapter { @NonNull private List<GeneratorChoice> choices = new ArrayList<>(); @NonNull private Class<? extends CutoutCellGenerator> chosen = ImageCellGenerator.class; public GeneratorChoiceAdapter() { choices.add(new GeneratorChoice(ImageCellGenerator.class, "Creates simple ImageViews. These are offset with X or Y translations. A classic choice with static background and dynamic content.")); choices.add(new GeneratorChoice(ClippedImageCellGenerator.class, "Creates ClippedImageViews. These are offset with X or Y translations. Stylish, yet ever so slightly heavier memory-wise than ImageCellGenerator."));
choices.add(new GeneratorChoice(BoldTextCellGenerator.class, "Creates TextViews with bold text. The bold sections are offset in a dynamic manner within the TextViews' text. Rather new and difficult to master."));
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/ComputationStageBuilder.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // }
import com.github.fhuss.kafka.streams.cep.core.Event;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.nfa; /** * Class to build a new {@link ComputationStage} instance. * * @param <K> the record key type * @param <V> the record value type. */ public class ComputationStageBuilder<K, V> { private Stage<K, V> stage; private DeweyVersion version; private long sequence;
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/ComputationStageBuilder.java import com.github.fhuss.kafka.streams.cep.core.Event; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.nfa; /** * Class to build a new {@link ComputationStage} instance. * * @param <K> the record key type * @param <V> the record value type. */ public class ComputationStageBuilder<K, V> { private Stage<K, V> stage; private DeweyVersion version; private long sequence;
private Event<K, V> event = null;
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/Stages.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/pattern/StateAggregator.java // public class StateAggregator<K, V, T> { // // private final String name; // private final Aggregator<K, V, T> aggregate; // // /** // * Creates a new {@link StateAggregator} instance. // * @param name the name of the state. // * @param aggregate the aggregate function. // */ // StateAggregator(final String name, final Aggregator<K, V, T> aggregate) { // this.name = name; // this.aggregate = aggregate; // } // // public String getName() { // return name; // } // // public Aggregator<K, V, T> getAggregate() { // return aggregate; // } // }
import com.github.fhuss.kafka.streams.cep.core.pattern.StateAggregator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.nfa; /** * A complex pattern sequence is made of multiple {@link Stage}. * * @param <K> the record key type. * @param <V> the record value type. */ public class Stages<K, V> implements Iterable<Stage<K, V>> { private final List<Stage<K, V>> stages; /** * Creates a new {@link Stages} instance. * * @param stages the list of stages. */ public Stages(final List<Stage<K, V>> stages) { this.stages = stages; } public List<Stage<K, V>> getAllStages() { return stages; } public Stage<K, V> getBeginingStage() { return stages.stream().filter(Stage::isBeginState).findFirst().get(); } public ComputationStage<K, V> initialComputationStage() { ComputationStage<K, V> computation = new ComputationStageBuilder<K, V>() .setStage(getBeginingStage()) .setVersion(new DeweyVersion(1)) .setSequence(1L) .build(); return computation; } public Set<String> getDefinedStates() { return stages.stream() .flatMap(s -> s.getAggregates().stream())
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/pattern/StateAggregator.java // public class StateAggregator<K, V, T> { // // private final String name; // private final Aggregator<K, V, T> aggregate; // // /** // * Creates a new {@link StateAggregator} instance. // * @param name the name of the state. // * @param aggregate the aggregate function. // */ // StateAggregator(final String name, final Aggregator<K, V, T> aggregate) { // this.name = name; // this.aggregate = aggregate; // } // // public String getName() { // return name; // } // // public Aggregator<K, V, T> getAggregate() { // return aggregate; // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/Stages.java import com.github.fhuss.kafka.streams.cep.core.pattern.StateAggregator; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.nfa; /** * A complex pattern sequence is made of multiple {@link Stage}. * * @param <K> the record key type. * @param <V> the record value type. */ public class Stages<K, V> implements Iterable<Stage<K, V>> { private final List<Stage<K, V>> stages; /** * Creates a new {@link Stages} instance. * * @param stages the list of stages. */ public Stages(final List<Stage<K, V>> stages) { this.stages = stages; } public List<Stage<K, V>> getAllStages() { return stages; } public Stage<K, V> getBeginingStage() { return stages.stream().filter(Stage::isBeginState).findFirst().get(); } public ComputationStage<K, V> initialComputationStage() { ComputationStage<K, V> computation = new ComputationStageBuilder<K, V>() .setStage(getBeginingStage()) .setVersion(new DeweyVersion(1)) .setSequence(1L) .build(); return computation; } public Set<String> getDefinedStates() { return stages.stream() .flatMap(s -> s.getAggregates().stream())
.map(StateAggregator::getName)
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/pattern/SimpleMatcher.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // }
import com.github.fhuss.kafka.streams.cep.core.Event;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.pattern; /** * A matcher defines the condition under which an event should be selected to be added to the pattern sequence. * * @param <K> the record key type. * @param <V> the record value type. */ @FunctionalInterface public interface SimpleMatcher<K, V> extends Matcher<K, V> { /** * {@inheritDoc} */ @Override default boolean accept(final MatcherContext<K, V> context) { return matches(context.getCurrentEvent()); } /** * The function that evaluates an input record stream. * * @param event the current event in the stream. * @return <code>true</code> if the event should be selected. */
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/pattern/SimpleMatcher.java import com.github.fhuss.kafka.streams.cep.core.Event; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.pattern; /** * A matcher defines the condition under which an event should be selected to be added to the pattern sequence. * * @param <K> the record key type. * @param <V> the record value type. */ @FunctionalInterface public interface SimpleMatcher<K, V> extends Matcher<K, V> { /** * {@inheritDoc} */ @Override default boolean accept(final MatcherContext<K, V> context) { return matches(context.getCurrentEvent()); } /** * The function that evaluates an input record stream. * * @param event the current event in the stream. * @return <code>true</code> if the event should be selected. */
boolean matches(final Event<K, V> event);
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/ComputationStage.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // }
import com.github.fhuss.kafka.streams.cep.core.Event; import java.util.List;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.nfa; /** * The implementation is based on the paper "Efficient Pattern Matching over Event Streams". * @see <a href="https://people.cs.umass.edu/~yanlei/publications/sase-sigmod08.pdf"> * https://people.cs.umass.edu/~yanlei/publications/sase-sigmod08.pdf * </a> * * @param <K> the type of keys * @param <V> the type of values */ public class ComputationStage<K, V> { /** * The stage. */ private final Stage<K , V> stage; /** * The pointer to the most recent event into the share buffer. */
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/ComputationStage.java import com.github.fhuss.kafka.streams.cep.core.Event; import java.util.List; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.nfa; /** * The implementation is based on the paper "Efficient Pattern Matching over Event Streams". * @see <a href="https://people.cs.umass.edu/~yanlei/publications/sase-sigmod08.pdf"> * https://people.cs.umass.edu/~yanlei/publications/sase-sigmod08.pdf * </a> * * @param <K> the type of keys * @param <V> the type of values */ public class ComputationStage<K, V> { /** * The stage. */ private final Stage<K , V> stage; /** * The pointer to the most recent event into the share buffer. */
private final Event<K, V> lastEvent;
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/pattern/Matcher.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // }
import com.github.fhuss.kafka.streams.cep.core.Event; import java.util.Objects;
class OrPredicate<K, V> implements Matcher<K, V> { private Matcher<K, V> left; private Matcher<K, V> right; OrPredicate(final Matcher<K, V> left, final Matcher<K, V> right) { this.left = left; this.right = right; } /** * {@inheritDoc} */ @Override public boolean accept(final MatcherContext<K, V> context) { return left.accept(context) || right.accept(context); } } class TopicPredicate<K, V> implements SimpleMatcher<K, V> { private final String topic; TopicPredicate(final String topic) { Objects.requireNonNull(topic, "topic can't be null"); this.topic = topic; } /** * {@inheritDoc} */ @Override
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/Event.java // public class Event<K, V> implements Comparable<Event<K, V>> { // // private final K key; // // private final V value; // // private final long timestamp; // // private final String topic; // // private final int partition; // // private long offset; // // /** // * Creates a new {@link Event} instance. // * // * @param key the record key // * @param value the record value // * @param timestamp the record timestamp // * @param topic the record topic // * @param partition the record partition // * @param offset the record offset // */ // public Event(final K key, // final V value, // final long timestamp, // final String topic, // final int partition, // final long offset) { // this.key = key; // this.value = value; // this.timestamp = timestamp; // this.topic = topic; // this.partition = partition; // this.offset = offset; // } // // public K key() { // return this.key; // } // // public V value() { // return this.value; // } // // public long timestamp() { // return this.timestamp; // } // // public String topic() { // return this.topic; // } // // public int partition() { // return this.partition; // } // // public long offset() { // return this.offset; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Event<?, ?> event = (Event<?, ?>) o; // return partition == event.partition && // offset == event.offset && // Objects.equals(topic, event.topic); // } // // @Override // public int hashCode() { // return Objects.hash(topic, partition, offset); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder("Event{"); // sb.append("key=").append(key); // sb.append(", value=").append(value); // sb.append(", timestamp=").append(timestamp); // sb.append(", topic='").append(topic).append('\''); // sb.append(", partition=").append(partition); // sb.append(", offset=").append(offset); // sb.append('}'); // return sb.toString(); // } // // @Override // public int compareTo(Event<K, V> that) { // if (!this.topic.equals(that.topic) || this.partition != that.partition) // return Long.compare(this.timestamp, that.timestamp); // return Long.compare(this.offset, that.offset); // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/pattern/Matcher.java import com.github.fhuss.kafka.streams.cep.core.Event; import java.util.Objects; class OrPredicate<K, V> implements Matcher<K, V> { private Matcher<K, V> left; private Matcher<K, V> right; OrPredicate(final Matcher<K, V> left, final Matcher<K, V> right) { this.left = left; this.right = right; } /** * {@inheritDoc} */ @Override public boolean accept(final MatcherContext<K, V> context) { return left.accept(context) || right.accept(context); } } class TopicPredicate<K, V> implements SimpleMatcher<K, V> { private final String topic; TopicPredicate(final String topic) { Objects.requireNonNull(topic, "topic can't be null"); this.topic = topic; } /** * {@inheritDoc} */ @Override
public boolean matches(final Event<K, V> event) {
fhussonnois/kafkastreams-cep
streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/internal/builder/AggregatesStoreBuilder.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/AggregatesStore.java // public interface AggregatesStore<K> { // // <T> T find(final Aggregated<K> aggregated); // // <T> void put(final Aggregated<K> aggregated, final T aggregate); // // /** // * Duplicates the underlying state for the specified sequence. // */ // default void branch(final Aggregated<K> aggregated, final long sequence) { // Object o = find(aggregated); // if (o != null) { // put(new Aggregated<>(aggregated.getKey(), aggregated.getAggregate().setSequence(sequence)), o); // } // } // } // // Path: streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/AggregatesStateStore.java // public interface AggregatesStateStore<K> extends AggregatesStore<K>, StateStore { // } // // Path: streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/internal/AggregatesStoreImpl.java // public class AggregatesStoreImpl<K> // extends WrappedStateStore<KeyValueStore<Bytes, byte[]>, K, Object> // implements AggregatesStateStore<K> { // // private StateSerdes<Aggregated<K>, Object> serdes; // // private KeyValueStore<Bytes, byte[]> bytesStore; // // /** // * Creates a new {@link AggregatesStoreImpl} instance. // * // * @param bytesStore the {@link KeyValueStore} bytes store. // */ // public AggregatesStoreImpl(final KeyValueStore<Bytes, byte[]> bytesStore) { // super(bytesStore); // this.bytesStore = bytesStore; // } // // /** // * {@inheritDoc} // */ // @Override // public void init(final ProcessorContext context, final StateStore root) { // super.init(context, root); // // final String storeName = bytesStore.name(); // String topic = ProcessorStateManager.storeChangelogTopic(context.applicationId(), storeName); // serdes = new StateSerdes<>(topic, new AggregateKeySerde<>(), new KryoSerDe<>()); // } // // /** // * {@inheritDoc} // */ // @SuppressWarnings("unchecked") // @Override // public <T> T find(final Aggregated<K> aggregated) { // byte[] bytes = bytesStore.get(Bytes.wrap(serdes.rawKey(aggregated))); // return (T) serdes.valueFrom(bytes); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> void put(final Aggregated<K> aggregated, T aggregate) { // bytesStore.put(Bytes.wrap(serdes.rawKey(aggregated)), serdes.rawValue(aggregate)); // } // }
import com.github.fhuss.kafka.streams.cep.core.state.AggregatesStore; import com.github.fhuss.kafka.streams.cep.state.AggregatesStateStore; import com.github.fhuss.kafka.streams.cep.state.internal.AggregatesStoreImpl; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.StoreBuilder; import org.apache.kafka.streams.state.Stores;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.state.internal.builder; /** * Default class to build {@link AggregatesStore} instance. * * @param <K> the type of keys * @param <V> the type of values */ public class AggregatesStoreBuilder<K, V> extends AbstractStoreBuilder<K, V, AggregatesStateStore<K>> { private final KeyValueBytesStoreSupplier storeSupplier; public AggregatesStoreBuilder(final KeyValueBytesStoreSupplier storeSupplier) { super(storeSupplier.name(), null, null); this.storeSupplier = storeSupplier; } /** * {@inheritDoc} */ @Override public AggregatesStateStore<K> build() { final StoreBuilder<KeyValueStore<Bytes, byte[]>> builder = Stores.keyValueStoreBuilder( storeSupplier, Serdes.Bytes(), Serdes.ByteArray()); if (enableLogging) { builder.withLoggingEnabled(logConfig()); } else { builder.withLoggingDisabled(); } if (enableCaching) { builder.withCachingEnabled(); }
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/AggregatesStore.java // public interface AggregatesStore<K> { // // <T> T find(final Aggregated<K> aggregated); // // <T> void put(final Aggregated<K> aggregated, final T aggregate); // // /** // * Duplicates the underlying state for the specified sequence. // */ // default void branch(final Aggregated<K> aggregated, final long sequence) { // Object o = find(aggregated); // if (o != null) { // put(new Aggregated<>(aggregated.getKey(), aggregated.getAggregate().setSequence(sequence)), o); // } // } // } // // Path: streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/AggregatesStateStore.java // public interface AggregatesStateStore<K> extends AggregatesStore<K>, StateStore { // } // // Path: streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/internal/AggregatesStoreImpl.java // public class AggregatesStoreImpl<K> // extends WrappedStateStore<KeyValueStore<Bytes, byte[]>, K, Object> // implements AggregatesStateStore<K> { // // private StateSerdes<Aggregated<K>, Object> serdes; // // private KeyValueStore<Bytes, byte[]> bytesStore; // // /** // * Creates a new {@link AggregatesStoreImpl} instance. // * // * @param bytesStore the {@link KeyValueStore} bytes store. // */ // public AggregatesStoreImpl(final KeyValueStore<Bytes, byte[]> bytesStore) { // super(bytesStore); // this.bytesStore = bytesStore; // } // // /** // * {@inheritDoc} // */ // @Override // public void init(final ProcessorContext context, final StateStore root) { // super.init(context, root); // // final String storeName = bytesStore.name(); // String topic = ProcessorStateManager.storeChangelogTopic(context.applicationId(), storeName); // serdes = new StateSerdes<>(topic, new AggregateKeySerde<>(), new KryoSerDe<>()); // } // // /** // * {@inheritDoc} // */ // @SuppressWarnings("unchecked") // @Override // public <T> T find(final Aggregated<K> aggregated) { // byte[] bytes = bytesStore.get(Bytes.wrap(serdes.rawKey(aggregated))); // return (T) serdes.valueFrom(bytes); // } // // /** // * {@inheritDoc} // */ // @Override // public <T> void put(final Aggregated<K> aggregated, T aggregate) { // bytesStore.put(Bytes.wrap(serdes.rawKey(aggregated)), serdes.rawValue(aggregate)); // } // } // Path: streams/src/main/java/com/github/fhuss/kafka/streams/cep/state/internal/builder/AggregatesStoreBuilder.java import com.github.fhuss.kafka.streams.cep.core.state.AggregatesStore; import com.github.fhuss.kafka.streams.cep.state.AggregatesStateStore; import com.github.fhuss.kafka.streams.cep.state.internal.AggregatesStoreImpl; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.utils.Bytes; import org.apache.kafka.streams.state.KeyValueBytesStoreSupplier; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.StoreBuilder; import org.apache.kafka.streams.state.Stores; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.state.internal.builder; /** * Default class to build {@link AggregatesStore} instance. * * @param <K> the type of keys * @param <V> the type of values */ public class AggregatesStoreBuilder<K, V> extends AbstractStoreBuilder<K, V, AggregatesStateStore<K>> { private final KeyValueBytesStoreSupplier storeSupplier; public AggregatesStoreBuilder(final KeyValueBytesStoreSupplier storeSupplier) { super(storeSupplier.name(), null, null); this.storeSupplier = storeSupplier; } /** * {@inheritDoc} */ @Override public AggregatesStateStore<K> build() { final StoreBuilder<KeyValueStore<Bytes, byte[]>> builder = Stores.keyValueStoreBuilder( storeSupplier, Serdes.Bytes(), Serdes.ByteArray()); if (enableLogging) { builder.withLoggingEnabled(logConfig()); } else { builder.withLoggingDisabled(); } if (enableCaching) { builder.withCachingEnabled(); }
return new AggregatesStoreImpl<>(builder.build());
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/States.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregate.java // public class Aggregate { // // private String name; // private Long sequence; // // /** // * Creates a new {@link Aggregate} instance. // * @param name the aggregate name. // * @param sequence the sequence id. // */ // public Aggregate(final String name, final long sequence) { // this.name = name; // this.sequence = sequence; // } // // public String getName() { // return name; // } // // public Long getSequence() { // return sequence; // } // // /** // * Sets the sequence identifier of this aggregate. // * // * @param sequence the new identifier. // * @return a new {@link Aggregate} instance. // */ // public Aggregate setSequence(final long sequence) { // return new Aggregate(name, sequence); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregate aggregate = (Aggregate) o; // return Objects.equals(name, aggregate.name) && // Objects.equals(sequence, aggregate.sequence); // } // // @Override // public int hashCode() { // return Objects.hash(name, sequence); // } // // @Override // public String toString() { // return "Aggregate{" + // "name='" + name + '\'' + // ", sequence=" + sequence + // '}'; // } // } // // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregated.java // public class Aggregated<K> { // // private final K key; // // private final Aggregate aggregate; // // /** // * Creates a new {@link Aggregated} instance. // * @param key the record key // * @param aggregate the instance of {@link Aggregate}. // */ // public Aggregated(final K key, final Aggregate aggregate) { // this.key = key; // this.aggregate = aggregate; // } // // public K getKey() { // return key; // } // // public Aggregate getAggregate() { // return aggregate; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregated<?> that = (Aggregated<?>) o; // return Objects.equals(key, that.key) && // Objects.equals(aggregate, that.aggregate); // } // // @Override // public int hashCode() { // // return Objects.hash(key, aggregate); // } // // @Override // public String toString() { // return "Aggregated{" + // "key=" + key + // ", aggregate=" + aggregate + // '}'; // } // }
import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregate; import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregated;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.state; /** * Simple class to wrap a {@link AggregatesStore}. * * @param <K> the record key type. */ public class States<K> { private final AggregatesStore<K> store; private final long sequence; private final K key; /** * Creates a new {@link States} instance. * * @param states the aggregates store. * @param key the record key used to store aggregates. * @param sequence The sequence number (aka run) used to store aggregates. */ public States(final AggregatesStore<K> states, K key, long sequence) { this.store = states; this.key = key; this.sequence = sequence; } /** * Retrieve the value state for the specified key. * * @param state the state name. * @param <T> the of default value. * @return <code>null</code> if no state exists for the given key. */ public <T> T get(final String state) { T v = getOrNull(state); if (v == null) throw new UnknownAggregateException(state); return v; } /** * Retrieve the value state for the specified key. * * @param key the object key. * @param def the default value. * @param <T> the of default value. * @return {@literal def} if no state exists for the given key. */ public <T> T getOrElse(String key, T def) { T val = getOrNull(key); return val != null ? val : def; } private <T> T getOrNull(String state) {
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregate.java // public class Aggregate { // // private String name; // private Long sequence; // // /** // * Creates a new {@link Aggregate} instance. // * @param name the aggregate name. // * @param sequence the sequence id. // */ // public Aggregate(final String name, final long sequence) { // this.name = name; // this.sequence = sequence; // } // // public String getName() { // return name; // } // // public Long getSequence() { // return sequence; // } // // /** // * Sets the sequence identifier of this aggregate. // * // * @param sequence the new identifier. // * @return a new {@link Aggregate} instance. // */ // public Aggregate setSequence(final long sequence) { // return new Aggregate(name, sequence); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregate aggregate = (Aggregate) o; // return Objects.equals(name, aggregate.name) && // Objects.equals(sequence, aggregate.sequence); // } // // @Override // public int hashCode() { // return Objects.hash(name, sequence); // } // // @Override // public String toString() { // return "Aggregate{" + // "name='" + name + '\'' + // ", sequence=" + sequence + // '}'; // } // } // // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregated.java // public class Aggregated<K> { // // private final K key; // // private final Aggregate aggregate; // // /** // * Creates a new {@link Aggregated} instance. // * @param key the record key // * @param aggregate the instance of {@link Aggregate}. // */ // public Aggregated(final K key, final Aggregate aggregate) { // this.key = key; // this.aggregate = aggregate; // } // // public K getKey() { // return key; // } // // public Aggregate getAggregate() { // return aggregate; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregated<?> that = (Aggregated<?>) o; // return Objects.equals(key, that.key) && // Objects.equals(aggregate, that.aggregate); // } // // @Override // public int hashCode() { // // return Objects.hash(key, aggregate); // } // // @Override // public String toString() { // return "Aggregated{" + // "key=" + key + // ", aggregate=" + aggregate + // '}'; // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/States.java import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregate; import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregated; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.state; /** * Simple class to wrap a {@link AggregatesStore}. * * @param <K> the record key type. */ public class States<K> { private final AggregatesStore<K> store; private final long sequence; private final K key; /** * Creates a new {@link States} instance. * * @param states the aggregates store. * @param key the record key used to store aggregates. * @param sequence The sequence number (aka run) used to store aggregates. */ public States(final AggregatesStore<K> states, K key, long sequence) { this.store = states; this.key = key; this.sequence = sequence; } /** * Retrieve the value state for the specified key. * * @param state the state name. * @param <T> the of default value. * @return <code>null</code> if no state exists for the given key. */ public <T> T get(final String state) { T v = getOrNull(state); if (v == null) throw new UnknownAggregateException(state); return v; } /** * Retrieve the value state for the specified key. * * @param key the object key. * @param def the default value. * @param <T> the of default value. * @return {@literal def} if no state exists for the given key. */ public <T> T getOrElse(String key, T def) { T val = getOrNull(key); return val != null ? val : def; } private <T> T getOrNull(String state) {
Aggregated<K> aggregated = new Aggregated<>(key, new Aggregate(state, sequence));
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/States.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregate.java // public class Aggregate { // // private String name; // private Long sequence; // // /** // * Creates a new {@link Aggregate} instance. // * @param name the aggregate name. // * @param sequence the sequence id. // */ // public Aggregate(final String name, final long sequence) { // this.name = name; // this.sequence = sequence; // } // // public String getName() { // return name; // } // // public Long getSequence() { // return sequence; // } // // /** // * Sets the sequence identifier of this aggregate. // * // * @param sequence the new identifier. // * @return a new {@link Aggregate} instance. // */ // public Aggregate setSequence(final long sequence) { // return new Aggregate(name, sequence); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregate aggregate = (Aggregate) o; // return Objects.equals(name, aggregate.name) && // Objects.equals(sequence, aggregate.sequence); // } // // @Override // public int hashCode() { // return Objects.hash(name, sequence); // } // // @Override // public String toString() { // return "Aggregate{" + // "name='" + name + '\'' + // ", sequence=" + sequence + // '}'; // } // } // // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregated.java // public class Aggregated<K> { // // private final K key; // // private final Aggregate aggregate; // // /** // * Creates a new {@link Aggregated} instance. // * @param key the record key // * @param aggregate the instance of {@link Aggregate}. // */ // public Aggregated(final K key, final Aggregate aggregate) { // this.key = key; // this.aggregate = aggregate; // } // // public K getKey() { // return key; // } // // public Aggregate getAggregate() { // return aggregate; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregated<?> that = (Aggregated<?>) o; // return Objects.equals(key, that.key) && // Objects.equals(aggregate, that.aggregate); // } // // @Override // public int hashCode() { // // return Objects.hash(key, aggregate); // } // // @Override // public String toString() { // return "Aggregated{" + // "key=" + key + // ", aggregate=" + aggregate + // '}'; // } // }
import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregate; import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregated;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.state; /** * Simple class to wrap a {@link AggregatesStore}. * * @param <K> the record key type. */ public class States<K> { private final AggregatesStore<K> store; private final long sequence; private final K key; /** * Creates a new {@link States} instance. * * @param states the aggregates store. * @param key the record key used to store aggregates. * @param sequence The sequence number (aka run) used to store aggregates. */ public States(final AggregatesStore<K> states, K key, long sequence) { this.store = states; this.key = key; this.sequence = sequence; } /** * Retrieve the value state for the specified key. * * @param state the state name. * @param <T> the of default value. * @return <code>null</code> if no state exists for the given key. */ public <T> T get(final String state) { T v = getOrNull(state); if (v == null) throw new UnknownAggregateException(state); return v; } /** * Retrieve the value state for the specified key. * * @param key the object key. * @param def the default value. * @param <T> the of default value. * @return {@literal def} if no state exists for the given key. */ public <T> T getOrElse(String key, T def) { T val = getOrNull(key); return val != null ? val : def; } private <T> T getOrNull(String state) {
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregate.java // public class Aggregate { // // private String name; // private Long sequence; // // /** // * Creates a new {@link Aggregate} instance. // * @param name the aggregate name. // * @param sequence the sequence id. // */ // public Aggregate(final String name, final long sequence) { // this.name = name; // this.sequence = sequence; // } // // public String getName() { // return name; // } // // public Long getSequence() { // return sequence; // } // // /** // * Sets the sequence identifier of this aggregate. // * // * @param sequence the new identifier. // * @return a new {@link Aggregate} instance. // */ // public Aggregate setSequence(final long sequence) { // return new Aggregate(name, sequence); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregate aggregate = (Aggregate) o; // return Objects.equals(name, aggregate.name) && // Objects.equals(sequence, aggregate.sequence); // } // // @Override // public int hashCode() { // return Objects.hash(name, sequence); // } // // @Override // public String toString() { // return "Aggregate{" + // "name='" + name + '\'' + // ", sequence=" + sequence + // '}'; // } // } // // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/Aggregated.java // public class Aggregated<K> { // // private final K key; // // private final Aggregate aggregate; // // /** // * Creates a new {@link Aggregated} instance. // * @param key the record key // * @param aggregate the instance of {@link Aggregate}. // */ // public Aggregated(final K key, final Aggregate aggregate) { // this.key = key; // this.aggregate = aggregate; // } // // public K getKey() { // return key; // } // // public Aggregate getAggregate() { // return aggregate; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Aggregated<?> that = (Aggregated<?>) o; // return Objects.equals(key, that.key) && // Objects.equals(aggregate, that.aggregate); // } // // @Override // public int hashCode() { // // return Objects.hash(key, aggregate); // } // // @Override // public String toString() { // return "Aggregated{" + // "key=" + key + // ", aggregate=" + aggregate + // '}'; // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/States.java import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregate; import com.github.fhuss.kafka.streams.cep.core.state.internal.Aggregated; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.fhuss.kafka.streams.cep.core.state; /** * Simple class to wrap a {@link AggregatesStore}. * * @param <K> the record key type. */ public class States<K> { private final AggregatesStore<K> store; private final long sequence; private final K key; /** * Creates a new {@link States} instance. * * @param states the aggregates store. * @param key the record key used to store aggregates. * @param sequence The sequence number (aka run) used to store aggregates. */ public States(final AggregatesStore<K> states, K key, long sequence) { this.store = states; this.key = key; this.sequence = sequence; } /** * Retrieve the value state for the specified key. * * @param state the state name. * @param <T> the of default value. * @return <code>null</code> if no state exists for the given key. */ public <T> T get(final String state) { T v = getOrNull(state); if (v == null) throw new UnknownAggregateException(state); return v; } /** * Retrieve the value state for the specified key. * * @param key the object key. * @param def the default value. * @param <T> the of default value. * @return {@literal def} if no state exists for the given key. */ public <T> T getOrElse(String key, T def) { T val = getOrNull(key); return val != null ? val : def; } private <T> T getOrNull(String state) {
Aggregated<K> aggregated = new Aggregated<>(key, new Aggregate(state, sequence));
fhussonnois/kafkastreams-cep
core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/MatchedEvent.java
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/DeweyVersion.java // public class DeweyVersion { // // private static final String VERSION_RUN_SEP = "\\."; // // private int[] versions; // // public DeweyVersion() {} // // /** // * Creates a new {@link DeweyVersion} instance. // * // * @param run the first version number. // */ // public DeweyVersion(final int run) { // this(new int[]{run}); // } // // /** // * Creates a new {@link DeweyVersion} from the specified string. // * // * @param version A string dewey version number. // */ // public DeweyVersion(final String version) { // String[] integers = version.split(VERSION_RUN_SEP); // this.versions = new int[integers.length]; // for(int i = 0; i < integers.length; i++) // this.versions[i] = Integer.parseInt(integers[i]); // } // // private DeweyVersion(int[] versions) { // this.versions = versions; // } // // public DeweyVersion addRun() { // return addRun(1); // } // // public DeweyVersion addRun(final int offset) { // int[] newDeweyNumber = Arrays.copyOf(versions, versions.length); // newDeweyNumber[versions.length - offset]++; // // return new DeweyVersion(newDeweyNumber); // } // // public int length() { // return this.versions.length; // } // // public boolean isCompatible(DeweyVersion that) { // if (this.length() > that.length()) { // // prefix case // for (int i = 0; i < that.length(); i++) // if (this.versions[i] != that.versions[i]) // return false; // // return true; // } else if (this.length() == that.length()) { // // check init digits for equality // int lastIndex = length() - 1; // for (int i = 0; i < lastIndex; i++) // if ( this.versions[i] != that.versions[i]) // return false; // // // check that the last digit is greater or equal // return this.versions[lastIndex] >= that.versions[lastIndex]; // } else { // return false; // } // } // // public DeweyVersion addStage() { // return new DeweyVersion(Arrays.copyOf(this.versions, versions.length + 1)); // } // // @Override // public String toString() { // return Arrays.stream(versions) // .mapToObj(Integer::toString) // .collect(Collectors.joining(".")); // } // }
import com.github.fhuss.kafka.streams.cep.core.nfa.DeweyVersion; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong;
} public long incrementRefAndGet() { return this.refs.incrementAndGet(); } public long decrementRefAndGet() { return this.refs.get() == 0 ? 0 : this.refs.decrementAndGet(); } public long getTimestamp() { return timestamp; } public K getKey() { return key; } public V getValue() { return value; } void removePredecessor(Pointer pointer) { this.predecessors.remove(pointer); } public Collection<Pointer> getPredecessors() { return predecessors; }
// Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/nfa/DeweyVersion.java // public class DeweyVersion { // // private static final String VERSION_RUN_SEP = "\\."; // // private int[] versions; // // public DeweyVersion() {} // // /** // * Creates a new {@link DeweyVersion} instance. // * // * @param run the first version number. // */ // public DeweyVersion(final int run) { // this(new int[]{run}); // } // // /** // * Creates a new {@link DeweyVersion} from the specified string. // * // * @param version A string dewey version number. // */ // public DeweyVersion(final String version) { // String[] integers = version.split(VERSION_RUN_SEP); // this.versions = new int[integers.length]; // for(int i = 0; i < integers.length; i++) // this.versions[i] = Integer.parseInt(integers[i]); // } // // private DeweyVersion(int[] versions) { // this.versions = versions; // } // // public DeweyVersion addRun() { // return addRun(1); // } // // public DeweyVersion addRun(final int offset) { // int[] newDeweyNumber = Arrays.copyOf(versions, versions.length); // newDeweyNumber[versions.length - offset]++; // // return new DeweyVersion(newDeweyNumber); // } // // public int length() { // return this.versions.length; // } // // public boolean isCompatible(DeweyVersion that) { // if (this.length() > that.length()) { // // prefix case // for (int i = 0; i < that.length(); i++) // if (this.versions[i] != that.versions[i]) // return false; // // return true; // } else if (this.length() == that.length()) { // // check init digits for equality // int lastIndex = length() - 1; // for (int i = 0; i < lastIndex; i++) // if ( this.versions[i] != that.versions[i]) // return false; // // // check that the last digit is greater or equal // return this.versions[lastIndex] >= that.versions[lastIndex]; // } else { // return false; // } // } // // public DeweyVersion addStage() { // return new DeweyVersion(Arrays.copyOf(this.versions, versions.length + 1)); // } // // @Override // public String toString() { // return Arrays.stream(versions) // .mapToObj(Integer::toString) // .collect(Collectors.joining(".")); // } // } // Path: core/src/main/java/com/github/fhuss/kafka/streams/cep/core/state/internal/MatchedEvent.java import com.github.fhuss.kafka.streams.cep.core.nfa.DeweyVersion; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; } public long incrementRefAndGet() { return this.refs.incrementAndGet(); } public long decrementRefAndGet() { return this.refs.get() == 0 ? 0 : this.refs.decrementAndGet(); } public long getTimestamp() { return timestamp; } public K getKey() { return key; } public V getValue() { return value; } void removePredecessor(Pointer pointer) { this.predecessors.remove(pointer); } public Collection<Pointer> getPredecessors() { return predecessors; }
public Pointer getPointerByVersion(DeweyVersion version) {
52North/Supervisor
core/src/main/java/org/n52/supervisor/CheckerResolver.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import java.util.Set; import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor; /** * * @author Daniel * */ @Singleton public class CheckerResolver { private static Logger log = LoggerFactory.getLogger(CheckerResolver.class); @Inject
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: core/src/main/java/org/n52/supervisor/CheckerResolver.java import java.util.Set; import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor; /** * * @author Daniel * */ @Singleton public class CheckerResolver { private static Logger log = LoggerFactory.getLogger(CheckerResolver.class); @Inject
private Set<RunnerFactory> factories;
52North/Supervisor
core/src/main/java/org/n52/supervisor/CheckerResolver.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import java.util.Set; import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor; /** * * @author Daniel * */ @Singleton public class CheckerResolver { private static Logger log = LoggerFactory.getLogger(CheckerResolver.class); @Inject private Set<RunnerFactory> factories;
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: core/src/main/java/org/n52/supervisor/CheckerResolver.java import java.util.Set; import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor; /** * * @author Daniel * */ @Singleton public class CheckerResolver { private static Logger log = LoggerFactory.getLogger(CheckerResolver.class); @Inject private Set<RunnerFactory> factories;
public CheckRunner getRunner(final Check check) {
52North/Supervisor
core/src/main/java/org/n52/supervisor/CheckerResolver.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import java.util.Set; import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor; /** * * @author Daniel * */ @Singleton public class CheckerResolver { private static Logger log = LoggerFactory.getLogger(CheckerResolver.class); @Inject private Set<RunnerFactory> factories;
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: core/src/main/java/org/n52/supervisor/CheckerResolver.java import java.util.Set; import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor; /** * * @author Daniel * */ @Singleton public class CheckerResolver { private static Logger log = LoggerFactory.getLogger(CheckerResolver.class); @Inject private Set<RunnerFactory> factories;
public CheckRunner getRunner(final Check check) {
52North/Supervisor
json/src/main/java/org/n52/supervisor/checks/json/EnviroCarRunnerFactory.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor.checks.json; public class EnviroCarRunnerFactory implements RunnerFactory { @Override
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: json/src/main/java/org/n52/supervisor/checks/json/EnviroCarRunnerFactory.java import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.supervisor.checks.json; public class EnviroCarRunnerFactory implements RunnerFactory { @Override
public CheckRunner resolveRunner(Check check) {