answer
stringlengths
17
10.2M
package com.google.sps.servlets; import com.google.gson.Gson; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; // import com.google.api.services.admin.directory.Directory; // import com.google.api.services.admin.directory.DirectoryScopes; // import com.google.api.services.admin.directory.model.User; // import com.google.api.services.admin.directory.model.Users; import java.io.IOException; import java.util.List; import java.util.ArrayList; import java.io.FileReader; @WebServlet("/token") public class TokenServlet extends HttpServlet { private final Gson GSON_OBJECT = new Gson(); private final String CLIENT_SECRET_FILE = "client_secret.json"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { final String authCode = (String) request.getParameter("code"); GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE)); GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest( new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "https://oauth2.googleapis.com/token", clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode, "http://localhost:8080") .execute(); String accessToken = tokenResponse.getAccessToken(); System.out.println(accessToken); System.out.println("is the access token!"); } }
package com.instructure.canvasapi.model; import android.os.Parcel; import com.instructure.canvasapi.utilities.APIHelpers; import java.util.Date; public class Page extends CanvasModel<Page> { private static final long serialVersionUID = 1L; public static final String FRONT_PAGE_NAME = "front-page"; /* Example JSON response * * { // the unique locator for the page url: "my-page-title", // the title of the page title: "My Page Title", // the creation date for the page created_at: "2012-08-06T16:46:33-06:00", // the date the page was last updated updated_at: "2012-08-08T14:25:20-06:00", // whether this page is hidden from students // (note: students will never see this true; pages hidden from them will be omitted from results) hide_from_students: false, // the page content, in HTML // (present when requesting a single page; omitted when listing pages) body: "<p>Page Content</p>" } */ private String url; private long page_id; private String title; private String created_at; private String updated_at; private boolean hide_from_students; private String status; private String body; private LockInfo lock_info; private boolean front_page; // Getters and Setters public long getPageId() { return page_id; } public void setPageId(long pageId) { this.page_id = pageId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getCreate_at() { return APIHelpers.stringToDate(created_at); } public void setCreate_at(Date create_at) { this.created_at = APIHelpers.dateToString(create_at); } public Date getUpdated_at() { return APIHelpers.stringToDate(updated_at); } public void setUpdated_at(Date updated_at) { this.created_at = APIHelpers.dateToString(updated_at); } public boolean isHide_from_students() { return hide_from_students || (status != null && status.equalsIgnoreCase("unauthorized")); } public void setHide_from_students(boolean hide_from_students) { this.hide_from_students = hide_from_students; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } //During parsing, GSON will try. Which means sometimes we get 'empty' objects //They're non-null, but don't have any information. public LockInfo getLockInfo() { //Check for null or empty lock info. if(lock_info == null || lock_info.isEmpty()){ return null; } return lock_info; } public void setLockInfo(LockInfo lockInfo) { this.lock_info = lockInfo; } public boolean isFrontPage(){ return front_page; } // Required Overrides public Date getComparisonDate() { return getCreate_at(); } public String getComparisonString() { return title; } // Constructors public Page() {} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Page page = (Page) o; if (url != null ? !url.equals(page.url) : page.url != null) return false; return true; } @Override public long getId() { return getPageId(); } @Override public int hashCode() { return url != null ? url.hashCode() : 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.url); dest.writeString(this.title); dest.writeString(this.created_at); dest.writeString(this.updated_at); dest.writeByte(hide_from_students ? (byte) 1 : (byte) 0); dest.writeString(this.status); dest.writeString(this.body); dest.writeParcelable(this.lock_info, flags); dest.writeByte(front_page ? (byte) 1 : (byte) 0); } private Page(Parcel in) { this.url = in.readString(); this.title = in.readString(); this.created_at = in.readString(); this.updated_at = in.readString(); this.hide_from_students = in.readByte() != 0; this.status = in.readString(); this.body = in.readString(); this.lock_info = in.readParcelable(LockInfo.class.getClassLoader()); this.front_page = in.readByte() != 0; } public static Creator<Page> CREATOR = new Creator<Page>() { public Page createFromParcel(Parcel source) { return new Page(source); } public Page[] newArray(int size) { return new Page[size]; } }; }
package com.mpatric.mp3agic; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; public abstract class AbstractID3v2Tag implements ID3v2 { public static final String ID_IMAGE = "APIC"; public static final String ID_ENCODER = "TENC"; public static final String ID_URL = "WXXX"; public static final String ID_ARTIST_URL = "WOAR"; public static final String ID_COMMERCIAL_URL = "WCOM"; public static final String ID_COPYRIGHT_URL = "WCOP"; public static final String ID_AUDIOFILE_URL = "WOAF"; public static final String ID_AUDIOSOURCE_URL = "WOAS"; public static final String ID_RADIOSTATION_URL = "WORS"; public static final String ID_PAYMENT_URL = "WPAY"; public static final String ID_PUBLISHER_URL = "WPUB"; public static final String ID_COPYRIGHT = "TCOP"; public static final String ID_ORIGINAL_ARTIST = "TOPE"; public static final String ID_BPM = "TBPM"; public static final String ID_COMPOSER = "TCOM"; public static final String ID_PUBLISHER = "TPUB"; public static final String ID_COMMENT = "COMM"; public static final String ID_GENRE = "TCON"; public static final String ID_YEAR = "TYER"; public static final String ID_DATE = "TDAT"; public static final String ID_ALBUM = "TALB"; public static final String ID_TITLE = "TIT2"; public static final String ID_KEY = "TKEY"; public static final String ID_ARTIST = "TPE1"; public static final String ID_ALBUM_ARTIST = "TPE2"; public static final String ID_TRACK = "TRCK"; public static final String ID_PART_OF_SET = "TPOS"; public static final String ID_COMPILATION = "TCMP"; public static final String ID_CHAPTER_TOC = "CTOC"; public static final String ID_CHAPTER = "CHAP"; public static final String ID_GROUPING = "TIT1"; public static final String ID_IMAGE_OBSELETE = "PIC"; public static final String ID_ENCODER_OBSELETE = "TEN"; public static final String ID_URL_OBSELETE = "WXX"; public static final String ID_COPYRIGHT_OBSELETE = "TCR"; public static final String ID_ORIGINAL_ARTIST_OBSELETE = "TOA"; public static final String ID_BPM_OBSELETE = "TBP"; public static final String ID_COMPOSER_OBSELETE = "TCM"; public static final String ID_PUBLISHER_OBSELETE = "TBP"; public static final String ID_COMMENT_OBSELETE = "COM"; public static final String ID_GENRE_OBSELETE = "TCO"; public static final String ID_YEAR_OBSELETE = "TYE"; public static final String ID_DATE_OBSELETE = "TDA"; public static final String ID_ALBUM_OBSELETE = "TAL"; public static final String ID_TITLE_OBSELETE = "TT2"; public static final String ID_KEY_OBSELETE = "TKE"; public static final String ID_ARTIST_OBSELETE = "TP1"; public static final String ID_ALBUM_ARTIST_OBSELETE = "TP2"; public static final String ID_TRACK_OBSELETE = "TRK"; public static final String ID_PART_OF_SET_OBSELETE = "TPA"; public static final String ID_COMPILATION_OBSELETE = "TCP"; public static final String ID_GROUPING_OBSELETE = "TT1"; protected static final String TAG = "ID3"; protected static final String FOOTER_TAG = "3DI"; protected static final int HEADER_LENGTH = 10; protected static final int FOOTER_LENGTH = 10; protected static final int MAJOR_VERSION_OFFSET = 3; protected static final int MINOR_VERSION_OFFSET = 4; protected static final int FLAGS_OFFSET = 5; protected static final int DATA_LENGTH_OFFSET = 6; protected static final int FOOTER_BIT = 4; protected static final int EXPERIMENTAL_BIT = 5; protected static final int EXTENDED_HEADER_BIT = 6; protected static final int COMPRESSION_BIT = 6; protected static final int UNSYNCHRONISATION_BIT = 7; protected static final int PADDING_LENGTH = 256; private static final String ITUNES_COMMENT_DESCRIPTION = "iTunNORM"; protected boolean unsynchronisation = false; protected boolean extendedHeader = false; protected boolean experimental = false; protected boolean footer = false; protected boolean compression = false; protected boolean padding = false; protected String version = null; private int dataLength = 0; private int extendedHeaderLength; private byte[] extendedHeaderData; private boolean obseleteFormat = false; private final Map<String, ID3v2FrameSet> frameSets; public AbstractID3v2Tag() { frameSets = new TreeMap<String, ID3v2FrameSet>(); } public AbstractID3v2Tag(byte[] bytes) throws NoSuchTagException, UnsupportedTagException, InvalidDataException { this(bytes, false); } public AbstractID3v2Tag(byte[] bytes, boolean obseleteFormat) throws NoSuchTagException, UnsupportedTagException, InvalidDataException { frameSets = new TreeMap<String, ID3v2FrameSet>(); this.obseleteFormat = obseleteFormat; unpackTag(bytes); } private void unpackTag(byte[] bytes) throws NoSuchTagException, UnsupportedTagException, InvalidDataException { ID3v2TagFactory.sanityCheckTag(bytes); int offset = unpackHeader(bytes); try { if (extendedHeader) { offset = unpackExtendedHeader(bytes, offset); } int framesLength = dataLength; if (footer) framesLength -= 10; offset = unpackFrames(bytes, offset, framesLength); if (footer) { offset = unpackFooter(bytes, dataLength); } } catch (ArrayIndexOutOfBoundsException e) { throw new InvalidDataException("Premature end of tag", e); } } private int unpackHeader(byte[] bytes) throws UnsupportedTagException, InvalidDataException { int majorVersion = bytes[MAJOR_VERSION_OFFSET]; int minorVersion = bytes[MINOR_VERSION_OFFSET]; version = majorVersion + "." + minorVersion; if (majorVersion != 2 && majorVersion != 3 && majorVersion != 4) { throw new UnsupportedTagException("Unsupported version " + version); } unpackFlags(bytes); if ((bytes[FLAGS_OFFSET] & 0x0F) != 0) throw new UnsupportedTagException("Unrecognised bits in header"); dataLength = BufferTools.unpackSynchsafeInteger(bytes[DATA_LENGTH_OFFSET], bytes[DATA_LENGTH_OFFSET + 1], bytes[DATA_LENGTH_OFFSET + 2], bytes[DATA_LENGTH_OFFSET + 3]); if (dataLength < 1) throw new InvalidDataException("Zero size tag"); return HEADER_LENGTH; } protected abstract void unpackFlags(byte[] bytes); private int unpackExtendedHeader(byte[] bytes, int offset) { extendedHeaderLength = BufferTools.unpackSynchsafeInteger(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]) + 4; extendedHeaderData = BufferTools.copyBuffer(bytes, offset + 4, extendedHeaderLength); return extendedHeaderLength; } protected int unpackFrames(byte[] bytes, int offset, int framesLength) { int currentOffset = offset; while (currentOffset <= framesLength) { ID3v2Frame frame; try { frame = createFrame(bytes, currentOffset); addFrame(frame, false); currentOffset += frame.getLength(); } catch (InvalidDataException e) { break; } } return currentOffset; } protected void addFrame(ID3v2Frame frame, boolean replace) { ID3v2FrameSet frameSet = frameSets.get(frame.getId()); if (frameSet == null) { frameSet = new ID3v2FrameSet(frame.getId()); frameSet.addFrame(frame); frameSets.put(frame.getId(), frameSet); } else if (replace) { frameSet.clear(); frameSet.addFrame(frame); } else { frameSet.addFrame(frame); } } protected ID3v2Frame createFrame(byte[] bytes, int currentOffset) throws InvalidDataException { if (obseleteFormat) return new ID3v2ObseleteFrame(bytes, currentOffset); return new ID3v2Frame(bytes, currentOffset); } protected ID3v2Frame createFrame(String id, byte[] data) { if (obseleteFormat) return new ID3v2ObseleteFrame(id, data); else return new ID3v2Frame(id, data); } private int unpackFooter(byte[] bytes, int offset) throws InvalidDataException { if (! FOOTER_TAG.equals(BufferTools.byteBufferToStringIgnoringEncodingIssues(bytes, offset, FOOTER_TAG.length()))) { throw new InvalidDataException("Invalid footer"); } return FOOTER_LENGTH; } public byte[] toBytes() throws NotSupportedException { byte[] bytes = new byte[getLength()]; packTag(bytes); return bytes; } public void packTag(byte[] bytes) throws NotSupportedException { int offset = packHeader(bytes, 0); if (extendedHeader) { offset = packExtendedHeader(bytes, offset); } offset = packFrames(bytes, offset); if (footer) { offset = packFooter(bytes, dataLength); } } private int packHeader(byte[] bytes, int offset) { try { BufferTools.stringIntoByteBuffer(TAG, 0, TAG.length(), bytes, offset); } catch (UnsupportedEncodingException e) { } String s[] = version.split("\\."); if (s.length > 0) { byte majorVersion = Byte.parseByte(s[0]); bytes[offset + MAJOR_VERSION_OFFSET] = majorVersion; } if (s.length > 1) { byte minorVersion = Byte.parseByte(s[1]); bytes[offset + MINOR_VERSION_OFFSET] = minorVersion; } packFlags(bytes, offset); BufferTools.packSynchsafeInteger(getDataLength(), bytes, offset + DATA_LENGTH_OFFSET); return offset + HEADER_LENGTH; } protected abstract void packFlags(byte[] bytes, int i); private int packExtendedHeader(byte[] bytes, int offset) { BufferTools.packSynchsafeInteger(extendedHeaderLength, bytes, offset); BufferTools.copyIntoByteBuffer(extendedHeaderData, 0, extendedHeaderData.length, bytes, offset + 4); return offset + 4 + extendedHeaderData.length; } public int packFrames(byte[] bytes, int offset) throws NotSupportedException { int newOffset = packSpecifiedFrames(bytes, offset, null, "APIC"); newOffset = packSpecifiedFrames(bytes, newOffset, "APIC", null); return newOffset; } private int packSpecifiedFrames(byte[] bytes, int offset, String onlyId, String notId) throws NotSupportedException { Iterator<ID3v2FrameSet> setIterator = frameSets.values().iterator(); while (setIterator.hasNext()) { ID3v2FrameSet frameSet = setIterator.next(); if ((onlyId == null || onlyId.equals(frameSet.getId())) && (notId == null || !notId.equals(frameSet.getId()))) { Iterator<ID3v2Frame> frameIterator = frameSet.getFrames().iterator(); while (frameIterator.hasNext()) { ID3v2Frame frame = (ID3v2Frame) frameIterator.next(); if (frame.getDataLength() > 0) { byte[] frameData = frame.toBytes(); BufferTools.copyIntoByteBuffer(frameData, 0, frameData.length, bytes, offset); offset += frameData.length; } } } } return offset; } private int packFooter(byte[] bytes, int offset) { try { BufferTools.stringIntoByteBuffer(FOOTER_TAG, 0, FOOTER_TAG.length(), bytes, offset); } catch (UnsupportedEncodingException e) { } String s[] = version.split("\\."); if (s.length > 0) { byte majorVersion = Byte.parseByte(s[0]); bytes[offset + MAJOR_VERSION_OFFSET] = majorVersion; } if (s.length > 1) { byte minorVersion = Byte.parseByte(s[1]); bytes[offset + MINOR_VERSION_OFFSET] = minorVersion; } packFlags(bytes, offset); BufferTools.packSynchsafeInteger(getDataLength(), bytes, offset + DATA_LENGTH_OFFSET); return offset + FOOTER_LENGTH; } private int calculateDataLength() { int length = 0; if (extendedHeader) length += extendedHeaderLength; if (footer) length += FOOTER_LENGTH; else if (padding) length += PADDING_LENGTH; Iterator<ID3v2FrameSet> setIterator = frameSets.values().iterator(); while (setIterator.hasNext()) { ID3v2FrameSet frameSet = setIterator.next(); Iterator<ID3v2Frame> frameIterator = frameSet.getFrames().iterator(); while (frameIterator.hasNext()) { ID3v2Frame frame = (ID3v2Frame) frameIterator.next(); length += frame.getLength(); } } return length; } protected boolean useFrameUnsynchronisation() { return false; } public String getVersion() { return version; } protected void invalidateDataLength() { dataLength = 0; } public int getDataLength() { if (dataLength == 0) { dataLength = calculateDataLength(); } return dataLength; } public int getLength() { return getDataLength() + HEADER_LENGTH; } public Map<String, ID3v2FrameSet> getFrameSets() { return frameSets; } public boolean getPadding() { return padding; } public void setPadding(boolean padding) { if (this.padding != padding) { invalidateDataLength(); this.padding = padding; } } public boolean hasFooter() { return footer; } public void setFooter(boolean footer) { if (this.footer != footer) { invalidateDataLength(); this.footer = footer; } } public boolean hasUnsynchronisation() { return unsynchronisation; } public void setUnsynchronisation(boolean unsynchronisation) { if (this.unsynchronisation != unsynchronisation) { invalidateDataLength(); this.unsynchronisation = unsynchronisation; } } public boolean getObseleteFormat() { return obseleteFormat; } public String getTrack() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_TRACK_OBSELETE : ID_TRACK); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setTrack(String track) { if (track != null && track.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(track)); addFrame(createFrame(ID_TRACK, frameData.toBytes()), true); } } public String getPartOfSet() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_PART_OF_SET_OBSELETE : ID_PART_OF_SET); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setPartOfSet(String partOfSet) { if (partOfSet != null && partOfSet.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(partOfSet)); addFrame(createFrame(ID_PART_OF_SET, frameData.toBytes()), true); } } public boolean isCompilation() { // unofficial frame used by iTunes ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_COMPILATION_OBSELETE : ID_COMPILATION); if (frameData != null && frameData.getText() != null) return "1".equals(frameData.getText().toString()); return false; } public void setCompilation(boolean compilation) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(compilation ? "1" : "0")); addFrame(createFrame(ID_COMPILATION, frameData.toBytes()), true); } public String getGrouping() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_GROUPING_OBSELETE : ID_GROUPING); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setGrouping(String grouping) { if (grouping != null && grouping.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(grouping)); addFrame(createFrame(ID_GROUPING, frameData.toBytes()), true); } } public String getArtist() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_ARTIST_OBSELETE : ID_ARTIST); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setArtist(String artist) { if (artist != null && artist.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(artist)); addFrame(createFrame(ID_ARTIST, frameData.toBytes()), true); } } public String getAlbumArtist() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_ALBUM_ARTIST_OBSELETE : ID_ALBUM_ARTIST); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setAlbumArtist(String albumArtist) { if (albumArtist != null && albumArtist.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(albumArtist)); addFrame(createFrame(ID_ALBUM_ARTIST, frameData.toBytes()), true); } } public String getTitle() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_TITLE_OBSELETE : ID_TITLE); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setTitle(String title) { if (title != null && title.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(title)); addFrame(createFrame(ID_TITLE, frameData.toBytes()), true); } } public String getAlbum() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_ALBUM_OBSELETE : ID_ALBUM); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setAlbum(String album) { if (album != null && album.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(album)); addFrame(createFrame(ID_ALBUM, frameData.toBytes()), true); } } public String getYear() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_YEAR_OBSELETE : ID_YEAR); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setYear(String year) { if (year != null && year.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(year)); addFrame(createFrame(ID_YEAR, frameData.toBytes()), true); } } public String getDate() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_DATE_OBSELETE : ID_DATE); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setDate(String date) { if (date != null && date.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(date)); addFrame(createFrame(ID_DATE, frameData.toBytes()), true); } } private int getGenre(String text) { if (text != null && text.length() > 0) { try { return extractGenreNumber(text); } catch (NumberFormatException e) { // match genre description String description = extractGenreDescription(text); return ID3v1Genres.matchGenreDescription(description); } } return -1; } public int getGenre() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_GENRE_OBSELETE : ID_GENRE); if (frameData == null || frameData.getText() == null) { return -1; } return getGenre(frameData.getText().toString()); } public void setGenre(int genre) { if (genre >= 0) { invalidateDataLength(); String genreDescription = genre < ID3v1Genres.GENRES.length ? ID3v1Genres.GENRES[genre] : ""; String combinedGenre = "(" + Integer.toString(genre) + ")" + genreDescription; ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(combinedGenre)); addFrame(createFrame(ID_GENRE, frameData.toBytes()), true); } else { // TODO remove frame? } } public int getBPM() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_BPM_OBSELETE : ID_BPM); if (frameData == null || frameData.getText() == null) { return -1; } return Integer.parseInt(frameData.getText().toString()); } public void setBPM(int bpm) { if (bpm >= 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(Integer.toString(bpm))); addFrame(createFrame(ID_GENRE, frameData.toBytes()), true); } } public String getKey() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_KEY_OBSELETE : ID_KEY); if (frameData == null || frameData.getText() == null) { return null; } return frameData.getText().toString(); } public void setKey(String key) { if (key != null && key.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(key)); addFrame(createFrame(ID_KEY, frameData.toBytes()), true); } } public String getGenreDescription() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_GENRE_OBSELETE : ID_GENRE); if (frameData == null || frameData.getText() == null) { return null; } String text = frameData.getText().toString(); if (text != null) { int genreNum = getGenre(text); if (genreNum >= 0 && genreNum < ID3v1Genres.GENRES.length) { return ID3v1Genres.GENRES[genreNum]; } else { String description = extractGenreDescription(text); if (description != null && description.length() > 0) { return description; } } } return null; } public void setGenreDescription(String text) throws IllegalArgumentException { int genreNum = ID3v1Genres.matchGenreDescription(text); if (genreNum < 0) { throw new IllegalArgumentException("Unknown genre: " + text); } setGenre(genreNum); } protected int extractGenreNumber(String genreValue) throws NumberFormatException { String value = genreValue.trim(); if (value.length() > 0) { if (value.charAt(0) == '(') { int pos = value.indexOf(')'); if (pos > 0) { return Integer.parseInt(value.substring(1, pos)); } } } return Integer.parseInt(value); } protected String extractGenreDescription(String genreValue) throws NumberFormatException { String value = genreValue.trim(); if (value.length() > 0) { if (value.charAt(0) == '(') { int pos = value.indexOf(')'); if (pos > 0) { return value.substring(pos + 1); } } return value; } return null; } public String getComment() { ID3v2CommentFrameData frameData = extractCommentFrameData(obseleteFormat ? ID_COMMENT_OBSELETE : ID_COMMENT, false); if (frameData != null && frameData.getComment() != null) return frameData.getComment().toString(); return null; } public void setComment(String comment) { if (comment != null && comment.length() > 0) { invalidateDataLength(); ID3v2CommentFrameData frameData = new ID3v2CommentFrameData(useFrameUnsynchronisation(), "eng", null, new EncodedText(comment)); addFrame(createFrame(ID_COMMENT, frameData.toBytes()), true); } } public String getItunesComment() { ID3v2CommentFrameData frameData = extractCommentFrameData(obseleteFormat ? ID_COMMENT_OBSELETE : ID_COMMENT, true); if (frameData != null && frameData.getComment() != null) return frameData.getComment().toString(); return null; } public void setItunesComment(String itunesComment) { if (itunesComment != null && itunesComment.length() > 0) { invalidateDataLength(); ID3v2CommentFrameData frameData = new ID3v2CommentFrameData(useFrameUnsynchronisation(), ITUNES_COMMENT_DESCRIPTION, null, new EncodedText(itunesComment)); addFrame(createFrame(ID_COMMENT, frameData.toBytes()), true); } } public String getComposer() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_COMPOSER_OBSELETE : ID_COMPOSER); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setComposer(String composer) { if (composer != null && composer.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(composer)); addFrame(createFrame(ID_COMPOSER, frameData.toBytes()), true); } } public String getPublisher() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_PUBLISHER_OBSELETE : ID_PUBLISHER); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setPublisher(String publisher) { if (publisher != null && publisher.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(publisher)); addFrame(createFrame(ID_PUBLISHER, frameData.toBytes()), true); } } public String getOriginalArtist() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_ORIGINAL_ARTIST_OBSELETE : ID_ORIGINAL_ARTIST); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setOriginalArtist(String originalArtist) { if (originalArtist != null && originalArtist.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(originalArtist)); addFrame(createFrame(ID_ORIGINAL_ARTIST, frameData.toBytes()), true); } } public String getCopyright() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_COPYRIGHT_OBSELETE : ID_COPYRIGHT); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setCopyright(String copyright) { if (copyright != null && copyright.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(copyright)); addFrame(createFrame(ID_COPYRIGHT, frameData.toBytes()), true); } } public String getArtistUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_ARTIST_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setArtistUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_ARTIST_URL, frameData.toBytes()), true); } } public String getCommercialUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_COMMERCIAL_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setCommercialUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_COMMERCIAL_URL, frameData.toBytes()), true); } } public String getCopyrightUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_COPYRIGHT_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setCopyrightUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_COPYRIGHT_URL, frameData.toBytes()), true); } } public String getAudiofileUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_AUDIOFILE_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setAudiofileUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_AUDIOFILE_URL, frameData.toBytes()), true); } } public String getAudioSourceUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_AUDIOSOURCE_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setAudioSourceUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_AUDIOSOURCE_URL, frameData.toBytes()), true); } } public String getRadiostationUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_RADIOSTATION_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setRadiostationUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_RADIOSTATION_URL, frameData.toBytes()), true); } } public String getPaymentUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_PAYMENT_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setPaymentUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_PAYMENT_URL, frameData.toBytes()), true); } } public String getPublisherUrl() { ID3v2WWWFrameData frameData = extractWWWFrameData(ID_PUBLISHER_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setPublisherUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2WWWFrameData frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), url); addFrame(createFrame(ID_PUBLISHER_URL, frameData.toBytes()), true); } } public String getUrl() { ID3v2UrlFrameData frameData = extractUrlFrameData(obseleteFormat ? ID_URL_OBSELETE : ID_URL); if (frameData != null) return frameData.getUrl(); return null; } public void setUrl(String url) { if (url != null && url.length() > 0) { invalidateDataLength(); ID3v2UrlFrameData frameData = new ID3v2UrlFrameData(useFrameUnsynchronisation(), null, url); addFrame(createFrame(ID_URL, frameData.toBytes()), true); } } public ArrayList<ID3v2ChapterFrameData> getChapters() { if (obseleteFormat) { return null; } return extractChapterFrameData(ID_CHAPTER); } public void setChapters(ArrayList<ID3v2ChapterFrameData> chapters) { if(chapters != null) { invalidateDataLength(); boolean first = true; for(ID3v2ChapterFrameData chapter: chapters) { if(first) { first = false; addFrame(createFrame(ID_CHAPTER, chapter.toBytes()), true); } else { addFrame(createFrame(ID_CHAPTER, chapter.toBytes()), false); } } } } public ArrayList<ID3v2ChapterTOCFrameData> getChapterTOC() { if (obseleteFormat) { return null; } return extractChapterTOCFrameData(ID_CHAPTER_TOC); } public void setChapterTOC(ArrayList<ID3v2ChapterTOCFrameData> toc) { if(toc != null) { invalidateDataLength(); boolean first = true; for(ID3v2ChapterTOCFrameData ct: toc) { if(first) { first = false; addFrame(createFrame(ID_CHAPTER_TOC, ct.toBytes()), true); } else { addFrame(createFrame(ID_CHAPTER_TOC, ct.toBytes()), false); } } } } public String getEncoder() { ID3v2TextFrameData frameData = extractTextFrameData(obseleteFormat ? ID_ENCODER_OBSELETE: ID_ENCODER); if (frameData != null && frameData.getText() != null) return frameData.getText().toString(); return null; } public void setEncoder(String encoder) { if (encoder != null && encoder.length() > 0) { invalidateDataLength(); ID3v2TextFrameData frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), new EncodedText(encoder)); addFrame(createFrame(ID_ENCODER, frameData.toBytes()), true); } } public byte[] getAlbumImage() { ID3v2PictureFrameData frameData = createPictureFrameData(obseleteFormat ? ID_IMAGE_OBSELETE : ID_IMAGE); if (frameData != null) return frameData.getImageData(); return null; } public void setAlbumImage(byte[] albumImage, String mimeType) { if (albumImage != null && albumImage.length > 0 && mimeType != null && mimeType.length() > 0) { invalidateDataLength(); ID3v2PictureFrameData frameData = new ID3v2PictureFrameData(useFrameUnsynchronisation(), mimeType, (byte)0, null, albumImage); addFrame(createFrame(ID_IMAGE, frameData.toBytes()), true); } } public void clearAlbumImage() { clearFrameSet(obseleteFormat ? ID_IMAGE_OBSELETE : ID_IMAGE); } public String getAlbumImageMimeType() { ID3v2PictureFrameData frameData = createPictureFrameData(obseleteFormat ? ID_IMAGE_OBSELETE : ID_IMAGE); if (frameData != null && frameData.getMimeType() != null) return frameData.getMimeType(); return null; } public void clearFrameSet(String id) { if (frameSets.remove(id) != null) { invalidateDataLength(); } } private ArrayList<ID3v2ChapterFrameData> extractChapterFrameData(String id) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { ArrayList<ID3v2ChapterFrameData> chapterData = new ArrayList<ID3v2ChapterFrameData>(); List<ID3v2Frame> frames = frameSet.getFrames(); for (ID3v2Frame frame : frames) { ID3v2ChapterFrameData frameData; try { frameData = new ID3v2ChapterFrameData(useFrameUnsynchronisation(), frame.getData()); chapterData.add(frameData); } catch (InvalidDataException e) { // do nothing } } return chapterData; } return null; } private ArrayList<ID3v2ChapterTOCFrameData> extractChapterTOCFrameData(String id) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { ArrayList<ID3v2ChapterTOCFrameData> chapterData = new ArrayList<ID3v2ChapterTOCFrameData>(); List<ID3v2Frame> frames = frameSet.getFrames(); for (ID3v2Frame frame : frames) { ID3v2ChapterTOCFrameData frameData; try { frameData = new ID3v2ChapterTOCFrameData(useFrameUnsynchronisation(), frame.getData()); chapterData.add(frameData); } catch (InvalidDataException e) { // do nothing } } return chapterData; } return null; } protected ID3v2TextFrameData extractTextFrameData(String id) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { ID3v2Frame frame = (ID3v2Frame) frameSet.getFrames().get(0); ID3v2TextFrameData frameData; try { frameData = new ID3v2TextFrameData(useFrameUnsynchronisation(), frame.getData()); return frameData; } catch (InvalidDataException e) { // do nothing } } return null; } private ID3v2WWWFrameData extractWWWFrameData(String id) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { ID3v2Frame frame = (ID3v2Frame) frameSet.getFrames().get(0); ID3v2WWWFrameData frameData; try { frameData = new ID3v2WWWFrameData(useFrameUnsynchronisation(), frame.getData()); return frameData; } catch (InvalidDataException e) { // do nothing } } return null; } private ID3v2UrlFrameData extractUrlFrameData(String id) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { ID3v2Frame frame = (ID3v2Frame) frameSet.getFrames().get(0); ID3v2UrlFrameData frameData; try { frameData = new ID3v2UrlFrameData(useFrameUnsynchronisation(), frame.getData()); return frameData; } catch (InvalidDataException e) { // do nothing } } return null; } private ID3v2CommentFrameData extractCommentFrameData(String id, boolean itunes) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { Iterator<ID3v2Frame> iterator = frameSet.getFrames().iterator(); while (iterator.hasNext()) { ID3v2Frame frame = (ID3v2Frame) iterator.next(); ID3v2CommentFrameData frameData; try { frameData = new ID3v2CommentFrameData(useFrameUnsynchronisation(), frame.getData()); if (itunes && ITUNES_COMMENT_DESCRIPTION.equals(frameData.getDescription().toString())) { return frameData; } else if (! itunes) { return frameData; } } catch (InvalidDataException e) { // Do nothing } } } return null; } private ID3v2PictureFrameData createPictureFrameData(String id) { ID3v2FrameSet frameSet = frameSets.get(id); if (frameSet != null) { ID3v2Frame frame = (ID3v2Frame) frameSet.getFrames().get(0); ID3v2PictureFrameData frameData; try { if (obseleteFormat) frameData = new ID3v2ObseletePictureFrameData(useFrameUnsynchronisation(), frame.getData()); else frameData = new ID3v2PictureFrameData(useFrameUnsynchronisation(), frame.getData()); return frameData; } catch (InvalidDataException e) { // do nothing } } return null; } public boolean equals(Object obj) { if (! (obj instanceof AbstractID3v2Tag)) return false; if (super.equals(obj)) return true; AbstractID3v2Tag other = (AbstractID3v2Tag) obj; if (unsynchronisation != other.unsynchronisation) return false; if (extendedHeader != other.extendedHeader) return false; if (experimental != other.experimental) return false; if (footer != other.footer) return false; if (compression != other.compression) return false; if (dataLength != other.dataLength) return false; if (extendedHeaderLength != other.extendedHeaderLength) return false; if (version == null) { if (other.version != null) return false; } else if (other.version == null) return false; else if (! version.equals(other.version)) return false; if (frameSets == null) { if (other.frameSets != null) return false; } else if (other.frameSets == null) return false; else if (! frameSets.equals(other.frameSets)) return false; return true; } }
package com.nurkiewicz.java8.util; import com.google.common.base.Splitter; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.CharMatcher.anyOf; /** * @see Map#merge(Object, Object, BiFunction) * @see Map#computeIfAbsent(Object, Function) * @see Collectors#groupingBy(Function) */ public class LoremIpsum { public static String text() throws IOException { return IOUtils.toString(LoremIpsum.class.getResourceAsStream("/lorem-ipsum.txt")); } /** * Case insensitive */ public static Map<String, Integer> wordCount(String text) { throw new UnsupportedOperationException("wordCount()"); } private static List<String> splitWords(String text) { return Splitter .on(anyOf(" .,\n")) .trimResults() .omitEmptyStrings() .splitToList(text); } }
package com.pesegato.MonkeySheet; import com.pesegato.goldmonkey.Animation; import com.pesegato.goldmonkey.Container; /** * @author Pesegato */ public class MSContainer { boolean USE_COMPRESSION = false; public int numTiles; String[] sheets; String name; Container c; public MSContainer(Container c) { this.numTiles = c.size; this.name = c.id; this.sheets = new String[]{"Textures/MonkeySheet/" + name + (USE_COMPRESSION ? ".dds" : ".png")}; this.c = c; } public Animation[] getAnimList() { return MonkeySheetAppState.animationC.get(c); } public void setPath(String path) { this.sheets = new String[]{path + name + (USE_COMPRESSION ? ".dds" : ".png")}; } }
package com.postgresintl.logicaldecoding; import java.nio.ByteBuffer; import java.sql.*; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.postgresql.PGConnection; import org.postgresql.PGProperty; import org.postgresql.core.BaseConnection; import org.postgresql.core.ServerVersion; import org.postgresql.replication.LogSequenceNumber; import org.postgresql.replication.PGReplicationStream; /** * Hello world! * */ public class App { private final static String SLOT_NAME="slot"; Connection mgmntConnection; Connection replicationConnection; Connection dmlConnection; private static String toString(ByteBuffer buffer) { int offset = buffer.arrayOffset(); byte[] source = buffer.array(); int length = source.length - offset; return new String(source, offset, length); } public void createConnection() { try { mgmntConnection = DriverManager.getConnection("jdbc:postgresql://localhost:15432/test","rep",""); dmlConnection = DriverManager.getConnection("jdbc:postgresql://localhost:15432/test","davec",""); } catch (SQLException ex) { } } public void createLogicalReplicationSlot(String slotName, String outputPlugin ) throws InterruptedException, SQLException, TimeoutException { //drop previous slot dropReplicationSlot(mgmntConnection, slotName); try (PreparedStatement preparedStatement = mgmntConnection.prepareStatement("SELECT * FROM pg_create_logical_replication_slot(?, ?)") ) { preparedStatement.setString(1, slotName); preparedStatement.setString(2, outputPlugin); try (ResultSet rs = preparedStatement.executeQuery()) { while (rs.next()) { System.out.println("Slot Name: " + rs.getString(1)); System.out.println("Xlog Position: " + rs.getString(2)); } } } } public void dropReplicationSlot(Connection connection, String slotName) throws SQLException, InterruptedException, TimeoutException { try (PreparedStatement preparedStatement = connection.prepareStatement( "select pg_terminate_backend(active_pid) from pg_replication_slots " + "where active = true and slot_name = ?")) { preparedStatement.setString(1, slotName); preparedStatement.execute(); } waitStopReplicationSlot(connection, slotName); try (PreparedStatement preparedStatement = connection.prepareStatement("select pg_drop_replication_slot(slot_name) " + "from pg_replication_slots where slot_name = ?")) { preparedStatement.setString(1, slotName); preparedStatement.execute(); } } public boolean isReplicationSlotActive(Connection connection, String slotName) throws SQLException { try (PreparedStatement preparedStatement = connection.prepareStatement("select active from pg_replication_slots where slot_name = ?")){ preparedStatement.setString(1, slotName); try (ResultSet rs = preparedStatement.executeQuery()) { return rs.next() && rs.getBoolean(1); } } } private void waitStopReplicationSlot(Connection connection, String slotName) throws InterruptedException, TimeoutException, SQLException { long startWaitTime = System.currentTimeMillis(); boolean stillActive; long timeInWait = 0; do { stillActive = isReplicationSlotActive(connection, slotName); if (stillActive) { TimeUnit.MILLISECONDS.sleep(100L); timeInWait = System.currentTimeMillis() - startWaitTime; } } while (stillActive && timeInWait <= 30000); if (stillActive) { throw new TimeoutException("Wait stop replication slot " + timeInWait + " timeout occurs"); } } public void receiveChangesOccursBeforStartReplication() throws Exception { PGConnection pgConnection = (PGConnection) replicationConnection; LogSequenceNumber lsn = getCurrentLSN(); Statement st = dmlConnection.createStatement(); st.execute("insert into test_logical_table(name) values('previous value')"); st.close(); PGReplicationStream stream = pgConnection .getReplicationAPI() .replicationStream() .logical() .withSlotName(SLOT_NAME) .withStartPosition(lsn) .withSlotOption("include-xids", true) // .withSlotOption("pretty-print",true) .withSlotOption("skip-empty-xacts", true) .withStatusInterval(20, TimeUnit.SECONDS) .start(); ByteBuffer buffer; while(true) { buffer = stream.readPending(); if (buffer == null) { TimeUnit.MILLISECONDS.sleep(10L); continue; } System.out.println( toString(buffer)); //feedback stream.setAppliedLSN(stream.getLastReceiveLSN()); stream.setFlushedLSN(stream.getLastReceiveLSN()); } } private LogSequenceNumber getCurrentLSN() throws SQLException { try (Statement st = mgmntConnection.createStatement()) { try (ResultSet rs = st.executeQuery("select " + (((BaseConnection) mgmntConnection).haveMinimumServerVersion(ServerVersion.v10) ? "pg_current_wal_location()" : "pg_current_xlog_location()"))) { if (rs.next()) { String lsn = rs.getString(1); return LogSequenceNumber.valueOf(lsn); } else { return LogSequenceNumber.INVALID_LSN; } } } } private void openReplicationConnection() throws Exception { Properties properties = new Properties(); properties.setProperty("user","rep"); properties.setProperty("password","test"); PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, "9.4"); PGProperty.REPLICATION.set(properties, "database"); PGProperty.PREFER_QUERY_MODE.set(properties, "simple"); replicationConnection = DriverManager.getConnection("jdbc:postgresql://localhost:15432/test",properties); } public static void main( String[] args ) { String pluginName = "test_decoding"; //wal2json App app = new App(); app.createConnection(); try { app.createLogicalReplicationSlot(SLOT_NAME, pluginName); app.openReplicationConnection(); app.receiveChangesOccursBeforStartReplication(); } catch (InterruptedException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
package com.rultor.agents.github; import com.jcabi.aspects.Immutable; import com.jcabi.github.Bulk; import com.jcabi.github.Comment; import com.jcabi.github.Github; import com.jcabi.github.Issue; import com.jcabi.github.Smarts; import com.jcabi.log.Logger; import com.jcabi.xml.XML; import com.rultor.agents.AbstractAgent; import com.rultor.agents.daemons.Home; import com.rultor.spi.Profile; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.ResourceBundle; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.exception.ExceptionUtils; import org.cactoos.iterable.Joined; import org.xembly.Directive; import org.xembly.Directives; /** * Understands request. * * @author Yegor Bugayenko (yegor256@gmail.com) * @version $Id$ * @since 1.3 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @Immutable @ToString @EqualsAndHashCode(callSuper = false, of = { "github", "question" }) @SuppressWarnings ( { "PMD.CyclomaticComplexity", "PMD.StdCyclomaticComplexity", "PMD.ModifiedCyclomaticComplexity" } ) public final class Understands extends AbstractAgent { /** * Message bundle. */ private static final ResourceBundle PHRASES = ResourceBundle.getBundle("phrases"); /** * Github. */ private final transient Github github; /** * Question. */ private final transient Question question; /** * Ctor. * @param ghub Github client * @param qtn Question */ public Understands(final Github ghub, final Question qtn) { super( "/talk[@later='true']", "/talk/wire[github-repo and github-issue]" ); this.github = ghub; this.question = qtn; } // @checkstyle ExecutableStatementCountCheck (50 lines) // @checkstyle CyclomaticComplexityCheck (100 lines) @Override public Iterable<Directive> process(final XML xml) throws IOException { final Issue.Smart issue = new TalkIssues(this.github, xml).get(); final Iterator<Comment.Smart> comments = new SafeIterator<>( new Smarts<Comment.Smart>( new Joined<Comment>( Collections.singleton(new FirstComment(issue)), new Bulk<>(issue.comments().iterate(new Date(0L))) ) ).iterator() ); final int seen = Understands.seen(xml); int next = seen; int fresh = 0; int total = 0; Req req = Req.EMPTY; while (comments.hasNext()) { final Comment.Smart comment = comments.next(); ++total; if (comment.number() <= seen) { continue; } ++fresh; req = this.parse(comment, xml); if (req.equals(Req.LATER)) { break; } next = comment.number(); if (!req.equals(Req.EMPTY)) { break; } } if (next < seen) { throw new IllegalStateException( String.format( "comment #%d is younger than #%d, something is wrong", next, seen ) ); } final Directives dirs = new Directives(); if (req.equals(Req.EMPTY)) { Logger.info( this, "nothing new in %s#%d, fresh/total: %d/%d", issue.repo().coordinates(), issue.number(), fresh, total ); } else if (req.equals(Req.DONE)) { Logger.info( this, "simple request in %s issue.repo().coordinates(), issue.number() ); } else if (req.equals(Req.LATER)) { Logger.info( this, "temporary pause in %s#%d, at message #%d", issue.repo().coordinates(), issue.number(), next ); } else if (xml.xpath(String.format("//archive/log[@id='%d']", next)) .isEmpty()) { dirs.xpath("/talk/request").remove() .xpath("/talk[not(request)]").strict(1) .add("request") .attr("id", Integer.toString(next)) .append(req.dirs()); } else { Logger.error( this, "We have seen this conversation already: %d", next ); } if (next > seen) { dirs.xpath("/talk/wire") .addIf("github-seen") .set(Integer.toString(next)); } return dirs.xpath("/talk") .attr("later", Boolean.toString(!req.equals(Req.EMPTY))); } /** * Understand. * @param comment Comment * @param xml XML * @return Req * @throws IOException If fails */ private Req parse(final Comment.Smart comment, final XML xml) throws IOException { Req req; try { req = this.question.understand( comment, new Home(xml, Integer.toString(comment.number())).uri() ); } catch (final Profile.ConfigException ex) { new Answer(comment).post( false, String.format( Understands.PHRASES.getString("Understands.broken-profile"), ExceptionUtils.getRootCauseMessage(ex) ) ); req = Req.EMPTY; } return req; } /** * Last seen message. * @param xml XML * @return Number */ private static int seen(final XML xml) { final int seen; if (xml.nodes("/talk/wire/github-seen").isEmpty()) { seen = 0; } else { seen = Integer.parseInt( xml.xpath("/talk/wire/github-seen/text()").get(0) ); } return seen; } }
package com.rultor.agents.github; import com.jcabi.aspects.Immutable; import com.jcabi.github.Bulk; import com.jcabi.github.Comment; import com.jcabi.github.Github; import com.jcabi.github.Issue; import com.jcabi.github.Smarts; import com.jcabi.log.Logger; import com.jcabi.xml.XML; import com.rultor.agents.AbstractAgent; import com.rultor.agents.daemons.Home; import com.rultor.spi.Profile; import java.io.IOException; import java.util.ResourceBundle; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.exception.ExceptionUtils; import org.xembly.Directive; import org.xembly.Directives; /** * Understands request. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.3 */ @Immutable @ToString @EqualsAndHashCode(callSuper = false, of = { "github", "question" }) public final class Understands extends AbstractAgent { /** * Message bundle. */ private static final ResourceBundle PHRASES = ResourceBundle.getBundle("phrases"); /** * Github. */ private final transient Github github; /** * Question. */ private final transient Question question; /** * Ctor. * @param ghub Github client * @param qtn Question */ public Understands(final Github ghub, final Question qtn) { super( "/talk[@later='true']", "/talk/wire[github-repo and github-issue]" ); this.github = ghub; this.question = qtn; } // @checkstyle ExecutableStatementCountCheck (50 lines) @Override public Iterable<Directive> process(final XML xml) throws IOException { final Issue.Smart issue = new TalkIssues(this.github, xml).get(); final Iterable<Comment.Smart> comments = new Smarts<Comment.Smart>( new Bulk<Comment>(issue.comments().iterate()) ); final int seen = Understands.seen(xml); int next = seen; int fresh = 0; int total = 0; Req req = Req.EMPTY; for (final Comment.Smart comment : comments) { ++total; if (comment.number() <= seen) { continue; } ++fresh; req = this.parse(comment, xml); if (req.equals(Req.LATER)) { break; } next = comment.number(); if (!req.equals(Req.EMPTY)) { break; } } final Directives dirs = new Directives(); if (req.equals(Req.EMPTY)) { Logger.info( this, "nothing new in %s#%d, fresh/total: %d/%d", issue.repo().coordinates(), issue.number(), fresh, total ); } else if (req.equals(Req.LATER)) { Logger.info( this, "temporary pause in %s#%d, at message #%d", issue.repo().coordinates(), issue.number(), next ); } else { dirs.xpath("/talk").add("request") .attr("id", Integer.toString(next)) .append(req.dirs()); } if (next > seen) { dirs.xpath("/talk/wire") .addIf("github-seen") .set(Integer.toString(next)); } return dirs.xpath("/talk[not(@later)]") .attr("later", Boolean.toString(req.equals(Req.LATER))); } /** * Understand. * @param comment Comment * @param xml XML * @return Req * @throws IOException If fails */ private Req parse(final Comment.Smart comment, final XML xml) throws IOException { Req req; try { req = this.question.understand( comment, new Home(xml, Integer.toString(comment.number())).uri() ); } catch (final Profile.SyntaxException ex) { new Answer(comment).post( String.format( Understands.PHRASES.getString("Understands.broken-profile"), ExceptionUtils.getRootCauseMessage(ex) ) ); req = Req.EMPTY; } return req; } /** * Last seen message. * @param xml XML * @return Number */ private static int seen(final XML xml) { final int seen; if (xml.nodes("/talk/wire/github-seen").isEmpty()) { seen = 0; } else { seen = Integer.parseInt( xml.xpath("/talk/wire/github-seen/text()").get(0) ); } return seen; } }
package com.semihunaldi.excelorm; import com.semihunaldi.excelorm.annotations.Excel; import com.semihunaldi.excelorm.annotations.ExcelColumn; import com.semihunaldi.excelorm.exceptions.IllegalExcelArgumentException; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.Date; import java.util.LinkedList; import java.util.List; public class ExcelReader { public <T extends BaseExcel> List<T> read(InputStream inputStream, Class<T> clazz) throws InstantiationException, IllegalAccessException, IllegalExcelArgumentException, IOException { List<T> tList = new LinkedList<>(); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream); inputStream.close(); read(clazz, tList, xssfWorkbook); xssfWorkbook.getPackage().revert(); return tList; } public <T extends BaseExcel> List<T> read(File file, Class<T> clazz) throws InstantiationException, IllegalAccessException, IllegalExcelArgumentException, IOException, InvalidFormatException { List<T> tList = new LinkedList<>(); XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); read(clazz, tList, xssfWorkbook); xssfWorkbook.getPackage().revert(); return tList; } private <T extends BaseExcel> void read(Class<T> clazz, List<T> tList, XSSFWorkbook xssfWorkbook) throws InstantiationException, IllegalAccessException, IllegalExcelArgumentException { Excel excelAnnotation = clazz.getAnnotation(Excel.class); if (excelAnnotation != null) { Validator.validate(excelAnnotation); int firstRow = excelAnnotation.firstRow(); int firstCol = excelAnnotation.firstCol(); String sheetName = excelAnnotation.sheetName(); XSSFSheet xssfSheet = xssfWorkbook.getSheet(sheetName); for (int rows = firstRow; rows < firstRow + xssfSheet.getPhysicalNumberOfRows(); rows++) { T t = clazz.newInstance(); updateRowField(t,clazz,rows); XSSFRow row = xssfSheet.getRow(rows); if(row != null) { for (int cells = firstCol; cells < firstCol + row.getPhysicalNumberOfCells(); cells++) { XSSFCell cell = row.getCell(cells); if(cell != null) { Field field = findFieldByColNumber(clazz, cells,firstCol); if (field != null) { setFieldValue(t, cell, field); } } } tList.add(t); } } } } private <T extends BaseExcel> void setFieldValue(T t, XSSFCell cell, Field field) { Object o = getCellValue(cell, field); setFieldValue(t, field, o); } private <T extends BaseExcel> void setFieldValue(T t, Field field, Object o) { try { boolean accessible = field.isAccessible(); field.setAccessible(true); field.set(t, o); field.setAccessible(accessible); } catch (IllegalAccessException e) { //swallow } } private Field findFieldByColNumber(Class clazz, int col, int firstCol) { List<Field> fieldsListWithAnnotation = FieldUtils.getFieldsListWithAnnotation(clazz, ExcelColumn.class); for (Field field : fieldsListWithAnnotation) { ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); if (firstCol + annotation.col() == col) { return field; } } return null; } private <T extends BaseExcel> void updateRowField(T t, Class clazz, int row) { Field field = FieldUtils.getField(clazz,"_myRow",true); setFieldValue(t,field,row); } private Object getCellValue(XSSFCell cell, Field field) { Class<?> type = field.getType(); try { if (type == String.class) { cell.setCellType(CellType.STRING); return cell.getStringCellValue(); } else if (type == Integer.class) { return Integer.valueOf(getNumericTypesAsString(cell)); } else if (type == Double.class) { return Double.valueOf(getNumericTypesAsString(cell)); } else if (type == BigInteger.class) { return new BigInteger(getNumericTypesAsString(cell)); } else if (type == Long.class) { return Long.valueOf(getNumericTypesAsString(cell)); } else if (type == Boolean.class) { cell.setCellType(CellType.BOOLEAN); return cell.getBooleanCellValue(); } else if(type == Date.class) { return tryToGetDateCellValue(cell,field); } else { cell.setCellType(CellType.STRING); return cell.getStringCellValue(); } } catch (Exception e) { return null; } } private Date tryToGetDateCellValue(XSSFCell cell, Field field) { try { ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); if(annotation != null && StringUtils.isNotBlank(annotation.dateFormat())) { cell.setCellType(CellType.STRING); String stringCellValue = cell.getStringCellValue(); DateTimeFormatter dtf = DateTimeFormat.forPattern(annotation.dateFormat()); DateTime dateTime = dtf.parseDateTime(stringCellValue); return dateTime.toDate(); } else { try { return cell.getDateCellValue(); } catch (Exception e) { return null; } } } catch (Exception e1) { try { return cell.getDateCellValue(); } catch (Exception e) { return null; } } } private String getNumericTypesAsString(XSSFCell cell) { cell.setCellType(CellType.STRING); return cell.getStringCellValue(); } }
package com.showka.u01.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.showka.entity.MKokyaku; import com.showka.u01.service.MKokyakuCrudSearchCriteria; import com.showka.u01.service.i.MKokyakuCrudService; /** * U01G001 * * @author ShowKa * */ @Controller @EnableAutoConfiguration public class U01G001Controller { @Autowired private MKokyakuCrudService service; // public method called by request /** * * * * @param model * @param session * @return */ @RequestMapping(value = "/u01g001", method = RequestMethod.GET) public String index(Map<String, Object> model, HttpSession session) { return "/u01/u01g001"; } /** * * * @param form */ @RequestMapping(value = "/u01g001/search", method = RequestMethod.GET) public String search(@ModelAttribute U01G001Form form, Model model, HttpSession session) { MKokyakuCrudSearchCriteria criteria = new MKokyakuCrudSearchCriteria(); criteria.setName(form.getKokyakuName()); criteria.setBushoName(form.getBushoName()); List<MKokyaku> result = service.search(criteria); // list ArrayList<HashMap<String, String>> kokyakuList = new ArrayList<>(); for (MKokyaku k : result) { HashMap<String, String> m = new HashMap<String, String>(); m.put("name", k.getName()); m.put("bushoName", k.getShukanBusho().getName()); kokyakuList.add(m); } model.addAttribute("kokyakuList", kokyakuList); return "/u01/u01g001KokyakuList :: list"; } }
package com.wizzardo.http; import com.wizzardo.epoll.ByteBufferProvider; import com.wizzardo.epoll.EpollServer; import com.wizzardo.epoll.IOThread; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public abstract class AbstractHttpServer<T extends HttpConnection> extends EpollServer<T> { private BlockingQueue<T> queue = new LinkedBlockingQueue<>(); private int workersCount; private int sessionTimeoutSec = 30 * 60; protected MimeProvider mimeProvider; public AbstractHttpServer(int port) { this(null, port); } public AbstractHttpServer(String host, int port) { this(host, port, 0); } public AbstractHttpServer(String host, int port, int workersCount) { super(host, port); this.workersCount = workersCount; System.out.println("worker count: " + workersCount); for (int i = 0; i < workersCount; i++) { createWorker(queue, "worker_" + i).start(); } } protected Worker<T> createWorker(BlockingQueue<T> queue, String name) { return new HttpWorker<>(this, queue, name); } @Override public void run() { Session.createSessionsHolder(sessionTimeoutSec); super.run(); } @Override protected T createConnection(int fd, int ip, int port) { return (T) new HttpConnection(fd, ip, port, this); } @Override protected IOThread<T> createIOThread(int number, int divider) { return new HttpIOThread(number, divider); } private class HttpIOThread extends IOThread<T> { public HttpIOThread(int number, int divider) { super(number, divider); } @Override public void onRead(T connection) { if (connection.processInputListener()) return; process(connection, this); } @Override public void onDisconnect(T connection) { super.onDisconnect(connection); // System.out.println("close " + connection); } } protected boolean checkData(T connection, ByteBufferProvider bufferProvider) { ByteBuffer b; try { while ((b = connection.read(connection.getBufferSize(), bufferProvider)).limit() > 0) { if (connection.check(b)) break; } if (!connection.isRequestReady()) return false; } catch (IOException e) { e.printStackTrace(); try { connection.close(); } catch (IOException e1) { e1.printStackTrace(); } return false; } return true; } private void process(T connection, ByteBufferProvider bufferProvider) { if (workersCount > 0) { queue.add(connection); } else if (checkData(connection, bufferProvider)) while (processConnection(connection)) { } } protected boolean processConnection(T connection) { try { handle(connection); return finishHandling(connection); } catch (Exception t) { try { onError(connection, t); } catch (Exception e) { e.printStackTrace(); } } return false; } protected abstract void handle(T connection) throws Exception; protected void onError(T connection, Exception e) { e.printStackTrace(); //TODO render error page } protected boolean finishHandling(T connection) throws IOException { if (connection.getResponse().isAsync()) return false; connection.getResponse().commit(connection); connection.flushOutputStream(); if (!connection.onFinishingHandling()) return false; if (connection.isRequestReady()) return true; else if (connection.isReadyToRead() && checkData(connection, (ByteBufferProvider) Thread.currentThread())) return true; return false; } public void setSessionTimeout(int sec) { this.sessionTimeoutSec = sec; } public MimeProvider getMimeProvider() { if (mimeProvider == null) mimeProvider = createMimeProvider(); return mimeProvider; } protected MimeProvider createMimeProvider() { return new MimeProvider(); } }
package com.yahoo.bullet.parsing; import com.google.gson.annotations.Expose; import com.yahoo.bullet.BulletConfig; import com.yahoo.bullet.operations.AggregationOperations; import com.yahoo.bullet.operations.AggregationOperations.AggregationType; import com.yahoo.bullet.operations.AggregationOperations.GroupOperationType; import com.yahoo.bullet.operations.aggregations.GroupOperation; import com.yahoo.bullet.operations.aggregations.Strategy; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import static com.yahoo.bullet.operations.AggregationOperations.isEmpty; import static com.yahoo.bullet.parsing.Error.makeError; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; @Getter @Setter public class Aggregation implements Configurable, Validatable { @Expose private Integer size; @Expose private AggregationType type; @Expose private Map<String, Object> attributes; @Expose private Map<String, String> fields; @Setter(AccessLevel.NONE) private Set<GroupOperation> groupOperations; @Setter(AccessLevel.NONE) private Strategy strategy; // In case, any strategies need it. private Map configuration; // TODO: Move this to a Validation object tied in properly with Strategies when all are added. public static final Set<AggregationType> SUPPORTED_AGGREGATION_TYPES = new HashSet<>(asList(AggregationType.GROUP, AggregationType.COUNT_DISTINCT, AggregationType.RAW)); public static final Set<GroupOperationType> SUPPORTED_GROUP_OPERATIONS = new HashSet<>(asList(GroupOperationType.COUNT, GroupOperationType.AVG, GroupOperationType.MAX, GroupOperationType.MIN, GroupOperationType.SUM)); public static final String TYPE_NOT_SUPPORTED_ERROR_PREFIX = "Aggregation type not supported"; public static final String TYPE_NOT_SUPPORTED_RESOLUTION = "Current supported aggregation types are: RAW, GROUP, " + " COUNT DISTINCT"; public static final String SUPPORTED_GROUP_OPERATIONS_RESOLUTION = "Currently supported operations are: COUNT, AVG, MIN, MAX, SUM"; public static final String GROUP_OPERATION_REQUIRES_FIELD = "Group operation requires a field: "; public static final String OPERATION_REQUIRES_FIELD_RESOLUTION = "Please add a field for this operation."; public static final Error COUNT_DISTINCT_REQUIRES_FIELD_ERROR = makeError("Count Distinct requires atleast one field", OPERATION_REQUIRES_FIELD_RESOLUTION); // Temporary public static final Error GROUP_FIELDS_NOT_SUPPORTED_ERROR = makeError("Group type aggregation cannot have fields", "Do not specify fields when type is GROUP"); // Temporary public static final Error GROUP_ALL_OPERATION_ERROR = makeError("Group all needs to specify an operation to do", SUPPORTED_GROUP_OPERATIONS_RESOLUTION); public static final Integer DEFAULT_SIZE = 1; public static final Integer DEFAULT_MAX_SIZE = 30; public static final String DEFAULT_FIELD_SEPARATOR = "|"; public static final String OPERATIONS = "operations"; public static final String OPERATION_TYPE = "type"; public static final String OPERATION_FIELD = "field"; public static final String OPERATION_NEW_NAME = "newName"; /** * Default constructor. GSON recommended */ public Aggregation() { type = AggregationType.RAW; } @Override public void configure(Map configuration) { this.configuration = configuration; Number defaultSize = (Number) configuration.getOrDefault(BulletConfig.AGGREGATION_DEFAULT_SIZE, DEFAULT_SIZE); Number maximumSize = (Number) configuration.getOrDefault(BulletConfig.AGGREGATION_MAX_SIZE, DEFAULT_MAX_SIZE); int sizeDefault = defaultSize.intValue(); int sizeMaximum = maximumSize.intValue(); // Null or negative, then default, else min of size and max size = (size == null || size < 0) ? sizeDefault : Math.min(size, sizeMaximum); // Parse any group operations first before calling getStrategy groupOperations = getOperations(); strategy = AggregationOperations.getStrategyFor(this); } @Override public Optional<List<Error>> validate() { if (type == AggregationType.GROUP) { // We only support GROUP by ALL for now if (!isEmpty(fields)) { return Optional.of(singletonList(GROUP_FIELDS_NOT_SUPPORTED_ERROR)); } // Group operations are only created if they are supported. if (isEmpty(groupOperations)) { return Optional.of(singletonList(GROUP_ALL_OPERATION_ERROR)); } } if (type == AggregationType.COUNT_DISTINCT) { if (isEmpty(fields)) { return Optional.of(singletonList(COUNT_DISTINCT_REQUIRES_FIELD_ERROR)); } } // Supported aggregation types should be documented in TYPE_NOT_SUPPORTED_RESOLUTION if (!SUPPORTED_AGGREGATION_TYPES.contains(type)) { String typeSuffix = type == null ? "" : ": " + type; return Optional.of(singletonList(makeError(TYPE_NOT_SUPPORTED_ERROR_PREFIX + typeSuffix, TYPE_NOT_SUPPORTED_RESOLUTION))); } if (groupOperations != null) { for (GroupOperation operation : groupOperations) { if (operation.getField() == null && operation.getType() != GroupOperationType.COUNT) { return Optional.of(singletonList(makeError(GROUP_OPERATION_REQUIRES_FIELD + operation.getType(), OPERATION_REQUIRES_FIELD_RESOLUTION))); } } } return Optional.empty(); } private Set<GroupOperation> getOperations() { if (isEmpty(attributes)) { return null; } return parseOperations(attributes.get(OPERATIONS)); } private Set<GroupOperation> parseOperations(Object object) { if (object == null) { return null; } try { // Unchecked cast needed. List<Map<String, String>> operations = (List<Map<String, String>>) object; // Return a list of distinct, non-null, GroupOperations return operations.stream().map(Aggregation::makeGroupOperation) .filter(Objects::nonNull) .collect(Collectors.toSet()); } catch (ClassCastException cce) { return null; } } private static GroupOperation makeGroupOperation(Map<String, String> data) { String type = data.get(OPERATION_TYPE); Optional<GroupOperationType> operation = SUPPORTED_GROUP_OPERATIONS.stream().filter(t -> t.isMe(type)).findFirst(); // May or may not be present String field = data.get(OPERATION_FIELD); // May or may not be present String newName = data.get(OPERATION_NEW_NAME); // Unknown GroupOperations are ignored. return operation.isPresent() ? new GroupOperation(operation.get(), field, newName) : null; } @Override public String toString() { return "{size: " + size + ", type: " + type + ", fields: " + fields + ", attributes: " + attributes + "}"; } }
package com.yandex.money.api.model; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.yandex.money.api.model.showcase.ShowcaseReference; import com.yandex.money.api.time.DateTime; import com.yandex.money.api.typeadapters.model.AlphaCurrencyTypeAdapter; import com.yandex.money.api.util.Enums; import java.math.BigDecimal; import java.util.Collections; import java.util.List; import java.util.Map; /** * Operation details. */ public class Operation implements Identifiable { /** * Operation id. */ @SuppressWarnings("WeakerAccess") @SerializedName("operation_id") public final String operationId; /** * Status of operation. */ @SerializedName("status") public final OperationStatus status; /** * Pattern id. */ @SuppressWarnings("WeakerAccess") @SerializedName("pattern_id") public final String patternId; /** * Direction of operation. */ @SerializedName("direction") public final Direction direction; /** * Amount. */ @SerializedName("amount") public final BigDecimal amount; /** * Received amount. */ @SuppressWarnings("WeakerAccess") @SerializedName("amount_due") public final BigDecimal amountDue; /** * Fee. */ @SerializedName("fee") public final BigDecimal fee; /** * Operation datetime. */ @SerializedName("datetime") public final DateTime datetime; /** * Title of operation. */ @SerializedName("title") public final String title; /** * Sender. */ @SuppressWarnings("WeakerAccess") @SerializedName("sender") public final String sender; /** * Recipient. */ @SuppressWarnings("WeakerAccess") @SerializedName("recipient") public final String recipient; /** * Type of recipient identifier. */ @SuppressWarnings("WeakerAccess") @SerializedName("recipient_type") public final PayeeIdentifierType recipientType; /** * Message to recipient. */ @SerializedName("message") public final String message; /** * operation comment */ @SuppressWarnings("WeakerAccess") @SerializedName("comment") public final String comment; /** * {@code true} if operation is protected with a code */ @SuppressWarnings("WeakerAccess") @SerializedName("codepro") public final Boolean codepro; /** * Protection code for operation. */ @SuppressWarnings("WeakerAccess") @SerializedName("protection_code") public final String protectionCode; /** * Protection code expiration datetime. */ @SuppressWarnings("WeakerAccess") @SerializedName("expires") public final DateTime expires; /** * Answer datetime of operation acceptance/revoke. */ @SuppressWarnings("WeakerAccess") @SerializedName("answer_datetime") public final DateTime answerDatetime; /** * Label of operation. */ @SerializedName("label") public final String label; /** * Details of operation. */ @SerializedName("details") public final String details; /** * {@code true} if operation can be repeated. */ @SuppressWarnings("WeakerAccess") @SerializedName("repeatable") public final Boolean repeatable; /** * Payment parameters. */ @SuppressWarnings("WeakerAccess") @SerializedName("payment_parameters") public final Map<String, String> paymentParameters; @SuppressWarnings("WeakerAccess") @SerializedName("favourite") public final Boolean favorite; /** * Type of operation. */ @SerializedName("type") public final Type type; /** * Digital goods. */ @SuppressWarnings("WeakerAccess") @SerializedName("digital_goods") public final DigitalGoods digitalGoods; /** * Id of categories */ @SuppressWarnings("WeakerAccess") @SerializedName("categories") public final List<Integer> categories; /** * Spending categories */ @SuppressWarnings("WeakerAccess") @SerializedName("spendingCategories") public final List<SpendingCategory> spendingCategories; /** * Type of showcase */ @SuppressWarnings("WeakerAccess") @SerializedName("showcase_format") public final ShowcaseReference.Format showcaseFormat; /** * Available operations */ @SuppressWarnings("WeakerAccess") @SerializedName("available_operations") public final List<AvailableOperation> availableOperations; /** * Operation currency (ISO-4217 3-alpha currency symbol). */ @SuppressWarnings("WeakerAccess") @SerializedName("amount_currency") @JsonAdapter(AlphaCurrencyTypeAdapter.class) public final Currency amountCurrency; /** * Exchange currency amount. The currency is always different from the currency of the account * for which the history is requested. */ @SuppressWarnings("WeakerAccess") @SerializedName("exchange_amount") public final BigDecimal exchangeAmount; /** * Exchange currency (ISO-4217 3-alpha currency symbol). */ @SuppressWarnings("WeakerAccess") @SerializedName("exchange_amount_currency") @JsonAdapter(AlphaCurrencyTypeAdapter.class) public final Currency exchangeAmountCurrency; /** * Use {@link com.yandex.money.api.model.Operation.Builder} instead. */ protected Operation(Builder builder) { operationId = builder.operationId; status = builder.status; type = builder.type; direction = builder.direction; title = builder.title; patternId = builder.patternId; amount = builder.amount; amountDue = builder.amountDue; fee = builder.fee; datetime = builder.datetime; sender = builder.sender; recipient = builder.recipient; recipientType = builder.recipientType; message = builder.message; comment = builder.comment; codepro = builder.codepro; protectionCode = builder.protectionCode; expires = builder.expires; answerDatetime = builder.answerDatetime; label = builder.label; details = builder.details; repeatable = builder.repeatable; paymentParameters = builder.paymentParameters != null ? Collections.unmodifiableMap(builder.paymentParameters) : null; favorite = builder.favorite; digitalGoods = builder.digitalGoods; categories = builder.categories != null ? Collections.unmodifiableList(builder.categories) : null; spendingCategories = builder.spendingCategories != null ? Collections.unmodifiableList(builder.spendingCategories) : null; showcaseFormat = builder.format; availableOperations = builder.availableOperations != null ? Collections.unmodifiableList(builder.availableOperations) : null; amountCurrency = builder.amountCurrency; exchangeAmount = builder.exchangeAmount; exchangeAmountCurrency = builder.exchangeAmountCurrency; } @Override public String getId() { return operationId; } public boolean isCodepro() { return codepro != null && codepro; } public boolean isRepeatable() { return repeatable != null && repeatable; } public boolean isFavorite() { return favorite != null && favorite; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Operation operation = (Operation) o; if (operationId != null ? !operationId.equals(operation.operationId) : operation.operationId != null) return false; if (status != operation.status) return false; if (patternId != null ? !patternId.equals(operation.patternId) : operation.patternId != null) return false; if (direction != operation.direction) return false; if (amount != null ? !amount.equals(operation.amount) : operation.amount != null) return false; if (amountDue != null ? !amountDue.equals(operation.amountDue) : operation.amountDue != null) return false; if (fee != null ? !fee.equals(operation.fee) : operation.fee != null) return false; if (datetime != null ? !datetime.equals(operation.datetime) : operation.datetime != null) return false; if (title != null ? !title.equals(operation.title) : operation.title != null) return false; if (sender != null ? !sender.equals(operation.sender) : operation.sender != null) return false; if (recipient != null ? !recipient.equals(operation.recipient) : operation.recipient != null) return false; if (recipientType != operation.recipientType) return false; if (message != null ? !message.equals(operation.message) : operation.message != null) return false; if (comment != null ? !comment.equals(operation.comment) : operation.comment != null) return false; if (codepro != null ? !codepro.equals(operation.codepro) : operation.codepro != null) return false; if (protectionCode != null ? !protectionCode.equals(operation.protectionCode) : operation.protectionCode != null) return false; if (expires != null ? !expires.equals(operation.expires) : operation.expires != null) return false; if (answerDatetime != null ? !answerDatetime.equals(operation.answerDatetime) : operation.answerDatetime != null) return false; if (label != null ? !label.equals(operation.label) : operation.label != null) return false; if (details != null ? !details.equals(operation.details) : operation.details != null) return false; if (repeatable != null ? !repeatable.equals(operation.repeatable) : operation.repeatable != null) return false; if (paymentParameters != null ? !paymentParameters.equals(operation.paymentParameters) : operation.paymentParameters != null) return false; if (favorite != null ? !favorite.equals(operation.favorite) : operation.favorite != null) return false; if (type != operation.type) return false; if (digitalGoods != null ? !digitalGoods.equals(operation.digitalGoods) : operation.digitalGoods != null) return false; if (categories != null ? !categories.equals(operation.categories) : operation.categories != null) return false; if (spendingCategories != null ? !spendingCategories.equals(operation.spendingCategories) : operation.spendingCategories != null) return false; //noinspection SimplifiableIfStatement if (showcaseFormat != operation.showcaseFormat) return false; if (amountCurrency != null ? !amountCurrency.equals(operation.amountCurrency) : operation.amountCurrency != null) return false; if (exchangeAmount != null ? !exchangeAmount.equals(operation.exchangeAmount) : operation.exchangeAmount != null) return false; if (exchangeAmountCurrency != null ? !exchangeAmountCurrency.equals(operation.exchangeAmountCurrency) : operation.exchangeAmountCurrency != null) return false; return availableOperations != null ? availableOperations.equals(operation.availableOperations) : operation.availableOperations == null; } @Override public int hashCode() { int result = operationId != null ? operationId.hashCode() : 0; result = 31 * result + (status != null ? status.hashCode() : 0); result = 31 * result + (patternId != null ? patternId.hashCode() : 0); result = 31 * result + (direction != null ? direction.hashCode() : 0); result = 31 * result + (amount != null ? amount.hashCode() : 0); result = 31 * result + (amountDue != null ? amountDue.hashCode() : 0); result = 31 * result + (fee != null ? fee.hashCode() : 0); result = 31 * result + (datetime != null ? datetime.hashCode() : 0); result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (sender != null ? sender.hashCode() : 0); result = 31 * result + (recipient != null ? recipient.hashCode() : 0); result = 31 * result + (recipientType != null ? recipientType.hashCode() : 0); result = 31 * result + (message != null ? message.hashCode() : 0); result = 31 * result + (comment != null ? comment.hashCode() : 0); result = 31 * result + (codepro != null ? codepro.hashCode() : 0); result = 31 * result + (protectionCode != null ? protectionCode.hashCode() : 0); result = 31 * result + (expires != null ? expires.hashCode() : 0); result = 31 * result + (answerDatetime != null ? answerDatetime.hashCode() : 0); result = 31 * result + (label != null ? label.hashCode() : 0); result = 31 * result + (details != null ? details.hashCode() : 0); result = 31 * result + (repeatable != null ? repeatable.hashCode() : 0); result = 31 * result + (paymentParameters != null ? paymentParameters.hashCode() : 0); result = 31 * result + (favorite != null ? favorite.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (digitalGoods != null ? digitalGoods.hashCode() : 0); result = 31 * result + (categories != null ? categories.hashCode() : 0); result = 31 * result + (spendingCategories != null ? spendingCategories.hashCode() : 0); result = 31 * result + (showcaseFormat != null ? showcaseFormat.hashCode() : 0); result = 31 * result + (availableOperations != null ? availableOperations.hashCode() : 0); result = 31 * result + (amountCurrency != null ? amountCurrency.hashCode() : 0); result = 31 * result + (exchangeAmount != null ? exchangeAmount.hashCode() : 0); result = 31 * result + (exchangeAmountCurrency != null ? exchangeAmountCurrency.hashCode() : 0); return result; } @Override public String toString() { return "Operation{" + "operationId='" + operationId + '\'' + ", status=" + status + ", patternId='" + patternId + '\'' + ", direction=" + direction + ", amount=" + amount + ", amountDue=" + amountDue + ", fee=" + fee + ", datetime=" + datetime + ", title='" + title + '\'' + ", sender='" + sender + '\'' + ", recipient='" + recipient + '\'' + ", recipientType=" + recipientType + ", message='" + message + '\'' + ", comment='" + comment + '\'' + ", codepro=" + codepro + ", protectionCode='" + protectionCode + '\'' + ", expires=" + expires + ", answerDatetime=" + answerDatetime + ", label='" + label + '\'' + ", details='" + details + '\'' + ", repeatable=" + repeatable + ", paymentParameters=" + paymentParameters + ", favorite=" + favorite + ", type=" + type + ", digitalGoods=" + digitalGoods + ", categories=" + categories + ", spendingCategories=" + spendingCategories + ", showcaseFormat=" + showcaseFormat + ", availableOperations=" + availableOperations + ", amountCurrency=" + amountCurrency + ", exchangeAmount=" + exchangeAmount + ", exchangeAmountCurrency=" + exchangeAmountCurrency + '}'; } /** * Type of operation. */ public enum Type implements Enums.WithCode<Type> { /** * Payment to a shop. */ @SerializedName("payment-shop") PAYMENT_SHOP("payment-shop"), /** * Outgoing transfer. */ @SerializedName("outgoing-transfer") OUTGOING_TRANSFER("outgoing-transfer"), /** * Incoming transfer. */ @SerializedName("incoming-transfer") INCOMING_TRANSFER("incoming-transfer"), /** * Incoming transfer with protection code. */ @SerializedName("incoming-transfer-protected") INCOMING_TRANSFER_PROTECTED("incoming-transfer-protected"), /** * Deposition. */ @SerializedName("deposition") DEPOSITION("deposition"); public final String code; Type(String code) { this.code = code; } @Override public String getCode() { return code; } @Override public Type[] getValues() { return values(); } } /** * Direction of operation. */ public enum Direction implements Enums.WithCode<Direction> { /** * Incoming. */ @SerializedName("in") INCOMING("in"), /** * Outgoing. */ @SerializedName("out") OUTGOING("out"); public final String code; Direction(String code) { this.code = code; } @Override public String getCode() { return code; } @Override public Direction[] getValues() { return values(); } } /** * Types of available operations. * * These elements are for internal use only. * Use them carefully as they can be removed or changed. */ public enum AvailableOperation implements Enums.WithCode<AvailableOperation> { @SerializedName("turn-on-reminder") TURN_ON_REMINDER("turn-on-reminder"), @SerializedName("turn-on-autopayment") TURN_ON_AUTOPAYMENT("turn-on-autopayment"), @SerializedName("repeat") REPEAT("repeat"), @SerializedName("add-to-favourites") ADD_TO_FAVOURITES("add-to-favourites"); public final String code; AvailableOperation(String code) { this.code = code; } @Override public String getCode() { return code; } @Override public AvailableOperation[] getValues() { return values(); } } /** * Creates {@link com.yandex.money.api.model.Operation}. */ public static class Builder { String operationId; OperationStatus status; String patternId; Direction direction; BigDecimal amount = BigDecimal.ZERO; BigDecimal amountDue; BigDecimal fee; DateTime datetime = DateTime.now(); String title; String sender; String recipient; PayeeIdentifierType recipientType; String message; String comment; Boolean codepro; String protectionCode; DateTime expires; DateTime answerDatetime; String label; String details; Boolean repeatable; Map<String, String> paymentParameters; Boolean favorite; Type type; DigitalGoods digitalGoods; List<Integer> categories; List<SpendingCategory> spendingCategories; ShowcaseReference.Format format; List<AvailableOperation> availableOperations; Currency amountCurrency; BigDecimal exchangeAmount; Currency exchangeAmountCurrency; public Builder setOperationId(String operationId) { this.operationId = operationId; return this; } public Builder setStatus(OperationStatus status) { this.status = status; return this; } public Builder setPatternId(String patternId) { this.patternId = patternId; return this; } public Builder setDirection(Direction direction) { this.direction = direction; return this; } public Builder setAmount(BigDecimal amount) { this.amount = amount; return this; } public Builder setAmountDue(BigDecimal amountDue) { this.amountDue = amountDue; return this; } public Builder setFee(BigDecimal fee) { this.fee = fee; return this; } public Builder setDatetime(DateTime datetime) { this.datetime = datetime; return this; } public Builder setTitle(String title) { this.title = title; return this; } public Builder setSender(String sender) { this.sender = sender; return this; } public Builder setRecipient(String recipient) { this.recipient = recipient; return this; } public Builder setRecipientType(PayeeIdentifierType recipientType) { this.recipientType = recipientType; return this; } public Builder setMessage(String message) { this.message = message; return this; } public Builder setComment(String comment) { this.comment = comment; return this; } public Builder setCodepro(Boolean codepro) { this.codepro = codepro; return this; } public Builder setProtectionCode(String protectionCode) { this.protectionCode = protectionCode; return this; } public Builder setExpires(DateTime expires) { this.expires = expires; return this; } public Builder setAnswerDatetime(DateTime answerDatetime) { this.answerDatetime = answerDatetime; return this; } public Builder setLabel(String label) { this.label = label; return this; } public Builder setDetails(String details) { this.details = details; return this; } public Builder setRepeatable(Boolean repeatable) { this.repeatable = repeatable; return this; } public Builder setPaymentParameters(Map<String, String> paymentParameters) { this.paymentParameters = paymentParameters; return this; } public Builder setFavorite(Boolean favorite) { this.favorite = favorite; return this; } public Builder setType(Type type) { this.type = type; return this; } public Builder setDigitalGoods(DigitalGoods digitalGoods) { this.digitalGoods = digitalGoods; return this; } public Builder setCategories(List<Integer> categories) { this.categories = categories; return this; } public void setSpendingCategories(List<SpendingCategory> spendingCategories) { this.spendingCategories = spendingCategories; } public Builder setFormat(ShowcaseReference.Format format) { this.format = format; return this; } public Builder setAvailableOperations(List<AvailableOperation> operations) { this.availableOperations = operations; return this; } public Builder setAmountCurrency(Currency amountCurrency) { this.amountCurrency = amountCurrency; return this; } public Builder setExchangeAmount(BigDecimal exchangeAmount) { this.exchangeAmount = exchangeAmount; return this; } public Builder setExchangeAmountCurrency(Currency exchangeAmountCurrency) { this.exchangeAmountCurrency = exchangeAmountCurrency; return this; } public Operation create() { return new Operation(this); } } }
package cubicchunks.lighting; import static cubicchunks.util.Coords.blockToCube; import static cubicchunks.util.Coords.cubeToMaxBlock; import static cubicchunks.util.Coords.cubeToMinBlock; import static cubicchunks.util.Coords.localToBlock; import cubicchunks.server.PlayerCubeMap; import cubicchunks.util.Coords; import cubicchunks.util.CubePos; import cubicchunks.util.FastCubeBlockAccess; import cubicchunks.world.ICubeProvider; import cubicchunks.world.ICubicWorld; import cubicchunks.world.column.IColumn; import cubicchunks.world.cube.Cube; import gnu.trove.iterator.TIntIterator; import gnu.trove.set.TIntSet; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.WorldServer; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; //TODO: extract interfaces when it's done @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class LightingManager { public static final int MAX_CLIENT_LIGHT_SCAN_DEPTH = 64; @Nonnull private ICubicWorld world; @Nonnull private LightPropagator lightPropagator = new LightPropagator(); @Nonnull private final List<IHeightChangeListener> heightUpdateListeners = new ArrayList<>(); @Nullable private LightUpdateTracker tracker; public LightingManager(ICubicWorld world) { this.world = world; } @Nullable private LightUpdateTracker getTracker() { if (tracker == null) { if (!world.isRemote()) { tracker = new LightUpdateTracker((PlayerCubeMap) ((WorldServer) world).getPlayerChunkMap()); } } return tracker; } /** * Registers height change listener, that receives all height changes after initial lighting is done */ public void registerHeightChangeListener(IHeightChangeListener listener) { heightUpdateListeners.add(listener); } @Nullable public CubeLightUpdateInfo createCubeLightUpdateInfo(Cube cube) { if (!cube.getCubicWorld().getProvider().hasSkyLight()) { return null; } return new CubeLightUpdateInfo(cube); } private void columnSkylightUpdate(UpdateType type, IColumn column, int localX, int minY, int maxY, int localZ) { if (!world.getProvider().hasSkyLight()) { return; } int blockX = Coords.localToBlock(column.getX(), localX); int blockZ = Coords.localToBlock(column.getZ(), localZ); if (type == UpdateType.IMMEDIATE) { TIntSet toDiffuse = SkyLightUpdateCubeSelector.getCubesY(column, localX, localZ, minY, maxY); TIntIterator it = toDiffuse.iterator(); while (it.hasNext()) { int cubeY = it.next(); boolean success = updateDiffuseLight(column.getCube(cubeY), localX, localZ, minY, maxY); if (!success) { markCubeBlockColumnForUpdate(column.getCube(cubeY), blockX, blockZ); } } } else { assert type == UpdateType.QUEUED; TIntSet toDiffuse = SkyLightUpdateCubeSelector.getCubesY(column, localX, localZ, minY, maxY); TIntIterator it = toDiffuse.iterator(); while (it.hasNext()) { int cubeY = it.next(); markCubeBlockColumnForUpdate(column.getCube(cubeY), blockX, blockZ); } } } private boolean updateDiffuseLight(Cube cube, int localX, int localZ, int minY, int maxY) { int minCubeY = cube.getCoords().getMinBlockY(); int maxCubeY = cube.getCoords().getMaxBlockY(); int minInCubeY = MathHelper.clamp(minY, minCubeY, maxCubeY); int maxInCubeY = MathHelper.clamp(maxY, minCubeY, maxCubeY); if (minInCubeY > maxInCubeY) { return true; } int blockX = localToBlock(cube.getX(), localX); int blockZ = localToBlock(cube.getZ(), localZ); return this.relightMultiBlock( new BlockPos(blockX, minInCubeY, blockZ), new BlockPos(blockX, maxInCubeY, blockZ), EnumSkyBlock.SKY, world::notifyLightSet); } public void doOnBlockSetLightUpdates(IColumn column, int localX, int oldHeight, int changeY, int localZ) { this.columnSkylightUpdate(UpdateType.IMMEDIATE, column, localX, Math.min(oldHeight, changeY), Math.max(oldHeight, changeY), localZ); } //TODO: make it private public void markCubeBlockColumnForUpdate(Cube cube, int blockX, int blockZ) { CubeLightUpdateInfo data = cube.getCubeLightUpdateInfo(); if (data != null) { data.markBlockColumnForUpdate(Coords.blockToLocal(blockX), Coords.blockToLocal(blockZ)); } } public void onHeightMapUpdate(IColumn IColumn, int localX, int localZ, int oldHeight, int newHeight) { int minCubeY = blockToCube(Math.min(oldHeight, newHeight)); int maxCubeY = blockToCube(Math.max(oldHeight, newHeight)); IColumn.getLoadedCubes().stream().filter(cube -> cube.getY() >= minCubeY && cube.getY() <= maxCubeY).forEach(cube -> { markCubeBlockColumnForUpdate(cube, localX, localZ); }); } /** * Updates light for given block region. * <p> * * @param startPos the minimum block coordinates (inclusive) * @param endPos the maximum block coordinates (inclusive) * @param type the light type to update * * @return true if update was successful, false if it failed. If the method returns false, no light values are * changed. */ boolean relightMultiBlock(BlockPos startPos, BlockPos endPos, EnumSkyBlock type, Consumer<BlockPos> notify) { // TODO: optimize if needed // TODO: Figure out why it crashes with value 17 final int LOAD_RADIUS = 17; BlockPos midPos = Coords.midPos(startPos, endPos); BlockPos minLoad = startPos.add(-LOAD_RADIUS, -LOAD_RADIUS, -LOAD_RADIUS); BlockPos maxLoad = endPos.add(LOAD_RADIUS, LOAD_RADIUS, LOAD_RADIUS); ILightBlockAccess blocks = FastCubeBlockAccess.forBlockRegion(world.getCubeCache(), minLoad, maxLoad); this.lightPropagator.propagateLight(midPos, BlockPos.getAllInBox(startPos, endPos), blocks, type, notify); return true; } public void sendHeightMapUpdate(BlockPos pos) { int size = heightUpdateListeners.size(); for (int i = 0; i < size; i++) { heightUpdateListeners.get(i).heightUpdated(pos.getX(), pos.getZ()); } } private enum UpdateType { IMMEDIATE, QUEUED } //this will be interface public static class CubeLightUpdateInfo { private final Cube cube; private final boolean[] toUpdateColumns = new boolean[Cube.SIZE * Cube.SIZE]; private boolean hasUpdates; public CubeLightUpdateInfo(Cube cube) { this.cube = cube; } void markBlockColumnForUpdate(int localX, int localZ) { toUpdateColumns[index(localX, localZ)] = true; hasUpdates = true; } public void tick() { LightUpdateTracker tracker = cube.getCubicWorld().getLightingManager().getTracker(); for (EnumFacing dir : EnumFacing.values()) { if (cube.edgeNeedSkyLightUpdate[dir.ordinal()]) { ICubeProvider cache = cube.getCubicWorld().getCubeCache(); CubePos cpos = cube.getCoords(); Cube loadedCube = cache.getLoadedCube( cpos.getX() + dir.getFrontOffsetX(), cpos.getY() + dir.getFrontOffsetY(), cpos.getZ() + dir.getFrontOffsetZ()); if (loadedCube == null) continue; LightingManager manager = cube.getCubicWorld().getLightingManager(); int fromBlockX = cpos.getMinBlockX(); int fromBlockY = cpos.getMinBlockY(); int fromBlockZ = cpos.getMinBlockZ(); int toBlockX = cpos.getMaxBlockX(); int toBlockY = cpos.getMaxBlockY(); int toBlockZ = cpos.getMaxBlockZ(); boolean extendBack = loadedCube.edgeNeedSkyLightUpdate[dir.getOpposite().ordinal()]; switch (dir) { case DOWN: fromBlockY = fromBlockY - 1; toBlockY = extendBack ? fromBlockY + 1 : fromBlockY; break; case UP: toBlockY = toBlockY + 1; fromBlockY = extendBack ? toBlockY - 1 : toBlockY; break; case NORTH: fromBlockZ = fromBlockZ - 1; toBlockZ = extendBack ? fromBlockZ + 1 : fromBlockZ; break; case SOUTH: toBlockZ = toBlockZ + 1; fromBlockZ = extendBack ? toBlockZ - 1 : toBlockZ; break; case WEST: fromBlockX = fromBlockX - 1; toBlockX = extendBack ? fromBlockX + 1 : fromBlockX; break; case EAST: toBlockX = toBlockX + 1; fromBlockX = extendBack ? toBlockX - 1 : toBlockX; break; } manager.relightMultiBlock( new BlockPos(fromBlockX, fromBlockY, fromBlockZ), new BlockPos(toBlockX, toBlockY, toBlockZ), EnumSkyBlock.SKY, pos -> { cube.getCubicWorld().notifyLightSet(pos); if (tracker != null) { tracker.onUpdate(pos); } }); cube.edgeNeedSkyLightUpdate[dir.ordinal()] = false; loadedCube.edgeNeedSkyLightUpdate[dir.getOpposite().ordinal()] = false; } } if (!this.hasUpdates) { return; } for (int localX = 0; localX < Cube.SIZE; localX++) { for (int localZ = 0; localZ < Cube.SIZE; localZ++) { if (!toUpdateColumns[index(localX, localZ)]) { continue; } cube.getCubicWorld().getLightingManager().relightMultiBlock( new BlockPos(localToBlock(cube.getX(), localX), cubeToMinBlock(cube.getY()), localToBlock(cube.getZ(), localZ)), new BlockPos(localToBlock(cube.getX(), localX), cubeToMaxBlock(cube.getY()), localToBlock(cube.getZ(), localZ)), EnumSkyBlock.SKY, pos -> { cube.getCubicWorld().notifyLightSet(pos); if (tracker != null) { tracker.onUpdate(pos); } } ); toUpdateColumns[index(localX, localZ)] = false; } } this.hasUpdates = false; } private int index(int x, int z) { return x << 4 | z; } public boolean hasUpdates() { return hasUpdates; } public void clear() { for (int localX = 0; localX < Cube.SIZE; localX++) { for (int localZ = 0; localZ < Cube.SIZE; localZ++) { toUpdateColumns[index(localX, localZ)] = false; } } hasUpdates = false; } } public interface IHeightChangeListener { void heightUpdated(int blockX, int blockZ); } }
package de.bit3.jsass.context; import com.sun.jna.Memory; import com.sun.jna.Pointer; import de.bit3.jsass.importer.Importer; import de.bit3.jsass.Options; import de.bit3.jsass.OutputStyle; import de.bit3.jsass.function.FunctionCallbackFactory; import sass.SassLibrary; import java.io.File; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.List; public class ContextFactory { private final SassLibrary SASS; public ContextFactory(SassLibrary SASS) { this.SASS = SASS; } public SassLibrary.Sass_File_Context create(FileContext context) { File inputPath = context.getInputPath(); File outputPath = context.getOutputPath(); Options options = context.getOptions(); // create context SassLibrary.Sass_File_Context fileContext = SASS.sass_make_file_context(inputPath.getAbsolutePath()); // configure context SassLibrary.Sass_Options libsassOptions = SASS.sass_file_context_get_options(fileContext); configure(inputPath, outputPath, libsassOptions, options); return fileContext; } public SassLibrary.Sass_Data_Context create(StringContext context) { String string = context.getString(); Charset charset = context.getCharset(); File inputPath = context.getInputPath(); File outputPath = context.getOutputPath(); Options options = context.getOptions(); byte[] bytes = string.getBytes(charset); Memory memory = new Memory(bytes.length + 1); memory.write(0, bytes, 0, bytes.length); memory.setByte(bytes.length, (byte) 0); ByteBuffer buffer = memory.getByteBuffer(0, memory.size()); // create context SassLibrary.Sass_Data_Context dataContext = SASS.sass_make_data_context(buffer); // configure context SassLibrary.Sass_Options libsassOptions = SASS.sass_data_context_get_options(dataContext); configure(inputPath, outputPath, libsassOptions, options); return dataContext; } /** * Configure sass. * * @param libsassOptions The libsass options. * @param javaOptions The java options. */ private void configure(File inputPath, File outputPath, SassLibrary.Sass_Options libsassOptions, Options javaOptions) { int precision = javaOptions.getPrecision(); int outputStyle = mapOutputStyle(javaOptions.getOutputStyle()); byte sourceComments = createBooleanByte(javaOptions.isSourceComments()); byte sourceMapEmbed = createBooleanByte(javaOptions.isSourceMapEmbed()); byte sourceMapContents = createBooleanByte(javaOptions.isSourceMapContents()); byte omitSourceMapUrl = createBooleanByte(javaOptions.isOmitSourceMapUrl()); byte isIndentedSyntaxSrc = createBooleanByte(javaOptions.isIndentedSyntaxSrc()); String inputPathString = null == inputPath ? "" : inputPath.getAbsolutePath(); String outputPathString = null == outputPath ? "" : outputPath.getAbsolutePath(); String imagePath = javaOptions.getImageUrl(); String includePaths = joinFilePaths(javaOptions.getIncludePaths()); String sourceMapFile = null == javaOptions.getSourceMapFile() ? "" : javaOptions.getSourceMapFile().getAbsolutePath(); SassLibrary.Sass_C_Function_List functions = createFunctions(javaOptions.getFunctionProviders()); SassLibrary.Sass_C_Import_Callback importer = createImporter(javaOptions.getImporters()); SASS.sass_option_set_precision(libsassOptions, precision); SASS.sass_option_set_output_style(libsassOptions, outputStyle); SASS.sass_option_set_source_comments(libsassOptions, sourceComments); SASS.sass_option_set_source_map_embed(libsassOptions, sourceMapEmbed); SASS.sass_option_set_source_map_contents(libsassOptions, sourceMapContents); SASS.sass_option_set_omit_source_map_url(libsassOptions, omitSourceMapUrl); SASS.sass_option_set_is_indented_syntax_src(libsassOptions, isIndentedSyntaxSrc); SASS.sass_option_set_input_path(libsassOptions, inputPathString); SASS.sass_option_set_output_path(libsassOptions, outputPathString); SASS.sass_option_set_image_path(libsassOptions, imagePath); SASS.sass_option_set_include_path(libsassOptions, includePaths); SASS.sass_option_set_source_map_file(libsassOptions, sourceMapFile); SASS.sass_option_set_c_functions(libsassOptions, functions); SASS.sass_option_set_importer(libsassOptions, importer); } /** * Map java output style to native libsass output style. * * @param outputStyle The java output style. * @return The native libsass output style. */ private int mapOutputStyle(OutputStyle outputStyle) { int result = SassLibrary.Sass_Output_Style.SASS_STYLE_NESTED; switch (outputStyle) { case EXPANDED: result = SassLibrary.Sass_Output_Style.SASS_STYLE_EXPANDED; break; case COMPACT: result = SassLibrary.Sass_Output_Style.SASS_STYLE_COMPACT; break; case COMPRESSED: result = SassLibrary.Sass_Output_Style.SASS_STYLE_COMPRESSED; break; } return result; } /** * Create a string pointer from a file list, using the absolute paths and OS dependent separator char. * * @param list The file list. * @return Pointer to list of absolute paths. */ private String joinFilePaths(List<File> list) { if (null == list || list.isEmpty()) { return ""; } String separator = File.pathSeparator; StringBuilder string = new StringBuilder(); for (File file : list) { string.append(separator).append(file.getAbsolutePath()); } return string.substring(1); } private SassLibrary.Sass_C_Function_List createFunctions(List<?> functionProviders) { FunctionCallbackFactory functionCallbackFactory = new FunctionCallbackFactory(SASS); List<SassLibrary.Sass_C_Function_Callback> callbacks = functionCallbackFactory.compileFunctions(functionProviders); return functionCallbackFactory.toSassCFunctionList(callbacks); } private SassLibrary.Sass_C_Import_Callback createImporter(List<?> importers) { return null; // TODO } /** * Create native byte boolean. * * @param bool The boolean value. * @return <em>1</em> for <em>true</em> input, otherwise <em>0</em>. */ private byte createBooleanByte(boolean bool) { return bool ? (byte) 1 : 0; } }
package aQute.lib.xmldtoparser; import java.io.File; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import aQute.lib.converter.Converter; /** * Parse an XML file based on a DTO as schema */ public class DomDTOParser { final static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); /** * parse the given XML file based on the type as the schema. Attributes and * elements are mapped to fields in an object of this type. If the field is * a collection or a DTO type, the parse will be recursive. * * @param type the type acting as scheme * @param doc the file * @return a DTO of type */ public static <T> T parse(Class<T> type, File doc) throws Exception { return parse(type, dbf.newDocumentBuilder() .parse(doc)); } /** * parse the given XML file based on the type as the schema. Attributes and * elements are mapped to fields in an object of this type. If the field is * a collection or a DTO type, the parse will be recursive. * * @param type the type acting as scheme * @param doc the file * @return a DTO of type */ public static <T> T parse(Class<T> type, InputStream doc) throws Exception { return parse(type, dbf.newDocumentBuilder() .parse(doc)); } private static <T> T parse(Class<T> type, Node node) throws Exception { T instance = type.newInstance(); NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Attr attribute = (Attr) attributes.item(i); get(instance, attribute); } } NodeList children = node.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); get(instance, child); } return instance; } @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> void get(T instance, Node node) throws Exception { if (node instanceof Comment) return; if (node instanceof Text) { String text = node.getTextContent() .trim(); if (!text.isEmpty()) { Field field = getField(instance.getClass(), "_content"); if (field == null) return; field.set(instance, Converter.cnv(field.getGenericType(), text)); return; } } String name = toSimpleName(node.getNodeName()); Field field = getField(instance.getClass(), name); if (field == null) { // Store the content in an __extra variable // if exists for diagnostics try { field = getField(instance.getClass(), "__extra"); if (field != null && field.getType() == Map.class) { Map map = (Map) field.get(instance); if (map == null) { map = new HashMap(); field.set(instance, map); } map.put(name, node.getTextContent()); } } catch (Exception e) { // ignore, best effort } return; } if (isCollection(field.getType())) { ParameterizedType subType = (ParameterizedType) field.getGenericType(); Type collectionType = subType.getActualTypeArguments()[0]; Object member = parse((Class<T>) collectionType, node); Collection<Object> collection = (Collection<Object>) field.get(instance); if (collection == null) { collection = (Collection<Object>) Converter.cnv(field.getGenericType(), new Object[0]); field.set(instance, collection); } collection.add(member); } else if (isSimple(field.getType())) { String value = node.getTextContent(); Object convertedValue = Converter.cnv(field.getType(), value); field.set(instance, convertedValue); } else if (field.getType() .isEnum()) { String value = node.getTextContent(); Class<?> en = field.getType(); for (Field constant : en.getFields()) { String nm = constant.getName(); if (nm.equalsIgnoreCase(value) || (value.equals(getName(constant)))) { field.set(instance, constant.get(null)); return; } } } else { field.set(instance, parse(field.getType(), node)); } } private static String getName(Field field) { XmlAttribute xmlAttribute = field.getAnnotation(XmlAttribute.class); if (xmlAttribute != null) return xmlAttribute.name(); return null; } private static String toSimpleName(String nodeName) { int n = nodeName.indexOf(':'); return nodeName.substring(n + 1); } private static boolean isSimple(Class<?> class1) { return class1.isPrimitive() || Number.class.isAssignableFrom(class1) || class1 == Boolean.class || class1 == String.class; } private static boolean isCollection(Class<?> class1) { return Collection.class.isAssignableFrom(class1); } private static Field getField(Class<? extends Object> class1, String name) throws Exception { try { return class1.getField(name); } catch (Exception e) { for (Field field : class1.getFields()) { if (name.equals(getName(field))) { return field; } } } return null; } }
package de.onyxbits.raccoon.gui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import com.akdeniz.googleplaycrawler.GooglePlay.DocV2; import de.onyxbits.raccoon.io.Archive; import de.onyxbits.raccoon.io.FetchListener; /** * Display download progress and give the user a chance to cancel. * * @author patrick * */ public class DownloadView extends JPanel implements ActionListener, FetchListener { private static final long serialVersionUID = 1L; private DownloadWorker worker; private JProgressBar progress; private JButton cancel; private DocV2 doc; private Archive archive; private DownloadView(Archive archive, DocV2 doc) { this.doc = doc; this.archive = archive; this.cancel = new JButton("Cancel"); this.progress = new JProgressBar(0, 100); this.progress.setString("Waiting"); this.progress.setStringPainted(true); String pn = doc.getBackendDocid(); int vc = doc.getDetails().getAppDetails().getVersionCode(); String title = doc.getTitle(); File dest = archive.fileUnder(pn, vc); worker = new DownloadWorker(doc, archive, null); String boiler = "<html><h2>" + title + "</h2><code>" + dest.getAbsolutePath() + "</code></html>"; JPanel container = new JPanel(); container.setOpaque(false); container.add(progress); container.add(cancel); JEditorPane info = new JEditorPane("text/html", boiler); info.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); info.setEditable(false); info.setOpaque(false); add(info); add(container); } public static DownloadView create(Archive archive, DocV2 doc) { DownloadView ret = new DownloadView(archive, doc); ret.cancel.addActionListener(ret); ret.setLayout(new BoxLayout(ret, BoxLayout.Y_AXIS)); ret.worker.addFetchListener(ret); return ret; } public boolean isDownloaded() { String pn = doc.getBackendDocid(); int vc = doc.getDetails().getAppDetails().getVersionCode(); return archive.fileUnder(pn, vc).exists(); } public void addFetchListener(FetchListener listener) { worker.addFetchListener(listener); } public void startWorker() { worker.execute(); } public void stopWorker() { worker.cancel(true); } public boolean isDownloading() { return !worker.isDone(); } public void actionPerformed(ActionEvent event) { if (event.getSource() == cancel) { worker.cancel(true); } } public boolean onChunk(Object src, long numBytes) { float percent = (float) numBytes / (float) worker.totalBytes; int tmp = (int) (100f * percent); progress.setValue(tmp); progress.setString(tmp + "%"); return false; } public void onComplete(Object src) { progress.setString("Complete"); cancel.setEnabled(false); } public void onFailure(Object src, Exception e) { if (e instanceof IndexOutOfBoundsException) { progress.setString("Not paid for"); } else { progress.setString("Error!"); } cancel.setEnabled(false); } public void onAborted(Object src) { progress.setString("Cancelled"); cancel.setEnabled(false); } }
package editor.gui.inventory; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dialog; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.StringJoiner; import java.util.TreeMap; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.WindowConstants; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import editor.collection.Inventory; import editor.database.FormatConstraints; import editor.database.attributes.CombatStat; import editor.database.attributes.Expansion; import editor.database.attributes.Legality; import editor.database.attributes.ManaCost; import editor.database.attributes.ManaType; import editor.database.attributes.Rarity; import editor.database.card.Card; import editor.database.card.CardLayout; import editor.database.card.FlipCard; import editor.database.card.MeldCard; import editor.database.card.SingleCard; import editor.database.card.SplitCard; import editor.database.card.TransformCard; import editor.database.version.DatabaseVersion; import editor.filter.leaf.options.multi.CardTypeFilter; import editor.filter.leaf.options.multi.SubtypeFilter; import editor.filter.leaf.options.multi.SupertypeFilter; import editor.gui.MainFrame; import editor.gui.settings.SettingsDialog; /** * Worker that loads the JSON inventory file into memory and displays progress in a * popup dialog. * * @author Alec Roelke */ public class InventoryLoader extends SwingWorker<Inventory, String> { private static final DatabaseVersion VER_5_0_0 = new DatabaseVersion(5, 0, 0); /** * Load the inventory into memory from disk. Display a dialog indicating showing progress * and allowing cancellation. * * @param owner frame for setting the location of the dialog * @param file file to load the inventory from */ public static Inventory loadInventory(Frame owner, File file) { JDialog dialog = new JDialog(owner, "Loading Inventory", Dialog.ModalityType.APPLICATION_MODAL); dialog.setResizable(false); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); final int BORDER = 10; // Content panel Box contentPanel = new Box(BoxLayout.Y_AXIS); contentPanel.setBorder(BorderFactory.createEmptyBorder(BORDER, BORDER, BORDER, BORDER)); dialog.setContentPane(contentPanel); // Stage progress label JLabel progressLabel = new JLabel("Loading inventory..."); progressLabel.setAlignmentX(Component.LEFT_ALIGNMENT); contentPanel.add(progressLabel); contentPanel.add(Box.createVerticalStrut(2)); // Overall progress bar JProgressBar progressBar = new JProgressBar(); progressBar.setIndeterminate(true); progressBar.setAlignmentX(Component.LEFT_ALIGNMENT); contentPanel.add(progressBar); contentPanel.add(Box.createVerticalStrut(2)); // History text area JTextArea progressArea = new JTextArea("", 6, 40); progressArea.setEditable(false); JScrollPane progressPane = new JScrollPane(progressArea); progressPane.setAlignmentX(Component.LEFT_ALIGNMENT); contentPanel.add(progressPane); contentPanel.add(Box.createVerticalStrut(BORDER)); InventoryLoader loader = new InventoryLoader(file, (c) -> { progressLabel.setText(c); progressArea.append(c + "\n"); }, () -> { dialog.setVisible(false); dialog.dispose(); }); loader.addPropertyChangeListener((e) -> { if ("progress".equals(e.getPropertyName())) { int p = (Integer)e.getNewValue(); progressBar.setIndeterminate(p < 0); progressBar.setValue(p); } }); // Cancel button JPanel cancelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener((e) -> loader.cancel(false)); cancelPanel.setAlignmentX(Component.LEFT_ALIGNMENT); cancelPanel.add(cancelButton); contentPanel.add(cancelPanel); dialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { loader.cancel(false); } }); dialog.getRootPane().registerKeyboardAction((e) -> { loader.cancel(false); dialog.setVisible(false); dialog.dispose(); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); dialog.pack(); loader.execute(); dialog.setLocationRelativeTo(owner); dialog.setVisible(true); Inventory result = new Inventory(); try { result = loader.get(); } catch (InterruptedException | ExecutionException e) { JOptionPane.showMessageDialog(owner, "Error loading inventory: " + e.getCause().getMessage() + ".", "Error", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (CancellationException e) {} if (SettingsDialog.settings().inventory.warn && !loader.warnings().isEmpty()) { SwingUtilities.invokeLater(() -> { StringJoiner join = new StringJoiner("<li>", "<html>", "</ul></html>"); join.add("Errors ocurred while loading the following card(s):<ul style=\"margin-top:0;margin-left:20pt\">"); for (String failure : loader.warnings()) join.add(failure); JPanel warningPanel = new JPanel(new BorderLayout()); JLabel warningLabel = new JLabel(join.toString()); warningPanel.add(warningLabel, BorderLayout.CENTER); JCheckBox suppressBox = new JCheckBox("Don't show this warning in the future", !SettingsDialog.settings().inventory.warn); warningPanel.add(suppressBox, BorderLayout.SOUTH); JOptionPane.showMessageDialog(null, warningPanel, "Warning", JOptionPane.WARNING_MESSAGE); SettingsDialog.setShowInventoryWarnings(!suppressBox.isSelected()); }); } SettingsDialog.setInventoryWarnings(loader.warnings()); return result; } /** File to load from. */ private File file; /** List of errors that occur during loading. */ private List<String> errors; /** Action to perform on each chunk during process(). */ private Consumer<String> consumer; /** Function to perform when done loading. */ private Runnable finished; /** * Create a new InventoryWorker. * * @param f #File to load * @param c function to perform on each update * @param d function to perform when done loading */ private InventoryLoader(File f, Consumer<String> c, Runnable d) { super(); file = f; consumer = c; errors = new ArrayList<>(); finished = d; } /** * Convert a card that has a single face but incorrectly is loaded as a * multi-faced card into a card with a {@link CardLayout#NORMAL} layout. * * @param card card to convert * @return a {@link Card} with the same information as the input but a * {@link CardLayout#NORMAL} layout. */ private Card convertToNormal(Card card) { return new SingleCard( CardLayout.NORMAL, card.name().get(0), card.manaCost().get(0), card.colors(), card.colorIdentity(), card.supertypes(), card.types(), card.subtypes(), card.printedTypes().get(0), card.rarity(), card.expansion(), Optional.of(card.oracleText().get(0)), Optional.of(card.flavorText().get(0)), Optional.of(card.printedText().get(0)), card.artist().get(0), card.multiverseid().get(0), Optional.of(card.number().get(0)), card.power().get(0), card.toughness().get(0), Optional.of(card.loyalty().get(0).toString()), new TreeMap<>(card.rulings()), card.legality(), card.commandFormats() ); } @Override protected Inventory doInBackground() throws Exception { final DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); publish("Opening " + file.getName() + "..."); var cards = new ArrayList<Card>(); var faces = new HashMap<Card, List<String>>(); var melds = new HashMap<Card, List<String>>(); var expansions = new HashSet<Expansion>(); var blockNames = new HashSet<String>(); // Read the inventory file try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"))) { publish("Parsing " + file.getName() + "..."); JsonObject root = new JsonParser().parse(reader).getAsJsonObject(); DatabaseVersion version = root.has("meta") ? new DatabaseVersion(root.get("meta").getAsJsonObject().get("version").getAsString()) : new DatabaseVersion(0, 0, 0); // Anything less than 5.0.0 will do for pre-5.0.0 databases var entries = (version.compareTo(VER_5_0_0) < 0 ? root : root.get("data").getAsJsonObject()).entrySet(); int numCards = 0; if (version.compareTo(VER_5_0_0) < 0) { for (var setNode : entries) for (JsonElement card : setNode.getValue().getAsJsonObject().get("cards").getAsJsonArray()) if (card.getAsJsonObject().has("multiverseId")) numCards++; } else { for (var setNode : entries) for (JsonElement card : setNode.getValue().getAsJsonObject().get("cards").getAsJsonArray()) if (card.getAsJsonObject().get("identifiers").getAsJsonObject().has("multiverseId")) numCards++; } var costs = new HashMap<String, ManaCost>(); var colorLists = new HashMap<String, List<ManaType>>(); var allSupertypes = new HashMap<String, String>(); // map of supertype onto string reference var supertypeSets = new HashMap<String, Set<String>>(); var allTypes = new HashMap<String, String>(); // map of type onto string reference var typeSets = new HashMap<String, Set<String>>(); var allSubtypes = new HashMap<String, String>(); // map of subtype onto string reference var printedTypes = new HashMap<String, String>(); // Map of type line onto string reference var artists = new HashMap<String, String>(); // Map of artist name onto string reference var formats = new HashMap<>(FormatConstraints.FORMAT_NAMES.stream().collect(Collectors.toMap(Function.identity(), Function.identity()))); var stats = new HashMap<String, CombatStat>(); publish("Reading cards from " + file.getName() + "..."); setProgress(0); for (var setNode : entries) { if (isCancelled()) { expansions.clear(); blockNames.clear(); allSupertypes.clear(); allTypes.clear(); allSubtypes.clear(); formats.clear(); cards.clear(); return new Inventory(); } // Create the new Expansion JsonObject setProperties = setNode.getValue().getAsJsonObject(); JsonArray setCards = setProperties.get("cards").getAsJsonArray(); Expansion set = new Expansion( setProperties.get("name").getAsString(), Optional.ofNullable(setProperties.get("block")).map(JsonElement::getAsString).orElse("<No Block>"), setProperties.get("code").getAsString(), setCards.size(), LocalDate.parse(setProperties.get("releaseDate").getAsString(), Expansion.DATE_FORMATTER) ); expansions.add(set); blockNames.add(set.block); publish("Loading cards from " + set + "..."); for (JsonElement cardElement : setCards) { // Create the new card for the expansion JsonObject card = cardElement.getAsJsonObject(); // Card's multiverseid. Skip cards that aren't in gatherer int multiverseid = Optional.ofNullable(version.compareTo(VER_5_0_0) < 0 ? card.get("multiverseId") : card.get("identifiers").getAsJsonObject().get("multiverseId")).map(JsonElement::getAsInt).orElse(-1); if (multiverseid < 0) continue; // Card's name String name = card.get(card.has("faceName") ? "faceName" : "name").getAsString(); // If the card is a token, skip it CardLayout layout; try { layout = CardLayout.valueOf(card.get("layout").getAsString().toUpperCase().replaceAll("[^A-Z]", "_")); } catch (IllegalArgumentException e) { errors.add(name + " (" + set + "): " + e.getMessage()); continue; } // Mana Cost ManaCost cost; String costStr = card.has("manaCost") ? card.get("manaCost").getAsString() : ""; if (costs.containsKey(costStr)) cost = costs.get(costStr); else { cost = ManaCost.parseManaCost(costStr); costs.put(costStr, cost); } // Colors and color identity List<ManaType> colors = new ArrayList<>(); List<ManaType> identity = new ArrayList<>(); String colorsStr = card.get("colors").getAsJsonArray().toString(); String identityStr = card.get("colorIdentity").getAsJsonArray().toString(); if (colorLists.containsKey(colorsStr)) colors = colorLists.get(colorsStr); else { for (JsonElement e : card.get("colors").getAsJsonArray()) colors.add(ManaType.parseManaType(e.getAsString())); colors = Collections.unmodifiableList(colors); colorLists.put(colorsStr, colors); } if (colorLists.containsKey(identityStr)) identity = colorLists.get(identityStr); else { for (JsonElement e : card.get("colorIdentity").getAsJsonArray()) identity.add(ManaType.parseManaType(e.getAsString())); identity = Collections.unmodifiableList(identity); colorLists.put(identityStr, identity); } // Supertypes Set<String> supertypes; String supertypeStr = card.get("supertypes").getAsJsonArray().toString(); if (supertypeSets.containsKey(supertypeStr)) supertypes = supertypeSets.get(supertypeStr); else { supertypes = new HashSet<>(); for (JsonElement e : card.get("supertypes").getAsJsonArray()) { if (!allSupertypes.containsKey(e.getAsString())) allSupertypes.put(e.getAsString(), e.getAsString()); supertypes.add(allSupertypes.get(e.getAsString())); } supertypeSets.put(supertypeStr, supertypes); } // Types Set<String> types; String typeStr = card.get("types").getAsJsonArray().toString(); if (typeSets.containsKey(typeStr)) types = typeSets.get(typeStr); else { types = new HashSet<>(); for (JsonElement e : card.get("types").getAsJsonArray()) { if (!allTypes.containsKey(e.getAsString())) allTypes.put(e.getAsString(), e.getAsString()); types.add(allTypes.get(e.getAsString())); } typeSets.put(typeStr, types); } // Subtypes var subtypes = new HashSet<String>(); for (JsonElement e : card.get("subtypes").getAsJsonArray()) { if (!allSubtypes.containsKey(e.getAsString())) allSubtypes.put(e.getAsString(), e.getAsString()); subtypes.add(allSubtypes.get(e.getAsString())); } // Printed type line String printedType = card.has("originalType") ? card.get("originalType").getAsString() : ""; if (printedTypes.containsKey(printedType)) printedType = printedTypes.get(printedType); else printedTypes.put(printedType, printedType); // Artist String artist = card.has("artist") ? card.get("artist").getAsString() : ""; if (artists.containsKey(artist)) artist = artists.get(artist); else artists.put(artist, artist); // Power and toughness CombatStat power, toughness; String powerStr = card.has("power") ? card.get("power").getAsString() : ""; String toughStr = card.has("toughness") ? card.get("toughness").getAsString() : ""; if (stats.containsKey(powerStr)) power = stats.get(powerStr); else { power = new CombatStat(powerStr); stats.put(powerStr, power); } if (stats.containsKey(toughStr)) toughness = stats.get(toughStr); else { toughness = new CombatStat(toughStr); stats.put(toughStr, toughness); } // Rulings var rulings = new TreeMap<Date, List<String>>(); if (card.has("rulings")) { for (JsonElement l : card.get("rulings").getAsJsonArray()) { JsonObject o = l.getAsJsonObject(); String ruling = o.get("text").getAsString(); try { Date date = format.parse(o.get("date").getAsString()); if (!rulings.containsKey(date)) rulings.put(date, new ArrayList<>()); rulings.get(date).add(ruling); } catch (ParseException x) { errors.add(name + " (" + set + "): " + x.getMessage()); } } } var legality = new HashMap<String, Legality>(); for (var entry : card.get("legalities").getAsJsonObject().entrySet()) { if (!formats.containsKey(entry.getKey())) formats.put(entry.getKey(), entry.getKey()); legality.put(formats.get(entry.getKey()), Legality.parseLegality(entry.getValue().getAsString())); } // Formats the card can be commander in var commandFormats = !card.has("leadershipSkills") ? Collections.<String>emptyList() : card.get("leadershipSkills").getAsJsonObject().entrySet().stream() .filter((e) -> e.getValue().getAsBoolean()) .map(Map.Entry::getKey) .sorted() .collect(Collectors.toList()); Card c = new SingleCard( layout, name, cost, colors, identity, supertypes, types, subtypes, printedType, Rarity.parseRarity(card.get("rarity").getAsString()), set, Optional.ofNullable(card.get("text")).map(JsonElement::getAsString), Optional.ofNullable(card.get("flavorText")).map(JsonElement::getAsString), Optional.ofNullable(card.get("originalText")).map(JsonElement::getAsString), artist, multiverseid, Optional.ofNullable(card.get("number")).map(JsonElement::getAsString), power, toughness, Optional.ofNullable(card.get("loyalty")).map((e) -> e.isJsonNull() ? "X" : e.getAsString()), rulings, legality, commandFormats ); // Collect unexpected card values if (c.artist().stream().anyMatch(String::isEmpty)) errors.add(c.unifiedName() + " (" + c.expansion() + "): Missing artist!"); // Add to map of faces if the card has multiple faces if (layout.isMultiFaced) { if (version.compareTo(VER_5_0_0) < 0) { var names = new ArrayList<String>(); for (JsonElement e : card.get("names").getAsJsonArray()) names.add(e.getAsString()); faces.put(c, names); } else if (layout != CardLayout.MELD) faces.put(c, Arrays.asList(card.get("name").getAsString().split(Card.FACE_SEPARATOR))); else melds.put(c, Arrays.asList(card.get("name").getAsString().split(Card.FACE_SEPARATOR))); } cards.add(c); setProgress(cards.size()*100/numCards); } } publish("Processing multi-faced cards..."); var facesList = new ArrayList<>(faces.keySet()); while (!facesList.isEmpty()) { boolean error = false; Card face = facesList.remove(0); var otherFaces = new ArrayList<Card>(); if (version.compareTo(VER_5_0_0) < 0 || face.layout() != CardLayout.MELD) { var faceNames = faces.get(face); for (Card c : facesList) if (faceNames.contains(c.unifiedName()) && c.expansion().equals(face.expansion())) otherFaces.add(c); facesList.removeAll(otherFaces); otherFaces.add(face); otherFaces.sort(Comparator.comparingInt((a) -> faceNames.indexOf(a.unifiedName()))); } cards.removeAll(otherFaces); switch (face.layout()) { case SPLIT: case AFTERMATH: case ADVENTURE: if (otherFaces.size() < 2) { errors.add(face.toString() + " (" + face.expansion() + "): Can't find other face(s) for split card."); error = true; } else { for (Card f : otherFaces) { if (f.layout() != face.layout()) { errors.add(face.toString() + " (" + face.expansion() + "): Can't join non-split faces into a split card."); error = true; } } } if (!error) cards.add(new SplitCard(otherFaces)); else for (Card f : otherFaces) cards.add(convertToNormal(f)); break; case FLIP: if (otherFaces.size() < 2) { errors.add(face.toString() + " (" + face.expansion() + "): Can't find other side of flip card."); error = true; } else if (otherFaces.size() > 2) { errors.add(face.toString() + " (" + face.expansion() + "): Too many sides for flip card."); error = true; } else if (otherFaces.get(0).layout() != CardLayout.FLIP || otherFaces.get(1).layout() != CardLayout.FLIP) { errors.add(face.toString() + " (" + face.expansion() + "): Can't join non-flip faces into a flip card."); error = true; } if (!error) cards.add(new FlipCard(otherFaces.get(0), otherFaces.get(1))); else for (Card f : otherFaces) cards.add(convertToNormal(f)); break; case TRANSFORM: if (otherFaces.size() < 2) { errors.add(face.toString() + " (" + face.expansion() + "): Can't find other face of double-faced card."); error = true; } else if (otherFaces.size() > 2) { errors.add(face.toString() + " (" + face.expansion() + "): Too many faces for double-faced card."); error = true; } else if (otherFaces.get(0).layout() != CardLayout.TRANSFORM || otherFaces.get(1).layout() != CardLayout.TRANSFORM) { errors.add(face.toString() + " (" + face.expansion() + "): Can't join single-faced cards into double-faced cards."); error = true; } if (!error) cards.add(new TransformCard(otherFaces.get(0), otherFaces.get(1))); else for (Card f : otherFaces) cards.add(convertToNormal(f)); break; case MELD: if (version.compareTo(VER_5_0_0) < 0) { if (otherFaces.size() < 3) { errors.add(face.toString() + " (" + face.expansion() + "): Can't find some faces of meld card."); error = true; } else if (otherFaces.size() > 3) { errors.add(face.toString() + " (" + face.expansion() + "): Too many faces for meld card."); error = true; } else if (otherFaces.get(0).layout() != CardLayout.MELD || otherFaces.get(1).layout() != CardLayout.MELD || otherFaces.get(2).layout() != CardLayout.MELD) { errors.add(face.toString() + " (" + face.expansion() + "): Can't join single-faced cards into meld cards."); error = true; } if (!error) { cards.add(new MeldCard(otherFaces.get(0), otherFaces.get(2), otherFaces.get(1))); cards.add(new MeldCard(otherFaces.get(2), otherFaces.get(0), otherFaces.get(1))); } else for (Card f : otherFaces) cards.add(convertToNormal(f)); } else errors.add(face + " (" + face.expansion() + "): Wrong processing of meld card."); break; default: break; } } if (version.compareTo(VER_5_0_0) >= 0) { var meldBacks = melds.entrySet().stream().filter((e) -> e.getValue().size() == 1).map((e) -> e.getKey()).collect(Collectors.toList()); var meldFronts = new HashMap<>(melds.entrySet().stream().filter((e) -> e.getValue().size() > 1).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))); for (Card back : meldBacks) { var fronts = meldFronts.entrySet().stream().filter((e) -> e.getKey().expansion().equals(back.expansion()) && e.getValue().contains(back.unifiedName())).map((e) -> e.getKey()).collect(Collectors.toList()); if (fronts.size() < 2) errors.add(back + " (" + back.expansion() + "): Can't find some faces of meld card."); else if (fronts.size() == 2) { cards.add(new MeldCard(fronts.get(0), fronts.get(1), back)); cards.add(new MeldCard(fronts.get(1), fronts.get(0), back)); cards.remove(back); cards.removeAll(fronts); for (Card front : fronts) meldFronts.remove(front); } else errors.add(back + "( " + back.expansion() + "): Too many faces for meld card."); } for (Card front : meldFronts.keySet()) errors.add(front + "( " + front.expansion() + "): Couldn't pair with a back face."); } publish("Removing duplicate entries..."); var unique = new HashMap<Integer, Card>(); for (Card c : cards) if (!unique.containsKey(c.multiverseid().get(0))) unique.put(c.multiverseid().get(0), c); cards = new ArrayList<>(unique.values()); // Store the lists of expansion and block names and types and sort them alphabetically Expansion.expansions = expansions.stream().sorted().toArray(Expansion[]::new); Expansion.blocks = blockNames.stream().sorted().toArray(String[]::new); SupertypeFilter.supertypeList = allSupertypes.values().stream().sorted().toArray(String[]::new); CardTypeFilter.typeList = allTypes.values().stream().sorted().toArray(String[]::new); SubtypeFilter.subtypeList = allSubtypes.values().stream().sorted().toArray(String[]::new); var missingFormats = formats.values().stream().filter((f) -> !FormatConstraints.FORMAT_NAMES.contains(f)).sorted().collect(Collectors.toList()); if (!missingFormats.isEmpty()) errors.add("Could not find definitions for the following formats: " + missingFormats.stream().collect(Collectors.joining(", "))); } Inventory inventory = new Inventory(cards); if (Files.exists(Path.of(SettingsDialog.settings().inventory.tags))) { @SuppressWarnings("unchecked") var rawTags = (Map<Integer, Set<String>>)MainFrame.SERIALIZER.fromJson(String.join("\n", Files.readAllLines(Path.of(SettingsDialog.settings().inventory.tags))), new TypeToken<Map<Long, Set<String>>>() {}.getType()); Card.tags.clear(); Card.tags.putAll(rawTags.entrySet().stream().collect(Collectors.toMap((e) -> inventory.find(e.getKey()), Map.Entry::getValue))); } return inventory; } /** * {@inheritDoc} * Change the label in the dialog to match the stage this worker is in. */ @Override protected void process(List<String> chunks) { for (String chunk : chunks) consumer.accept(chunk); } @Override protected void done() { finished.run(); } /** * @return A list of warnings that occured while loading the inventory. */ public List<String> warnings() { return errors; } }
package edu.hm.hafner.analysis; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.InvalidPathException; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.input.ReaderInputStream; import org.apache.commons.lang3.ObjectUtils; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.google.errorprone.annotations.MustBeClosed; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Provides several useful helper methods to read the contents of a resource that is given by a {@link Reader}. * * @author Ullrich Hafner */ public abstract class ReaderFactory { private static final Function<String, String> IDENTITY = Function.identity(); private final @CheckForNull Charset charset; private final Function<String, String> lineMapper; /** * Creates a new factory to read a resource with a given charset. * * @param charset * the charset to use when reading the file */ public ReaderFactory(final @CheckForNull Charset charset) { this(charset, IDENTITY); } /** * Creates a new factory to read a resource with a given charset. * * @param charset * the charset to use when reading the file * @param lineMapper * provides a mapper to transform each of the resource lines */ public ReaderFactory(final @CheckForNull Charset charset, final Function<String, String> lineMapper) { this.charset = charset; this.lineMapper = lineMapper; } /** * Returns the name of the resource. * * @return the file name */ public abstract String getFileName(); /** * Creates a new {@link Reader} for the file. * * @return a reader */ @MustBeClosed public abstract Reader create(); /** * Provides the lines of the file as a {@link Stream} of strings. * * @return the file content as stream * @throws ParsingException * if the file could not be read */ @MustBeClosed @SuppressWarnings("MustBeClosedChecker") @SuppressFBWarnings("OS_OPEN_STREAM") public Stream<String> readStream() { BufferedReader reader = new BufferedReader(create()); Stream<String> stringStream = reader.lines().onClose(closeReader(reader)); if (hasLineMapper()) { return stringStream.map(lineMapper); } else { return stringStream; } } @SuppressWarnings("illegalcatch") private Runnable closeReader(final AutoCloseable closeable) { return () -> { try { closeable.close(); } catch (Exception e) { throw new RuntimeException(e); } }; } @SuppressWarnings("PMD.CompareObjectsWithEquals") @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "test stub") private boolean hasLineMapper() { return lineMapper != null && lineMapper != IDENTITY; } /** * Reads the whole file into a {@link String}. * * @return the file content as string * @throws ParsingException * if the file could not be read */ public String readString() { try (Stream<String> lines = readStream()) { return lines.collect(Collectors.joining("\n")); } } /** * Parses the whole file into a {@link Document}. * * @return the file content as document * @throws ParsingException * if the file could not be parsed */ public Document readDocument() { try (Reader reader = create()) { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); return docBuilder.parse(new InputSource(new ReaderInputStream(reader, getCharset()))); } catch (SAXException | IOException | InvalidPathException | ParserConfigurationException e) { throw new ParsingException(e); } } public Charset getCharset() { return ObjectUtils.defaultIfNull(charset, StandardCharsets.UTF_8); } }
package edu.ufl.cise.cnt5106c; import edu.ufl.cise.cnt5106c.messages.Bitfield; import edu.ufl.cise.cnt5106c.messages.Handshake; import edu.ufl.cise.cnt5106c.messages.Have; import edu.ufl.cise.cnt5106c.messages.Interested; import edu.ufl.cise.cnt5106c.messages.Message; import edu.ufl.cise.cnt5106c.messages.NotInterested; import edu.ufl.cise.cnt5106c.messages.Piece; import edu.ufl.cise.cnt5106c.messages.Request; import edu.ufl.cise.cnt5106c.log.EventLogger; import edu.ufl.cise.cnt5106c.log.LogHelper; import java.util.BitSet; /** * @author Giacomo Benincasa (giacomo@cise.ufl.edu) */ public class MessageHandler { private boolean _chokedByRemotePeer; private final int _remotePeerId; private final FileManager _fileMgr; private final PeerManager _peerMgr; private final EventLogger _eventLogger; MessageHandler(int remotePeerId, FileManager fileMgr, PeerManager peerMgr, EventLogger eventLogger) { _chokedByRemotePeer = true; _fileMgr = fileMgr; _peerMgr = peerMgr; _remotePeerId = remotePeerId; _eventLogger = eventLogger; } public Message handle(Handshake handshake) { BitSet bitset = _fileMgr.getReceivedParts(); if (!bitset.isEmpty()) { return (new Bitfield(bitset)); } return null; } public Message handle(Message msg) { switch (msg.getType()) { case Choke: { _chokedByRemotePeer = true; _eventLogger.chokeMessage(_remotePeerId); return null; } case Unchoke: { _chokedByRemotePeer = false; _eventLogger.unchokeMessage(_remotePeerId); return requestPiece(); } case Interested: { _eventLogger.interestedMessage(_remotePeerId); _peerMgr.addInterestPeer(_remotePeerId); return null; } case NotInterested: { _eventLogger.notInterestedMessage(_remotePeerId); _peerMgr.removeInterestPeer(_remotePeerId); return null; } case Have: { Have have = (Have) msg; final int pieceId = have.getPieceIndex(); _eventLogger.haveMessage(_remotePeerId, pieceId); _peerMgr.haveArrived(_remotePeerId, pieceId); if (_fileMgr.getReceivedParts().get(pieceId)) { return new NotInterested(); } else { return new Interested(); } } case BitField: { Bitfield bitfield = (Bitfield) msg; BitSet bitset = bitfield.getBitSet(); _peerMgr.bitfieldArrived(_remotePeerId, bitset); bitset.andNot(_fileMgr.getReceivedParts()); if (bitset.isEmpty()) { return new NotInterested(); } else { // the peer has parts that this peer does not have return new Interested(); } } case Request: { Request request = (Request) msg; if (_peerMgr.canUploadToPeer(_remotePeerId)) { byte[] piece = _fileMgr.getPiece(request.getPieceIndex()); if (piece != null) { return new Piece(request.getPieceIndex(), piece); } } return null; } case Piece: { Piece piece = (Piece) msg; _fileMgr.addPart(piece.getPieceIndex(), piece.getContent()); _peerMgr.receivedPart(_remotePeerId, piece.getContent().length); _eventLogger.pieceDownloadedMessage(_remotePeerId, piece.getPieceIndex(), _fileMgr.getNumberOfReceivedParts()); return requestPiece(); } } return null; } private Message requestPiece() { if (!_chokedByRemotePeer) { int partId = _fileMgr.getPartToRequest(_peerMgr.getReceivedParts(_remotePeerId)); if (partId >= 0) { LogHelper.getLogger().debug("Requesting part " + partId + " to " + _remotePeerId); return new Request (partId); } else { LogHelper.getLogger().debug("No parts can be requested to " + _remotePeerId); } } return null; } }
package function.genotype.base; import function.annotation.base.AnnotatedVariant; import function.genotype.statistics.HWEExact; import function.genotype.trio.TrioCommand; import function.genotype.trio.TrioManager; import function.variant.base.VariantManager; import global.Data; import global.Index; import java.sql.ResultSet; import java.util.HashMap; import utils.MathManager; /** * * @author nick */ public class CalledVariant extends AnnotatedVariant { private HashMap<Integer, Carrier> carrierMap = new HashMap<>(); private HashMap<Integer, NonCarrier> noncarrierMap = new HashMap<>(); private byte[] gt = new byte[SampleManager.getTotalSampleNum()]; private short[] dpBin = new short[SampleManager.getTotalSampleNum()]; private int[] qcFailSample = new int[2]; public int[][] genoCount = new int[5][2]; public float[] homFreq = new float[2]; public float[] hetFreq = new float[2]; public float[] af = new float[2]; public double[] hweP = new double[2]; private int[] coveredSample = new int[2]; private double coveredSampleBinomialP; private float[] coveredSamplePercentage = new float[2]; public CalledVariant(String chr, int variantId, ResultSet rset) throws Exception { super(chr, variantId, rset); init(); } private void init() throws Exception { if (isValid && initCarrierData()) { DPBinBlockManager.initCarrierAndNonCarrierByDPBin(this, carrierMap, noncarrierMap); initGenoCovArray(); if (checkGenoCountValid()) { calculateAlleleFreq(); if (checkAlleleFreqValid()) { initDPBinCoveredSampleBinomialP(); initCoveredSamplePercentage(); if (checkCoveredSampleBinomialP() && checkCoveredSamplePercentage()) { calculateGenotypeFreq(); calculateHweP(); } } } } } private boolean initCarrierData() { if (VariantManager.isUsed()) { // when --variant or --rs-number applied // single variant carriers data process CarrierBlockManager.initCarrierMap(carrierMap, this); if (!GenotypeLevelFilterCommand.isMinVarPresentValid(carrierMap.size())) { isValid = false; } } else { // block variants carriers data process CarrierBlockManager.init(this); carrierMap = CarrierBlockManager.getVarCarrierMap(variantId); if (carrierMap == null) { carrierMap = new HashMap<>(); if (GenotypeLevelFilterCommand.minVarPresent > 0) { isValid = false; } } else if (!GenotypeLevelFilterCommand.isMinVarPresentValid(carrierMap.size())) { isValid = false; } } return isValid; } private boolean checkGenoCountValid() { int totalQCFailSample = qcFailSample[Index.CASE] + qcFailSample[Index.CTRL]; isValid = GenotypeLevelFilterCommand.isMaxQcFailSampleValid(totalQCFailSample) && GenotypeLevelFilterCommand.isMinCaseCarrierValid(getCaseCarrier()); return isValid; } private boolean checkCoveredSampleBinomialP() { isValid = GenotypeLevelFilterCommand .isMinCoveredSampleBinomialPValid(coveredSampleBinomialP); return isValid; } private boolean checkCoveredSamplePercentage() { isValid = GenotypeLevelFilterCommand.isMinCoveredCasePercentageValid(coveredSamplePercentage[Index.CASE]) && GenotypeLevelFilterCommand.isMinCoveredCtrlPercentageValid(coveredSamplePercentage[Index.CTRL]); return isValid; } private boolean checkAlleleFreqValid() { isValid = GenotypeLevelFilterCommand.isMaxCtrlAFValid(af[Index.CTRL]) && GenotypeLevelFilterCommand.isMinCtrlAFValid(af[Index.CTRL]); return isValid; } private int getCaseCarrier() { return genoCount[Index.HOM][Index.CASE] + genoCount[Index.HET][Index.CASE]; } // initialize genotype & dpBin array for better compute performance use private void initGenoCovArray() { for (Sample sample : SampleManager.getList()) { Carrier carrier = carrierMap.get(sample.getId()); NonCarrier noncarrier = noncarrierMap.get(sample.getId()); boolean isDPBinValid; if (carrier != null) { isDPBinValid = applyCoverageFilter(sample, carrier.getDPBin(), GenotypeLevelFilterCommand.minCaseCoverageCall, GenotypeLevelFilterCommand.minCtrlCoverageCall); if (!isDPBinValid) { carrier.setGT(Data.BYTE_NA); carrier.setDPBin(Data.SHORT_NA); } setGenoDPBin(carrier.getGT(), carrier.getDPBin(), sample.getIndex()); addSampleGeno(carrier.getGT(), sample); if (carrier.getGT() == Data.BYTE_NA) { // have to remove it for init Non-carrier map qcFailSample[sample.getPheno()]++; carrierMap.remove(sample.getId()); } } else if (noncarrier != null) { isDPBinValid = applyCoverageFilter(sample, noncarrier.getDPBin(), GenotypeLevelFilterCommand.minCaseCoverageNoCall, GenotypeLevelFilterCommand.minCtrlCoverageNoCall); if (!isDPBinValid) { noncarrier.setGT(Data.BYTE_NA); noncarrier.setDPBin(Data.SHORT_NA); } setGenoDPBin(noncarrier.getGT(), noncarrier.getDPBin(), sample.getIndex()); addSampleGeno(noncarrier.getGT(), sample); } else { setGenoDPBin(Data.BYTE_NA, Data.SHORT_NA, sample.getIndex()); isDPBinValid = false; } if (isDPBinValid) { coveredSample[sample.getPheno()]++; } } noncarrierMap = null; // free memory } public void initDPBinCoveredSampleBinomialP() { if (GenotypeLevelFilterCommand.minCoveredSampleBinomialP != Data.NO_FILTER) { if (coveredSample[Index.CASE] == 0 || coveredSample[Index.CTRL] == 0) { coveredSampleBinomialP = Data.DOUBLE_NA; } else { coveredSampleBinomialP = MathManager.getBinomialTWOSIDED(coveredSample[Index.CASE] + coveredSample[Index.CTRL], coveredSample[Index.CASE], MathManager.devide(SampleManager.getCaseNum(), SampleManager.getTotalSampleNum())); } } } public void initCoveredSamplePercentage() { coveredSamplePercentage[Index.CASE] = MathManager.devide(coveredSample[Index.CASE], SampleManager.getCaseNum()) * 100; coveredSamplePercentage[Index.CTRL] = MathManager.devide(coveredSample[Index.CTRL], SampleManager.getCtrlNum()) * 100; } private boolean applyCoverageFilter(Sample sample, short dpBin, int minCaseCov, int minCtrlCov) { if (sample.isCase()) // --min-case-coverage-call or --min-case-coverage-no-call { if (!GenotypeLevelFilterCommand.isMinCoverageValid(dpBin, minCaseCov)) { return false; } } else // --min-ctrl-coverage-call or --min-ctrl-coverage-no-call if (!GenotypeLevelFilterCommand.isMinCoverageValid(dpBin, minCtrlCov)) { return false; } return true; } public void addSampleGeno(byte geno, Sample sample) { if (geno != Data.BYTE_NA) { if (TrioCommand.isListTrio && TrioManager.isParent(sample.getId())) { // exclude parent controls return; } genoCount[geno][sample.getPheno()]++; } } public void deleteSampleGeno(byte geno, Sample sample) { if (geno != Data.BYTE_NA) { genoCount[geno][sample.getPheno()] } } private void setGenoDPBin(byte geno, short bin, int s) { gt[s] = geno; dpBin[s] = bin; } public void calculate() { calculateAlleleFreq(); calculateGenotypeFreq(); calculateHweP(); } private void calculateAlleleFreq() { int caseAC = 2 * genoCount[Index.HOM][Index.CASE] + genoCount[Index.HET][Index.CASE]; int caseTotalAC = caseAC + genoCount[Index.HET][Index.CASE] + 2 * genoCount[Index.REF][Index.CASE]; // (2*hom + maleHom + het) / (2*hom + maleHom + 2*het + 2*ref + maleRef) af[Index.CASE] = MathManager.devide(caseAC, caseTotalAC); int ctrlAC = 2 * genoCount[Index.HOM][Index.CTRL] + genoCount[Index.HET][Index.CTRL]; int ctrlTotalAC = ctrlAC + genoCount[Index.HET][Index.CTRL] + 2 * genoCount[Index.REF][Index.CTRL]; af[Index.CTRL] = MathManager.devide(ctrlAC, ctrlTotalAC); } private void calculateGenotypeFreq() { int totalCaseGenotypeCount = genoCount[Index.HOM][Index.CASE] + genoCount[Index.HET][Index.CASE] + genoCount[Index.REF][Index.CASE]; int totalCtrlGenotypeCount = genoCount[Index.HOM][Index.CTRL] + genoCount[Index.HET][Index.CTRL] + genoCount[Index.REF][Index.CTRL]; // hom / (hom + het + ref) homFreq[Index.CASE] = MathManager.devide( genoCount[Index.HOM][Index.CASE], totalCaseGenotypeCount); homFreq[Index.CTRL] = MathManager.devide( genoCount[Index.HOM][Index.CTRL], totalCtrlGenotypeCount); hetFreq[Index.CASE] = MathManager.devide(genoCount[Index.HET][Index.CASE], totalCaseGenotypeCount); hetFreq[Index.CTRL] = MathManager.devide(genoCount[Index.HET][Index.CTRL], totalCtrlGenotypeCount); } private void calculateHweP() { hweP[Index.CASE] = HWEExact.getP(genoCount[Index.HOM][Index.CASE], genoCount[Index.HET][Index.CASE], genoCount[Index.REF][Index.CASE]); hweP[Index.CTRL] = HWEExact.getP(genoCount[Index.HOM][Index.CTRL], genoCount[Index.HET][Index.CTRL], genoCount[Index.REF][Index.CTRL]); } public short getDPBin(int index) { if (index == Data.INTEGER_NA) { return Data.SHORT_NA; } return dpBin[index]; } public byte getGT(int index) { if (index == Data.INTEGER_NA) { return Data.BYTE_NA; } return gt[index]; } public Carrier getCarrier(int sampleId) { return carrierMap.get(sampleId); } public int getQcFailSample(byte pheno) { return qcFailSample[pheno]; } public int getCoveredSample(byte pheno) { return coveredSample[pheno]; } public float getCoveredSamplePercentage(byte pheno) { return coveredSamplePercentage[pheno]; } public double getCoveredSampleBinomialP() { return coveredSampleBinomialP; } }
package jstore.implementations; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Stack; import jstore.StringSet; abstract class AbstractDafsa<TState> implements StringSet { @Override public boolean contains(String string) { Helper.verifyInputString(string); TState state = getRootState(); for (int i = 0; i < string.length(); i++) { state = getNextState(state, string.charAt(i)); if (state == null) { return false; } } return isFinal(state); } public int countStates() { HashSet<TState> visited = new HashSet<TState>(); Queue<TState> toVisit = new LinkedList<TState>(); int counter = 0; toVisit.add(getRootState()); visited.add(getRootState()); while (!toVisit.isEmpty()) { ++counter; TState cur = toVisit.poll(); for (Pair<Character, TState> child : iterateDirectTransitions(cur)) { TState next = child.getSecond(); if (!visited.contains(next)) { visited.add(next); toVisit.add(next); } } } return counter; } @Override public Collection<String> getAll() { return getAll("", getRootState()); } @Override public Iterable<String> iterateAll() { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { Stack<TState> stack; Stack<Iterator<Pair<Character, TState>>> stack2; StringBuilder sb; boolean alreadyAdvanced = isFinal(getRootState()); { sb = new StringBuilder(); stack = new Stack<TState>(); stack2 = new Stack<Iterator<Pair<Character, TState>>>(); stack.push(getRootState()); stack2.push(iterateDirectTransitions(getRootState()).iterator()); } private void advanceToNextFinalState() { do { Iterator<Pair<Character, TState>> topIterator = stack2.peek(); if (topIterator.hasNext()) { Pair<Character, TState> nextTransition = topIterator.next(); TState nextState = nextTransition.getSecond(); sb.append(nextTransition.getFirst()); stack.push(nextState); stack2.push(iterateDirectTransitions(nextState).iterator()); if (isFinal(nextState)) { return; } } else { if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } stack.pop(); stack2.pop(); } } while (!stack.isEmpty()); } @Override public boolean hasNext() { if (!alreadyAdvanced) { advanceToNextFinalState(); alreadyAdvanced = true; } return !stack.isEmpty() && isFinal(stack.peek()); } @Override public String next() { if (hasNext()) { alreadyAdvanced = false; return sb.toString(); } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException("Implement me"); } }; } }; } @Override public Iterable<String> iterateByPrefix(String prefix) { return null; } @Override public Collection<String> getByPrefix(String prefix) { Helper.verifyInputString(prefix); TState state = getRootState(); for (int i = 0; i < prefix.length(); i++) { state = getNextState(state, prefix.charAt(i)); if (state == null) { return Collections.emptyList(); } } return getAll(prefix, state); } protected Collection<String> getAll(String prefix, TState fromState) { List<String> strings = new ArrayList<String>(); StringBuilder builder = new StringBuilder(prefix); this.iterateRecursive(fromState, builder, strings); return strings; } protected abstract TState getNextState(TState state, char symbol); protected abstract TState getRootState(); protected abstract boolean isFinal(TState state); protected abstract Iterable<Pair<Character, TState>> iterateDirectTransitions(TState fromState); protected void iterateRecursive(TState state, StringBuilder sb, List<String> strings) { if (isFinal(state)) { strings.add(sb.toString()); } for (Pair<Character, TState> entry : this.iterateDirectTransitions(state)) { sb.append(entry.getFirst()); iterateRecursive(entry.getSecond(), sb, strings); sb.deleteCharAt(sb.length() - 1); } } }
package kr.ac.ajou.dsd.kda.util; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.annotation.WebListener; import org.apache.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.embedded.ServletContextInitializer; import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.ContextStartedEvent; import org.springframework.stereotype.Component; import kr.ac.ajou.dsd.kda.KoreanDiningAdvisorApplication; @Configuration public class DatabaseInit implements ServletContextInitializer { static final private Logger logger = Logger.getLogger(KoreanDiningAdvisorApplication.class); static final private String DATABASETYPE = "MYSQL"; @Override public void onStartup(ServletContext servletContext) throws ServletException { String dbHost = System.getenv("OPENSHIFT_" + DATABASETYPE + "_DB_HOST"); String dbPort = System.getenv("OPENSHIFT_" + DATABASETYPE + "_DB_PORT"); String dbUsername = System.getenv("OPENSHIFT_" + DATABASETYPE + "_DB_USERNAME"); String dbPassword = System.getenv("OPENSHIFT_" + DATABASETYPE + "_DB_PASSWORD"); String dbSocket = System.getenv("OPENSHIFT_" + DATABASETYPE + "_DB_SOCKET"); String dbURL = System.getenv("OPENSHIFT_" + DATABASETYPE + "_DB_URL"); if(dbHost == null || dbPort == null || dbUsername == null || dbPassword == null || dbSocket == null || dbURL == null) { logger.info("Database environment variables not set. Use embedded database"); return; } logger.info("set properties for database connection on server"); System.setProperty("spring.datasource.url", "jdbc:"+ DATABASETYPE.toLowerCase() + "://"+ dbHost + ":" + dbPort + "/kda?characterEncoding=UTF-8"); System.setProperty("spring.datasource.username", dbUsername); System.setProperty("spring.datasource.password", dbPassword); System.setProperty("spring.datasource.driver", "com.mysql.jdbc.Driver"); System.setProperty("spring.jpa.database-platform", "org.hibernate.dialect.MySQL5Dialect"); System.setProperty("spring.datasource.testOnBorrow", "true"); System.setProperty("spring.datasource.validationQuery", "SELECT 1"); System.setProperty("spring.datasource.initialize", "true"); System.setProperty("spring.jpa.hibernate.ddl-auto", "create"); // System.setProperty("spring.jpa.hibernate.ddl-auto", "none"); } }
package nars.control; import nars.main.Parameters; import nars.entity.Concept; import nars.io.events.Events; import nars.entity.Task; import nars.entity.TermLink; import nars.inference.BudgetFunctions; import nars.inference.RuleTables; import nars.storage.Memory; /** Concept reasoning context - a concept is "fired" or activated by applying the reasoner */ public class GeneralInferenceControl { public static void selectConceptForInference(Memory mem) { Concept currentConcept = mem.concepts.takeNext(); if (currentConcept==null) { return; } if(currentConcept.taskLinks.size() == 0) { //remove concepts without tasklinks and without termlinks mem.concepts.take(currentConcept.getTerm()); mem.conceptRemoved(currentConcept); return; } if(currentConcept.termLinks.size() == 0) { //remove concepts without tasklinks and without termlinks mem.concepts.take(currentConcept.getTerm()); mem.conceptRemoved(currentConcept); return; } DerivationContext nal = new DerivationContext(mem); nal.setCurrentConcept(currentConcept); fireConcept(nal, 1); { // put back float forgetCycles = nal.memory.cycles(nal.memory.param.conceptForgetDurations); nal.currentConcept.setQuality(BudgetFunctions.or(nal.currentConcept.getQuality(),nal.memory.emotion.happy())); nal.memory.concepts.putBack(nal.currentConcept, forgetCycles, nal.memory); } } public static void fireConcept(DerivationContext nal, int numTaskLinks) { for (int i = 0; i < numTaskLinks; i++) { if (nal.currentConcept.taskLinks.size() == 0) { return; } nal.currentTaskLink = nal.currentConcept.taskLinks.takeNext(); if (nal.currentTaskLink == null) { return; } if (nal.currentTaskLink.budget.aboveThreshold()) { fireTaskLink(nal, Parameters.TERMLINK_MAX_REASONED); } nal.currentConcept.taskLinks.putBack(nal.currentTaskLink, nal.memory.cycles(nal.memory.param.taskLinkForgetDurations), nal.memory); } } protected static void fireTaskLink(DerivationContext nal, int termLinks) { final Task task = nal.currentTaskLink.getTarget(); nal.setCurrentTerm(nal.currentConcept.term); nal.setCurrentTaskLink(nal.currentTaskLink); nal.setCurrentBeliefLink(null); nal.setCurrentTask(task); // one of the two places where this variable is set nal.memory.emotion.adjustBusy(nal.currentTaskLink.getPriority(),nal.currentTaskLink.getDurability(),nal); if (nal.currentTaskLink.type == TermLink.TRANSFORM) { nal.setCurrentBelief(null); //TermLink tasklink_as_termlink = new TermLink(nal.currentTaskLink.getTerm(), TermLink.TRANSFORM, nal.getCurrentTaskLink().index); //if(nal.currentTaskLink.novel(tasklink_as_termlink, nal.memory.time(), true)) { //then record yourself, but also here novelty counts RuleTables.transformTask(nal.currentTaskLink, nal); // to turn this into structural inference as below? } else { while (termLinks > 0) { final TermLink termLink = nal.currentConcept.selectTermLink(nal.currentTaskLink, nal.memory.time()); if (termLink == null) { break; } fireTermlink(termLink, nal); nal.currentConcept.returnTermLink(termLink); termLinks } } nal.memory.emit(Events.ConceptFire.class, nal); //memory.logic.TASKLINK_FIRE.commit(currentTaskLink.budget.getPriority()); } public static boolean fireTermlink(final TermLink termLink, DerivationContext nal) { nal.setCurrentBeliefLink(termLink); try { RuleTables.reason(nal.currentTaskLink, termLink, nal); } catch(Exception ex) { if(Parameters.DEBUG) { System.out.println("issue in inference"); } } nal.memory.emit(Events.TermLinkSelect.class, termLink, nal.currentConcept, nal); //memory.logic.REASON.commit(termLink.getPriority()); return true; } }
package nl.hayovanloon.gcp.sql2gcloud; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import io.atlassian.fugue.Option; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.observables.ConnectableObservable; import java.lang.management.ManagementFactory; import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static io.atlassian.fugue.Option.option; public class Runner { private static final Logger LOG = LogManager.getLogger(Runner.class); private static final Pattern PARAMS_PATTERN = Pattern.compile( "(" + "(\\s+-c\\s+(?<conf>[^\\s]+))" + "|(\\s+-dr\\s+(?<driver>[^\\s]+))" + "|(\\s+-d\\s+(?<database>jdbc:[^\\s]+))" + "|(\\s+-u\\s+(?<user>[^\\s]+))" + "|(\\s+-p\\s+\"(?<password>[^\"]+)\")" + "|(\\s+-s\\s+\"(?<separator>[^\"]+)\"))+" + "(\\s+gs://(?<bucket>[a-z0-9-_.]{3,63})/(?<file>[^\\s]+))?" + "(\\s+(?<query>.+))?"); private static final String HELP = "Usage:" + "\n sql2gcloud [-c <config>] [-d jdbc:<database>] [-u <user>] [-p \"<password>\"] [-s \"<separator>\"]" + " [-dr <jdbc driver>] [<dest_url>] [<query>]" + "\n" + "\nExamples:" + "\n sql2gcloud -c conf/config.json gs://foo/bar/bla.txt SELECT \\* FROM foo" + "\n sql2gcloud -c conf/config.json -u myuser -p \\\"mypass\\\" gs://foo/bar/bla.txt SELECT \\* FROM foo" + "\n" + "\nConfig file format (JSON):" + "\n{" + "\n \"driver\": \"com.mysql.jdbc.Driver\"," + "\n \"database\": \"jdbc:mysql://127.0.0.1:3306/my_database\"," + "\n \"user\": \"my_user\"," + "\n \"password\": \"my_password\"," + "\n \"bucket\": \"foo\"," + "\n \"file\": \"bar/bla.txt\"," + "\n \"separator\": \"~~\"," + "\n \"query\": \"SELECT * FROM foo;\"" + "\n}" + "\n" + "\nSeparator is optional (default is '~~', all other fields must be " + "\nspecified in the config file or passed as a command line argument." + "\n" + "\nWhen passed via the command line, bucket and file names are to be" + "\nmerged into a single 'gs://...' url."; private static final String MISSING_PARAM = "either include it in the config or pass it as a parameter"; public static void main(String[] args) throws IOException { final Config config = parseArgs(args); final List<String> configErrors = config.validate(); if (!configErrors.isEmpty()) { System.err.println("Configuration errors detected:"); configErrors.forEach(error -> System.err.println(" " + error)); System.err.println("Operation aborted."); System.err.println("\nRun without command line arguments to display help."); System.exit(1); } // Register JDBC driver if provided config.getDriver().forEach(driver -> { try { Class.forName(driver).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { System.err.println("exception while registering JDBC driver: " + e); System.exit(1); } }); if (config.getDriver().isEmpty()) { final List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments(); if (!jvmArgs.stream().anyMatch(x -> x.startsWith("-Djdbc.drivers"))) { LOG.warn("No JDBC driver specified and could not detect one in JVM parameters."); } } Option<Subscription> subscription = Option.none(); try(Connection connection = DriverManager.getConnection(config.getDatabase(), config.getUser(), config.getPassword())) { final Observable<List<String>> observable = getObservable(connection, config.getQuery()); final Subscriber<List<String>> subscriber = GFSSubscriber.of(connection, config.getBucket(), config.getFile(), config.getSeparator()); subscription = Option.some(observable.subscribe(subscriber)); } catch (SQLException | GeneralSecurityException | IOException e) { System.err.println("Exception during initiation, operation aborted: " + e); e.printStackTrace(); subscription.forEach(Subscription::unsubscribe); System.exit(1); } } /** * Parses command line arguments and creates a Config object. * * The (optionally provided) config json provides the base. Its values are * overwritten with values provided on the command line. In the end, all * fields (except separator, which defaults to "~~") need to be set. * * @param args command line argument list * @return a new Config object */ private static Config parseArgs(String[] args) { if (args.length == 0 || "help".equals(args[0]) || "-h".equals(args[0])) { System.out.println(HELP); System.exit(0); return new Config(); // unreachable } else { // prefix whitespace is added to keep regex simple final String paramString = " " + StringUtils.join(args, " "); final Matcher m = PARAMS_PATTERN.matcher(paramString); if (m.find()) { final Config config = option(m.group("conf")).fold( Config::new, conf -> { try { return new ObjectMapper().readValue(new File(conf), Config.class); } catch (IOException e) { LOG.warn("Error reading configuration file {}, using empty as base.", conf); return new Config(); } }); option(m.group("driver")).forEach(config::setDriver); option(m.group("database")).forEach(config::setDatabase); option(m.group("user")).forEach(config::setUser); option(m.group("password")).forEach(config::setPassword); option(m.group("bucket")).forEach(config::setBucket); option(m.group("file")).forEach(config::setFile); option(m.group("separator")).forEach(config::setSeparator); option(m.group("query")).forEach(config::setQuery); System.out.println(config); return config; } else return new Config(); } } private static Observable<List<String>> getObservable(Connection connection, String query) throws GeneralSecurityException, IOException { return ConnectableObservable.create( new Observable.OnSubscribe<List<String>>() { @Override public void call(Subscriber<? super List<String>> subscriber) { try { final PreparedStatement statement = connection.prepareStatement(query); LOG.info("Started reading"); final ResultSet resultSet = statement.executeQuery(); final int cols = resultSet.getMetaData().getColumnCount(); while (resultSet.next()) { ImmutableList.Builder<String> colData = ImmutableList.builder(); for (int i = 1; i <= cols; i += 1) colData.add(resultSet.getString(i)); subscriber.onNext(colData.build()); } LOG.info("Done reading"); subscriber.onCompleted(); } catch (SQLException e) { subscriber.onError(e); } } } ); } private static class Config { private static final String DEFAULT_SEPARATOR = "~~"; private Option<String> driver = Option.none(); private String database; private String user; private String password; private String bucket; private String file; private String separator = DEFAULT_SEPARATOR; private String query; Config() {} List<String> validate() { final ImmutableList.Builder<String> errors = ImmutableList.builder(); if (database == null) errors.add("No database specified; " + MISSING_PARAM); if (user == null) errors.add("No user specified; " + MISSING_PARAM); if (password == null) errors.add("No password specified; " + MISSING_PARAM); if (bucket == null) errors.add("No bucket specified; " + MISSING_PARAM); if (file == null) errors.add("No file specified; " + MISSING_PARAM); if (separator == null) separator = DEFAULT_SEPARATOR; else if (separator.isEmpty()) LOG.info("Column separator is empty"); if (query == null) errors.add("No query specified; " + MISSING_PARAM); else if (!query.startsWith("SELECT")) errors.add("Query must start with 'SELECT'"); return errors.build(); } Option<String> getDriver() { return driver; } public void setDriver(String driver) { this.driver = Option.some(driver); } String getDatabase() { return database; } void setDatabase(String database) { this.database = database; } String getUser() { return user; } void setUser(String user) { this.user = user; } String getPassword() { return password; } void setPassword(String password) { this.password = password; } String getBucket() { return bucket; } void setBucket(String bucket) { this.bucket = bucket; } String getFile() { return file; } void setFile(String file) { this.file = file; } String getSeparator() { return separator; } void setSeparator(String separator) { this.separator = separator; } String getQuery() { return query; } void setQuery(String query) { this.query = query; } @Override public String toString() { return "Config{" + "driver=" + driver + ", database='" + database + '\'' + ", user='" + user + '\'' + ", password='" + password + '\'' + ", bucket='" + bucket + '\'' + ", file='" + file + '\'' + ", separator='" + separator + '\'' + ", query='" + query + '\'' + '}'; } } }
package org.ajabshahar.platform.daos; import io.dropwizard.hibernate.AbstractDAO; import org.ajabshahar.platform.models.Song; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public class SongDAO extends AbstractDAO<Song> { private final static Logger logger = LoggerFactory.getLogger(SongDAO.class); private final SessionFactory sessionFactory; public SongDAO(SessionFactory sessionFactory) { super(sessionFactory); this.sessionFactory = sessionFactory; } public Song findById(Long id) { return (Song) sessionFactory.openSession().get(Song.class, id); } public Song saveSong(Song song) { currentSession().update(song.getTitle()); currentSession().save(song); return song; } public List<Song> findAll() { return list(namedQuery("org.ajabshahar.platform.models.Song.findAll")); } public Song invokeAllSetters(Song originalSongData, Song updatableSongData) { originalSongData.setDownload_url(updatableSongData.getDownload_url()); originalSongData.setShowOnLandingPage(updatableSongData.getShowOnLandingPage()); originalSongData.setDuration(updatableSongData.getDuration()); originalSongData.setYoutubeVideoId(updatableSongData.getYoutubeVideoId()); originalSongData.setThumbnail_url(updatableSongData.getThumbnail_url()); originalSongData.setIsAuthoringComplete(updatableSongData.getIsAuthoringComplete()); originalSongData.setSingers(updatableSongData.getSingers()); originalSongData.setPoets(updatableSongData.getPoets()); originalSongData.setSongCategory(updatableSongData.getSongCategory()); originalSongData.setMediaCategory(updatableSongData.getMediaCategory()); originalSongData.setTitle(updatableSongData.getTitle()); originalSongData.setSongTitle(updatableSongData.getSongTitle()); return originalSongData; } public int getCountOfSongsThatStartWith(String letter) { return list(namedQuery("org.ajabshahar.platform.models.Song.findAllFilteredBy").setParameter("letter", letter + "%")).size(); } public List<Song> findBy(int songId, int singerId, int poetId, int startFrom, String filteredLetter) { Session currentSession = sessionFactory.getCurrentSession(); Criteria findSongs = currentSession.createCriteria(Song.class); if (songId != 0) { findSongs.add(Restrictions.eq("id", Long.valueOf(songId))); } if (singerId != 0) { findSongs.createAlias("singers", "singersAlias"); findSongs.add(Restrictions.eq("singersAlias.id", Long.valueOf(singerId))); } if (poetId != 0) { findSongs.createAlias("poets", "poetsAlias"); findSongs.add(Restrictions.eq("poetsAlias.id", Long.valueOf(poetId))); } if (startFrom != 0) { findSongs.setFirstResult(startFrom); } if (filteredLetter != null) { findSongs.createAlias("songTitle", "songTitleAlias"); findSongs.add(Restrictions.like("songTitleAlias.englishTranslation", filteredLetter, MatchMode.START)); } findSongs.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return findSongs.list(); } public Song updateSong(Song updatableSong) { Long id = updatableSong.getId(); Song originalSongData = (Song) sessionFactory.openSession().get(Song.class, id); if (updatableSong.getSongTitle().getId() == 0) { TitleDAO titleDAO = new TitleDAO(sessionFactory); titleDAO.create(updatableSong.getSongTitle()); } if (updatableSong.getTitle().getId() == 0) { TitleDAO titleDAO = new TitleDAO(sessionFactory); titleDAO.create(updatableSong.getTitle()); } originalSongData = invokeAllSetters(originalSongData, updatableSong); sessionFactory.getCurrentSession().update(originalSongData); return originalSongData; } public List<Song> findSongWithVersions(int songId) { Session currentSession = sessionFactory.getCurrentSession(); Criteria findSongs = currentSession.createCriteria(Song.class); Song song = findById(Long.valueOf(songId)); if (song != null) { findSongs.createAlias("title", "titleAlias"); findSongs.add(Restrictions.eq("titleAlias.id", song.getTitle().getId())); } else { return new ArrayList<>(); } findSongs.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return findSongs.list(); } }
package li.vin.net; import android.support.annotation.NonNull; import okhttp3.HttpUrl; public enum VinliEndpoint { AUTH("auth"), DIAGNOSTICS("diagnostic"), EVENTS("events"), PLATFORM("platform"), RULES("rules"), TELEMETRY("telemetry"), TRIPS("trips"), SAFETY("safety"), BEHAVIORAL("behavioral"), DISTANCE("distance"), DUMMY("dummies"); static final String DOMAIN_QA = "-qa."; static final String DOMAIN_DEV = "-dev."; static final String DOMAIN_DEMO = "-demo."; static final String DOMAIN_PROD = "."; static private String host = "vin.li"; static private String domain = DOMAIN_PROD; static synchronized String domain() { return domain + host; } public static synchronized void setHost(@NonNull String host) { VinliEndpoint.host = host; } public static synchronized void setDomain(@NonNull String domain) { VinliEndpoint.domain = domain; } private final HttpUrl mUrl; private final String subDomain; VinliEndpoint(String subDomain) { this.subDomain = subDomain; mUrl = new HttpUrl.Builder() .scheme("https") .host(subDomain + domain()) .addPathSegment("api") .addPathSegment("v1") .addPathSegment("") .build(); } public String getName() { return this.name(); } public String getUrl() { return mUrl.newBuilder().host(subDomain + domain()).toString(); } }
package io.strimzi.test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import io.fabric8.kubernetes.client.DefaultKubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.NamespacedKubernetesClient; import io.strimzi.test.k8s.HelmClient; import io.strimzi.test.k8s.KubeClient; import io.strimzi.test.k8s.KubeClusterException; import io.strimzi.test.k8s.KubeClusterResource; import io.strimzi.test.k8s.Minishift; import io.strimzi.test.k8s.OpenShift; import org.apache.commons.collections.CollectionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ConditionEvaluationResult; import org.junit.jupiter.api.extension.ExecutionCondition; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.TestExecutionExceptionHandler; import java.io.File; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Stack; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static io.strimzi.test.TestUtils.entriesToMap; import static io.strimzi.test.TestUtils.entry; import static io.strimzi.test.TestUtils.indent; import static io.strimzi.test.TestUtils.writeFile; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; /** * A test extension which sets up Strimzi resources in a Kubernetes cluster * according to annotations ({@link Namespace}, {@link Resources}, {@link ClusterOperator}) * on the test class and/or test methods. {@link OpenShiftOnly} can be used to ignore tests when not running on * OpenShift (if the thing under test is OpenShift-specific). JUnit5 annotation {@link Tag} can be used for execute/skip specific * test classes and/or test methods. */ public class StrimziExtension implements AfterAllCallback, BeforeAllCallback, AfterEachCallback, BeforeEachCallback, ExecutionCondition, TestExecutionExceptionHandler { private static final Logger LOGGER = LogManager.getLogger(StrimziExtension.class); /** * If env var NOTEARDOWN is set to any value then teardown for resources supported by annotations * won't happen. This can be useful in debugging a single test, because it leaves the cluster * in the state it was in when the test failed. */ public static final String NOTEARDOWN = "NOTEARDOWN"; public static final String KAFKA_PERSISTENT_YAML = "../examples/kafka/kafka-persistent.yaml"; public static final String KAFKA_CONNECT_YAML = "../examples/kafka-connect/kafka-connect.yaml"; public static final String KAFKA_CONNECT_S2I_CM = "../examples/configmaps/cluster-operator/kafka-connect-s2i.yaml"; public static final String CO_INSTALL_DIR = "../install/cluster-operator"; public static final String CO_DEPLOYMENT_NAME = "strimzi-cluster-operator"; public static final String TOPIC_CM = "../examples/topic/kafka-topic.yaml"; public static final String HELM_CHART = "../helm-charts/strimzi-kafka-operator/"; public static final String HELM_RELEASE_NAME = "strimzi-systemtests"; public static final String STRIMZI_ORG = "strimzi"; public static final String STRIMZI_TAG = "latest"; public static final String IMAGE_PULL_POLICY = "Always"; public static final String REQUESTS_MEMORY = "512Mi"; public static final String REQUESTS_CPU = "200m"; public static final String LIMITS_MEMORY = "512Mi"; public static final String LIMITS_CPU = "1000m"; public static final String OPERATOR_LOG_LEVEL = "INFO"; private static final String DEFAULT_TAG = ""; private static final String TAG_LIST_NAME = "junitTags"; private static final String START_TIME = "start time"; private static final String TEST_LOG_DIR = System.getenv().getOrDefault("TEST_LOG_DIR", "../systemtest/target/logs/"); /** Tags */ public static final String ACCEPTANCE = "acceptance"; public static final String REGRESSION = "regression"; private static DefaultKubernetesClient client = new DefaultKubernetesClient(); private KubeClusterResource clusterResource; private Class testClass; private Statement classStatement; private Statement methodStatement; private Collection<String> declaredTags; private Collection<String> enabledTags; @Override public void afterAll(ExtensionContext context) { deleteResource((Bracket) classStatement); } @Override public void beforeAll(ExtensionContext context) { classStatement = new Bracket(null, () -> e -> { LOGGER.info("Failed to set up test class {}, due to {}", testClass.getName(), e, e); }) { @Override protected void before() { } @Override protected void after() { } }; classStatement = withClusterOperator(testClass, classStatement); classStatement = withResources(testClass, classStatement); classStatement = withNamespaces(testClass, classStatement); classStatement = withLogging(testClass, classStatement); try { Bracket current = (Bracket) classStatement; while (current != null) { current.before(); current = (Bracket) current.statement; } } catch (Throwable throwable) { throwable.printStackTrace(); } } @Override public void afterEach(ExtensionContext context) { deleteResource((Bracket) methodStatement); } @Override public void beforeEach(ExtensionContext context) { Method testMethod = context.getTestMethod().get(); methodStatement = new Bracket(null, () -> e -> { LOGGER.info("Failed to set up test class {}, due to {}", testClass.getName(), e, e); }) { @Override protected void before() { } @Override protected void after() { } }; methodStatement = withClusterOperator(testMethod, methodStatement); methodStatement = withResources(testMethod, methodStatement); methodStatement = withNamespaces(testMethod, methodStatement); methodStatement = withLogging(testMethod, methodStatement); try { Bracket current = (Bracket) methodStatement; while (current != null) { current.before(); current = (Bracket) current.statement; } } catch (Throwable throwable) { throwable.printStackTrace(); } } @Override public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { if (throwable instanceof AssertionError || throwable instanceof TimeoutException || throwable instanceof KubeClusterException) { // Get current date to create a unique folder String currentDate = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()); String logDir = context.getTestMethod().isPresent() ? TEST_LOG_DIR + context.getTestMethod().get().getDeclaringClass().getSimpleName() + "." + context.getTestMethod().get().getName() + "_" + currentDate : TEST_LOG_DIR + currentDate; LogCollector logCollector = new LogCollector(client.inNamespace(kubeClient().namespace()), new File(logDir)); logCollector.collectEvents(); logCollector.collectLogsForPods(); } throw throwable; } private class LogCollector { NamespacedKubernetesClient client; String namespace; File logDir; private LogCollector(NamespacedKubernetesClient client, File logDir) { this.client = client; this.namespace = client.getNamespace(); this.logDir = logDir; logDir.mkdirs(); } private void collectLogsForPods() { LOGGER.info("Collecting logs for pods in namespace {}", namespace); client.pods().list().getItems().forEach(pod -> { String podName = pod.getMetadata().getName(); client.pods().withName(podName).get().getStatus().getContainerStatuses().forEach(containerStatus -> { try { String log = client.pods().withName(podName).inContainer(containerStatus.getName()).getLog(); // Print container logs to console LOGGER.info("Logs for container {} from pod {}{}{}", containerStatus.getName(), podName, System.lineSeparator(), log); // Write logs from containers to files writeFile(logDir + "/" + "logs-pod-" + podName + "-container-" + containerStatus.getName() + ".log", log); } catch (KubernetesClientException e) { if (e.getMessage().equals("container \"" + containerStatus.getName() + "\" in pod \"" + podName + "\" is terminated")) { LOGGER.info("Container {} in pod {} is terminated before teardown", containerStatus.getName(), podName); } else { throw e; } } }); }); } private void collectEvents() { LOGGER.info("Collecting events in namespace {}", namespace); String events = kubeClient().getEvents(); // Print events to console LOGGER.info("Events for namespace {}{}{}", namespace, System.lineSeparator(), events); // Write events to file writeFile(logDir + "/" + "events-in-namespace" + kubeClient().namespace() + ".log", events); } } @Override public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { if (context.getElement().get() instanceof Class) { saveTestingClassInfo(context); if (!isWrongClusterType(context) && !areAllChildrenIgnored(context)) { return ConditionEvaluationResult.enabled("Test class is enabled"); } return ConditionEvaluationResult.disabled("Test class is disabled"); } else { if (!isIgnoredByTag(context) && !isWrongClusterType(context)) { return ConditionEvaluationResult.enabled("Test method is enabled"); } return ConditionEvaluationResult.disabled("Test method is disabled"); } } private void deleteResource(Bracket resource) { if (resource != null) { deleteResource((Bracket) resource.statement); resource.after(); } } /** * Class for annotations routine execution */ abstract class Bracket extends Statement implements Runnable { public final Statement statement; private final Thread hook = new Thread(this); private final Supplier<Consumer<? super Throwable>> onError; public Bracket(Statement statement, Supplier<Consumer<? super Throwable>> onError) { this.statement = statement; this.onError = onError; } @Override public void evaluate() throws Throwable { // All this fuss just to ensure that the first thrown exception is what propagates Throwable thrown = null; try { Runtime.getRuntime().addShutdownHook(hook); before(); statement.evaluate(); } catch (Throwable e) { thrown = e; if (onError != null) { try { onError.get().accept(e); } catch (Throwable t) { thrown.addSuppressed(t); } } } finally { try { Runtime.getRuntime().removeShutdownHook(hook); runAfter(); } catch (Throwable e) { if (thrown != null) { thrown.addSuppressed(e); throw thrown; } else { thrown = e; } } if (thrown != null) { throw thrown; } } } /** * Runs before the test */ protected abstract void before(); /** * Runs after the test, even it if failed or the JVM can killed */ protected abstract void after(); @Override public void run() { runAfter(); } public void runAfter() { if (System.getenv(NOTEARDOWN) == null) { after(); } } } /** * Check if currently executed test has @OpenShiftOnly annotation * @param context extension context * @return true or false */ private boolean isWrongClusterType(ExtensionContext context) { AnnotatedElement element = context.getElement().get(); return isWrongClusterType(element); } /** * Check if current element has @OpenShiftOnly annotation * @param element test method/test class * @return true or false */ private boolean isWrongClusterType(AnnotatedElement element) { boolean result = element.getAnnotation(OpenShiftOnly.class) != null && !(clusterResource().cluster() instanceof OpenShift || clusterResource().cluster() instanceof Minishift); if (result) { LOGGER.info("{} is @OpenShiftOnly, but the running cluster is not OpenShift: Ignoring {}", name(testClass), name(element) ); } return result; } private void saveTestingClassInfo(ExtensionContext context) { testClass = context.getTestClass().orElse(null); declaredTags = context.getTags(); enabledTags = getEnabledTags(); } /** * Checks if some method of current test class is enabled. * @param context test context * @return true or false */ private boolean areAllChildrenIgnored(ExtensionContext context) { if (enabledTags.isEmpty()) { LOGGER.info("Test class {} with tags {} does not have any tag restrictions by tags: {}", context.getDisplayName(), declaredTags, enabledTags); return false; } else { if (CollectionUtils.containsAny(enabledTags, declaredTags) || declaredTags.isEmpty()) { LOGGER.info("Test class {} with tags {} does not have any tag restrictions by tags: {}. Checking method tags ...", context.getDisplayName(), declaredTags, enabledTags); for (Method method : testClass.getDeclaredMethods()) { if (method.getAnnotation(Test.class) == null) { continue; } if (!isWrongClusterType(method) && !isIgnoredByTag(method)) { LOGGER.info("One of the test group {} is enabled for test: {} with tags {} in class: {}", enabledTags, method.getName(), declaredTags, context.getDisplayName()); return false; } } } } LOGGER.info("None test from class {} is enabled for tags {}", context.getDisplayName(), enabledTags); return true; } /** * Check if passed element is ignored by set tags. * @param context extension context * @return true or false */ private boolean isIgnoredByTag(ExtensionContext context) { AnnotatedElement element = context.getElement().get(); return isIgnoredByTag(element); } /** * Check if passed element is ignored by set tags. * @param element test method or class * @return true or false */ private boolean isIgnoredByTag(AnnotatedElement element) { Tag[] annotations = element.getDeclaredAnnotationsByType(Tag.class); if (annotations.length == 0 || enabledTags.isEmpty()) { LOGGER.info("Test method {} is not ignored by tag", ((Method) element).getName()); return false; } for (Tag annotation : annotations) { if (enabledTags.contains(annotation.value())) { LOGGER.info("Test method {} is not ignored by tag: {}", ((Method) element).getName(), annotation.value()); return false; } } LOGGER.info("Test method {} is ignored by tag", ((Method) element).getName()); return true; } /** * Get the value of the @ClassRule-annotated KubeClusterResource field */ private KubeClusterResource clusterResource() { if (clusterResource == null) { try { Field field = testClass.getField("cluster"); clusterResource = (KubeClusterResource) field.get(KubeClusterResource.class); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } if (clusterResource == null) { clusterResource = new KubeClusterResource(); clusterResource.before(); } } return clusterResource; } private static Collection<String> getEnabledTags() { return splitProperties((String) System.getProperties().getOrDefault(TAG_LIST_NAME, DEFAULT_TAG)); } private static Collection<String> splitProperties(String commaSeparated) { if (commaSeparated == null || commaSeparated.trim().isEmpty()) { return Collections.emptySet(); } return new HashSet<>(Arrays.asList(commaSeparated.split(",+"))); } protected KubeClient<?> kubeClient() { return clusterResource().client(); } protected HelmClient helmClient() { return clusterResource().helmClient(); } class ResourceAction<T extends ResourceAction<T>> implements Supplier<Consumer<Throwable>> { protected List<Consumer<Throwable>> list = new ArrayList<>(); public ResourceAction getResources(ResourceMatcher resources) { list.add(new DescribeErrorAction(resources)); return this; } public ResourceAction getResources(String kind, String pattern) { return getResources(new ResourceMatcher(kind, pattern)); } public ResourceAction getPo() { return getPo(".*"); } public ResourceAction getPo(String pattern) { return getResources(new ResourceMatcher("pod", pattern)); } public ResourceAction getDep() { return getDep(".*"); } public ResourceAction getDep(String pattern) { return getResources(new ResourceMatcher("deployment", pattern)); } public ResourceAction getSs() { return getSs(".*"); } public ResourceAction getSs(String pattern) { return getResources(new ResourceMatcher("statefulset", pattern)); } /** * Gets a result. * * @return a result */ @Override public Consumer<Throwable> get() { return t -> { for (Consumer<Throwable> x : list) { x.accept(t); } }; } } class ResourceName { public final String kind; public final String name; public ResourceName(String kind, String name) { this.kind = kind; this.name = name; } } class ResourceMatcher implements Supplier<List<ResourceName>> { public final String kind; public final String namePattern; public ResourceMatcher(String kind, String namePattern) { this.kind = kind; this.namePattern = namePattern; } @Override public List<ResourceName> get() { return kubeClient().list(kind).stream() .filter(name -> name.matches(namePattern)) .map(name -> new ResourceName(kind, name)) .collect(Collectors.toList()); } } class DescribeErrorAction implements Consumer<Throwable> { private final Supplier<List<ResourceName>> resources; public DescribeErrorAction(Supplier<List<ResourceName>> resources) { this.resources = resources; } @Override public void accept(Throwable t) { for (ResourceName resource : resources.get()) { LOGGER.info("Description of {} '{}':{}{}", resource.kind, resource.name, System.lineSeparator(), indent(kubeClient().getResourceAsYaml(resource.kind, resource.name))); } } } /** * Get the (possibly @Repeatable) annotations on the given element. * * @param annotatedElement test method, class or field * @param annotationType annotation type * @return list of element's annotations */ @SuppressWarnings("unchecked") private <A extends Annotation> List<A> annotations(AnnotatedElement annotatedElement, Class<A> annotationType) { final List<A> list; A annotation = annotatedElement.getAnnotation(annotationType); if (annotation != null) { list = singletonList(annotation); } else { A[] annotations = annotatedElement.getAnnotationsByType(annotationType); if (annotations.length != 0) { list = asList(annotations); } else { list = emptyList(); } } return list; } /** * ClusterOperator annotation handler */ private Statement withClusterOperator(AnnotatedElement element, Statement statement) { Statement last = statement; for (ClusterOperator cc : annotations(element, ClusterOperator.class)) { boolean useHelmChart = cc.useHelmChart() || Boolean.parseBoolean(System.getProperty("useHelmChart", Boolean.FALSE.toString())); if (useHelmChart) { last = installOperatorFromHelmChart(element, last, cc); } else { last = installOperatorFromExamples(element, last, cc); } } return last; } /** * Namespace annotation handler */ private Statement withNamespaces(AnnotatedElement element, Statement statement) { Statement last = statement; for (Namespace namespace : annotations(element, Namespace.class)) { last = new Bracket(last, null) { String previousNamespace = null; @Override protected void before() { LOGGER.info("Creating namespace '{}' before test per @Namespace annotation on {}", namespace.value(), name(element)); kubeClient().createNamespace(namespace.value()); previousNamespace = namespace.use() ? kubeClient().namespace(namespace.value()) : kubeClient().namespace(); if (element instanceof Method) { applyMultipleNamespacesWatcher(element); } } @Override protected void after() { LOGGER.info("Deleting namespace '{}' after test per @Namespace annotation on {}", namespace.value(), name(element)); kubeClient().deleteNamespace(namespace.value()); kubeClient().namespace(previousNamespace); } }; } return last; } private void applyMultipleNamespacesWatcher(AnnotatedElement element) { List<Namespace> namespaces = annotations(element, Namespace.class); String defaultNamespace = namespaces.get(0).value(); for (Namespace namespace: namespaces) { if (namespace.value().matches(defaultNamespace)) { continue; } Map<File, String> configYamlFiles = Arrays.stream( Objects.requireNonNull(new File(CO_INSTALL_DIR).listFiles((file, name) -> name.matches("[0-9]*-RoleBinding.*"))) ).sorted().collect(Collectors.toMap(file -> file, f -> TestUtils.getContent(f, node -> { ArrayNode subjects = (ArrayNode) node.get("subjects"); ObjectNode subject = (ObjectNode) subjects.get(0); subject.put("kind", "ServiceAccount") .put("name", "strimzi-cluster-operator") .put("namespace", defaultNamespace); return TestUtils.toYamlString(node); }), (x, y) -> x, LinkedHashMap::new)); for (Map.Entry<File, String> entry : configYamlFiles.entrySet()) { LOGGER.info("Apply {} into namespace {}", entry.getKey(), namespace.value()); kubeClient().namespace(namespace.value()); kubeClient().clientWithAdmin().applyContent(entry.getValue()); } } kubeClient().namespace(defaultNamespace); } @SuppressWarnings("unchecked") private Statement installOperatorFromExamples(AnnotatedElement element, Statement last, ClusterOperator cc) { Map<File, String> yamls = Arrays.stream(new File(CO_INSTALL_DIR).listFiles()).sorted().collect(Collectors.toMap(file -> file, f -> TestUtils.getContent(f, node -> { // Change the docker org of the images in the 04-deployment.yaml if ("050-Deployment-strimzi-cluster-operator.yaml".equals(f.getName())) { ObjectNode containerNode = (ObjectNode) node.get("spec").get("template").get("spec").get("containers").get(0); containerNode.put("imagePullPolicy", IMAGE_PULL_POLICY); JsonNodeFactory factory = new JsonNodeFactory(false); ObjectNode resources = new ObjectNode(factory); ObjectNode requests = new ObjectNode(factory); requests.put("cpu", "200m").put(REQUESTS_CPU, REQUESTS_MEMORY); ObjectNode limits = new ObjectNode(factory); limits.put("cpu", "1000m").put(LIMITS_CPU, LIMITS_MEMORY); resources.set("requests", requests); resources.set("limits", limits); containerNode.replace("resources", resources); containerNode.remove("resources"); JsonNode ccImageNode = containerNode.get("image"); containerNode.put("image", TestUtils.changeOrgAndTag(ccImageNode.asText())); for (JsonNode envVar : containerNode.get("env")) { String varName = envVar.get("name").textValue(); // Replace all the default images with ones from the $DOCKER_ORG org and with the $DOCKER_TAG tag if (varName.matches("STRIMZI_DEFAULT_.*_IMAGE")) { String value = envVar.get("value").textValue(); ((ObjectNode) envVar).put("value", TestUtils.changeOrgAndTag(value)); } // Set log level if (varName.equals("STRIMZI_LOG_LEVEL")) { String logLevel = System.getenv().getOrDefault("TEST_STRIMZI_LOG_LEVEL", OPERATOR_LOG_LEVEL); ((ObjectNode) envVar).put("value", logLevel); } // Updates default values of env variables for (EnvVariables envVariable : cc.envVariables()) { if (varName.equals(envVariable.key())) { ((ObjectNode) envVar).put("value", envVariable.value()); } } if (varName.matches("STRIMZI_NAMESPACE")) { List<Namespace> namespaces = annotations(element, Namespace.class); List<String> test = new ArrayList<>(); ((ObjectNode) envVar).remove("valueFrom"); for (Namespace namespace : namespaces) { test.add(namespace.value()); } ((ObjectNode) envVar).put("value", String.join(",", test)); } } } if (f.getName().matches(".*RoleBinding.*")) { String ns = annotations(element, Namespace.class).get(0).value(); return TestUtils.changeRoleBindingSubject(f, ns); } return TestUtils.toYamlString(node); }), (x, y) -> x, LinkedHashMap::new)); last = new Bracket(last, new ResourceAction().getPo(CO_DEPLOYMENT_NAME + ".*") .getDep(CO_DEPLOYMENT_NAME)) { Stack<String> deletable = new Stack<>(); @Override protected void before() { // Here we record the state of the cluster LOGGER.info("Creating cluster operator {} before test per @ClusterOperator annotation on {}", cc, name(element)); for (Map.Entry<File, String> entry : yamls.entrySet()) { LOGGER.info("creating possibly modified version of {}", entry.getKey()); deletable.push(entry.getValue()); kubeClient().namespace(annotations(element, Namespace.class).get(0).value()); kubeClient().clientWithAdmin().applyContent(entry.getValue()); } applyMultipleNamespacesWatcher(element); kubeClient().waitForDeployment(CO_DEPLOYMENT_NAME, 1); } @Override protected void after() { LOGGER.info("Deleting cluster operator {} after test per @ClusterOperator annotation on {}", cc, name(element)); while (!deletable.isEmpty()) { kubeClient().clientWithAdmin().deleteContent(deletable.pop()); } kubeClient().waitForResourceDeletion("deployment", CO_DEPLOYMENT_NAME); } }; return last; } @SuppressWarnings("unchecked") private Statement installOperatorFromHelmChart(AnnotatedElement element, Statement last, ClusterOperator cc) { String dockerOrg = System.getenv().getOrDefault("DOCKER_ORG", STRIMZI_ORG); String dockerTag = System.getenv().getOrDefault("DOCKER_TAG", STRIMZI_TAG); Map<String, String> values = Collections.unmodifiableMap(Stream.of( entry("imageRepositoryOverride", dockerOrg), entry("imageTagOverride", dockerTag), entry("image.pullPolicy", IMAGE_PULL_POLICY), entry("resources.requests.memory", REQUESTS_MEMORY), entry("resources.requests.cpu", REQUESTS_CPU), entry("resources.limits.memory", LIMITS_MEMORY), entry("resources.limits.cpu", LIMITS_CPU), entry("logLevel", OPERATOR_LOG_LEVEL)) .collect(entriesToMap())); /* These entries aren't applied to the deployment yaml at this time */ Map<String, String> envVars = Collections.unmodifiableMap(Arrays.stream(cc.envVariables()) .map(var -> entry(String.format("env.%s", var.key()), var.value())) .collect(entriesToMap())); Map<String, String> allValues = Stream.of(values, envVars).flatMap(m -> m.entrySet().stream()) .collect(entriesToMap()); last = new Bracket(last, new ResourceAction().getPo(CO_DEPLOYMENT_NAME + ".*") .getDep(CO_DEPLOYMENT_NAME)) { @Override protected void before() { // Here we record the state of the cluster LOGGER.info("Creating cluster operator with Helm Chart {} before test per @ClusterOperator annotation on {}", cc, name(element)); Path pathToChart = new File(HELM_CHART).toPath(); String oldNamespace = kubeClient().namespace("kube-system"); InputStream helmAccountAsStream = getClass().getClassLoader().getResourceAsStream("helm/helm-service-account.yaml"); String helmServiceAccount = TestUtils.readResource(helmAccountAsStream); kubeClient().applyContent(helmServiceAccount); helmClient().init(); kubeClient().namespace(oldNamespace); helmClient().install(pathToChart, HELM_RELEASE_NAME, allValues); } @Override protected void after() { LOGGER.info("Deleting cluster operator with Helm Chart {} after test per @ClusterOperator annotation on {}", cc, name(element)); helmClient().delete(HELM_RELEASE_NAME); } }; return last; } /** * Resources annotation handler */ private Statement withResources(AnnotatedElement element, Statement statement) { Statement last = statement; for (Resources resources : annotations(element, Resources.class)) { last = new Bracket(last, null) { @Override protected void before() { // Here we record the state of the cluster LOGGER.info("Creating resources {}, before test per @Resources annotation on {}", Arrays.toString(resources.value()), name(element)); kubeClient().create(resources.value()); } private KubeClient kubeClient() { KubeClient client = StrimziExtension.this.kubeClient(); if (resources.asAdmin()) { client = client.clientWithAdmin(); } return client; } @Override protected void after() { LOGGER.info("Deleting resources {}, after test per @Resources annotation on {}", Arrays.toString(resources.value()), name(element)); // Here we verify the cluster is in the same state kubeClient().delete(resources.value()); } }; } return last; } private Statement withLogging(AnnotatedElement element, Statement statement) { return new Bracket(statement, null) { private long t0; @Override protected void before() { t0 = System.currentTimeMillis(); LOGGER.info("Starting {}", name(element)); } @Override protected void after() { LOGGER.info("Finished {}: took {}", name(element), duration(System.currentTimeMillis() - t0)); } }; } private static String duration(long millis) { long ms = millis % 1_000; long time = millis / 1_000; long minutes = time / 60; long seconds = time % 60; return minutes + "m" + seconds + "." + ms + "s"; } private String name(AnnotatedElement a) { if (a instanceof Class) { return "class " + ((Class) a).getSimpleName(); } else if (a instanceof Method) { Method method = (Method) a; return "method " + method.getDeclaringClass().getSimpleName() + "." + method.getName() + "()"; } else if (a instanceof Field) { Field field = (Field) a; return "field " + field.getDeclaringClass().getSimpleName() + "." + field.getName(); } else { return a.toString(); } } }
package org.codice.nitf.filereader; import java.text.ParseException; public class RGBColour { private byte red = 0x00; private byte green = 0x00; private byte blue = 0x00; private static final int REQUIRED_DATA_LENGTH = 3; private static final int UNSIGNED_BYTE_MASK = 0xFF; public RGBColour(final byte[] rgb) throws ParseException { if (rgb.length != REQUIRED_DATA_LENGTH) { throw new ParseException("Incorrect number of bytes in RGB constructor array", 0); } red = rgb[0]; green = rgb[1]; blue = rgb[2]; } public final byte getRed() { return red; } public final byte getGreen() { return green; } public final byte getBlue() { return blue; } @Override public final String toString() { return String.format("[0x%02x,0x%02x,0x%02x]", (int) (red & UNSIGNED_BYTE_MASK), (int) (green & UNSIGNED_BYTE_MASK), (int) (blue & UNSIGNED_BYTE_MASK)); } }
package org.dasein.cloud.google.platform; //import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import javax.annotation.Nonnull; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.ProviderContext; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.TimeWindow; import org.dasein.cloud.google.Google; import org.dasein.cloud.google.GoogleException; import org.dasein.cloud.google.GoogleMethod; import org.dasein.cloud.google.capabilities.GCERelationalDatabaseCapabilities; import org.dasein.cloud.identity.ServiceAction; import org.dasein.cloud.platform.ConfigurationParameter; import org.dasein.cloud.platform.Database; import org.dasein.cloud.platform.DatabaseBackup; import org.dasein.cloud.platform.DatabaseBackupState; import org.dasein.cloud.platform.DatabaseConfiguration; import org.dasein.cloud.platform.DatabaseEngine; import org.dasein.cloud.platform.DatabaseProduct; import org.dasein.cloud.platform.DatabaseSnapshot; import org.dasein.cloud.platform.DatabaseState; import org.dasein.cloud.platform.RelationalDatabaseCapabilities; import org.dasein.cloud.platform.RelationalDatabaseSupport; import org.dasein.cloud.util.APITrace; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.sqladmin.SQLAdmin; import com.google.api.services.sqladmin.model.BackupConfiguration; import com.google.api.services.sqladmin.model.BackupRun; import com.google.api.services.sqladmin.model.BackupRunsListResponse; import com.google.api.services.sqladmin.model.DatabaseFlags; import com.google.api.services.sqladmin.model.DatabaseInstance; import com.google.api.services.sqladmin.model.Flag; import com.google.api.services.sqladmin.model.FlagsListResponse; import com.google.api.services.sqladmin.model.InstancesDeleteResponse; import com.google.api.services.sqladmin.model.InstancesInsertResponse; import com.google.api.services.sqladmin.model.InstancesListResponse; import com.google.api.services.sqladmin.model.InstancesRestartResponse; import com.google.api.services.sqladmin.model.InstancesRestoreBackupResponse; import com.google.api.services.sqladmin.model.InstancesUpdateResponse; import com.google.api.services.sqladmin.model.LocationPreference; import com.google.api.services.sqladmin.model.OperationError; import com.google.api.services.sqladmin.model.Settings; import com.google.api.services.sqladmin.model.Tier; import com.google.api.services.sqladmin.model.TiersListResponse; public class RDS implements RelationalDatabaseSupport { static private volatile ArrayList<DatabaseEngine> engines = null; private volatile ArrayList<DatabaseProduct> databaseProducts = null; private Google provider; public RDS(Google provider) { this.provider = provider; } @Override public String[] mapServiceAction(ServiceAction action) { // TODO: implement me return new String[0]; } @Override public void alterDatabase(String providerDatabaseId, boolean applyImmediately, String productSize, int storageInGigabytes, String configurationId, String newAdminUser, String newAdminPassword, int newPort, int snapshotRetentionInDays, TimeWindow preferredMaintenanceWindow, TimeWindow preferredBackupWindow) throws CloudException, InternalException { // TODO Auto-generated method stub } @Override public String createFromScratch(String dataSourceName, DatabaseProduct product, String databaseVersion, String withAdminUser, String withAdminPassword, int hostPort) throws CloudException, InternalException { APITrace.begin(provider, "RDBMS.createFromScratch"); ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { DatabaseInstance content = new DatabaseInstance(); String newDatabaseVersion = getDefaultVersion(product.getEngine()).replaceAll("\\.", "_"); content.setInstance(dataSourceName); content.setDatabaseVersion(product.getEngine().name() + "_" + newDatabaseVersion); //content.setKind("sql#instance"); // REDUNDANT? content.setProject(ctx.getAccountNumber()); content.setRegion(ctx.getRegionId().replaceFirst("[0-9]$", "")); // Oddly setRegion needs just the base, no number after the region... // THINGS WE HAVE AND HAVE NOT USED // withAdminUser // withAdminPassword // SQLAdmin.Instances.SetRootPassword // hostPort // THINGS IT HAS AND DONT KNOW //content.setCurrentDiskSize(currentDiskSize); // long //content.setMaxDiskSize(maxDiskSize); // long //java.util.List<IpMapping> ipAddresses = new ArrayList<IpMapping>(); //ipAddresses.add(new IpMapping().setIpAddress(ipAddress)); // String //content.setIpAddresses(ipAddresses); //SslCert serverCaCert = null; //content.setServerCaCert(serverCaCert ); Settings settings = new Settings(); settings.setActivationPolicy("ALWAYS"); // ALWAYS NEVER ON_DEMAND //java.util.List<BackupConfiguration> backupConfiguration; //BackupConfiguration element; //element.set(fieldName, value); //element.setBinaryLogEnabled(binaryLogEnabled); //element.setEnabled(enabled); //element.setId(id); //element.setStartTime(startTime); //backupConfiguration.set(0, element); //settings.setBackupConfiguration(backupConfiguration); //java.util.List<DatabaseFlags> databaseFlags; //DatabaseFlags element; //element.setName("name").setValue("value"); // The name of the flag. These flags are passed at instance startup, so include both MySQL server options and MySQL system variables. Flags should be specified with underscores, not hyphens. Refer to the official MySQL documentation on server options and system variables for descriptions of what these flags do. Acceptable values are: event_scheduler on or off (Note: The event scheduler will only work reliably if the instance activationPolicy is set to ALWAYS.) general_log on or off group_concat_max_len 4..17179869184 innodb_flush_log_at_trx_commit 0..2 innodb_lock_wait_timeout 1..1073741824 log_bin_trust_function_creators on or off log_output Can be either TABLE or NONE, FILE is not supported. log_queries_not_using_indexes on or off long_query_time 0..30000000 lower_case_table_names 0..2 max_allowed_packet 16384..1073741824 read_only on or off skip_show_database on or off slow_query_log on or off wait_timeout 1..31536000 //databaseFlags.set(0, element); //settings.setDatabaseFlags(databaseFlags); //IpConfiguration ipConfiguration; //ipConfiguration.setAuthorizedNetworks(authorizedNetworks); //ipConfiguration.setRequireSsl(requireSsl); //settings.setIpConfiguration(ipConfiguration); // settings.setKind("sql#settings"); // REDUNDANT? //LocationPreference locationPreference; //locationPreference.setZone(zone); //us-centra1-a, us-central1-b //settings.setLocationPreference(locationPreference); settings.setPricingPlan("PER_USE"); // This can be either PER_USE or PACKAGE settings.setReplicationType("SYNCHRONOUS"); // This can be either ASYNCHRONOUS or SYNCHRONOUS settings.setTier("D0"); // D0 D1 D2 D4 D8 D16 D32 content.setSettings(settings); GoogleMethod method = new GoogleMethod(provider); InstancesInsertResponse response = sqlAdmin.instances().insert(ctx.getAccountNumber(), content).execute(); if (method.getRDSOperationComplete(ctx, response.getOperation(), dataSourceName)) return dataSourceName; else return null; // Should never reach here. should get an exception from getRDSOperationComplete } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new org.dasein.cloud.google.GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } finally { APITrace.end(); } } @Override public String createFromLatest(String dataSourceName, String providerDatabaseId, String productSize, String providerDataCenterId, int hostPort) throws InternalException, CloudException { // TODO Auto-generated method stub return null; } @Override public String createFromTimestamp(String dataSourceName, String providerDatabaseId, long beforeTimestamp, String productSize, String providerDataCenterId, int hostPort) throws InternalException, CloudException { // TODO Auto-generated method stub return null; } @Override public DatabaseConfiguration getConfiguration(String providerConfigurationId) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); // TODO Auto-generated method stub return null; } public Database getDatabase(String providerDatabaseId) throws CloudException, InternalException { APITrace.begin(provider, "RDBMS.getDatabase"); try { if( providerDatabaseId == null ) { return null; } Iterable<Database> dbs = listDatabases(); if (dbs != null) for( Database database : dbs) if (database != null) if( database.getProviderDatabaseId().equals(providerDatabaseId) ) return database; return null; } catch (Exception e) { throw new CloudException(e); } finally { APITrace.end(); } } @Override public Iterable<DatabaseEngine> getDatabaseEngines() throws CloudException, InternalException { APITrace.begin(provider, "RDBMS.getSupportedVersions"); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); HashMap<DatabaseEngine, Boolean> engines = new HashMap<DatabaseEngine, Boolean>(); try { FlagsListResponse flags = sqlAdmin.flags().list().execute(); for (Flag flag : flags.getItems()) { List<String> appliesTo = flag.getAppliesTo(); for (String dbNameVersion : appliesTo) { String dbBaseName = dbNameVersion.replaceFirst("_.*", ""); engines.put(DatabaseEngine.valueOf(dbBaseName), true); } } } catch( IOException e ) { throw new CloudException(e); } finally { APITrace.end(); } return engines.keySet(); } @Override public String getDefaultVersion(@Nonnull DatabaseEngine forEngine) throws CloudException, InternalException { if (forEngine == null) return null; APITrace.begin(provider, "RDBMS.getDefaultVersion"); try { Iterable<String> versions = getSupportedVersions(forEngine); for (String version : versions) return version; // just return first... } finally { APITrace.end(); } return null; } @Override public @Nonnull Iterable<String> getSupportedVersions(@Nonnull DatabaseEngine forEngine) throws CloudException, InternalException { APITrace.begin(provider, "RDBMS.getSupportedVersions"); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); HashMap<String, Boolean> versions = new HashMap<String, Boolean>(); try { FlagsListResponse flags = sqlAdmin.flags().list().execute(); for (Flag flag : flags.getItems()) { List<String> appliesTo = flag.getAppliesTo(); for (String dbNameVersion : appliesTo) versions.put(dbNameVersion.toLowerCase().replaceFirst(forEngine.toString().toLowerCase() + "_", "").replaceAll("_", "."), true); } } catch( IOException e ) { throw new CloudException(e); } finally { APITrace.end(); } return versions.keySet(); } @Override public @Nonnull Iterable<DatabaseProduct> listDatabaseProducts(@Nonnull DatabaseEngine forEngine) throws CloudException, InternalException { APITrace.begin(provider, "RDBMS.listDatabaseProducts"); ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); ArrayList<DatabaseProduct> products = new ArrayList<DatabaseProduct>(); try { TiersListResponse tierList = sqlAdmin.tiers().list(ctx.getAccountNumber()).execute(); List<Tier> tiers = tierList.getItems(); float fakeRate = 0.01f; for (Tier t : tiers) { DatabaseProduct product = null; int ramInMB = (int) ( t.getRAM() / 1048576 ); product = new DatabaseProduct(t.getTier(), ramInMB + "MB RAM"); product.setEngine(forEngine); // TODO Which to use? 1 GB = 1000000000 bytes or 1 GiB = 1073741824 bytes int sizeInGB = (int) ( t.getDiskQuota() / 1073741824 ); product.setStorageInGigabytes(sizeInGB); product.setStandardHourlyRate(fakeRate); // unknown as yet product.setStandardIoRate(fakeRate); // unknown as yet product.setStandardStorageRate(fakeRate); // unknown as yet fakeRate += 0.01f; product.setHighAvailability(false); // unknown as yet /* * Database db = getDatabase(forDatabaseId); * db.isHighAvailability() */ //t.getRegion(); // list of regions products.add(product); } } catch( Exception e ) { throw new CloudException(e); } finally { APITrace.end(); } return products; } @Deprecated public String getProviderTermForDatabase(Locale locale) { String providerTermForDatabase = null; try { providerTermForDatabase = getCapabilities().getProviderTermForDatabase(locale); } catch( Exception e ) { } // ignore return providerTermForDatabase; } @Deprecated public String getProviderTermForSnapshot(Locale locale) { String providerTermForSnapshot = null; try { providerTermForSnapshot = getCapabilities().getProviderTermForSnapshot(locale); } catch( Exception e ) { } // ignore return providerTermForSnapshot; } @Override public DatabaseSnapshot getSnapshot(String providerDbSnapshotId) throws CloudException, InternalException { return null; } @Override public boolean isSubscribed() throws CloudException, InternalException { // TODO Verify that i interpreted this correctly. return true; } @Deprecated public boolean isSupportsFirewallRules() { boolean supportsFirewallRules = false; try { supportsFirewallRules = getCapabilities().isSupportsFirewallRules(); } catch( Exception e ) { } // ignore return supportsFirewallRules; } @Deprecated public boolean isSupportsHighAvailability() throws CloudException, InternalException { /* * Database db = getDatabase(forDatabaseId); * db.isHighAvailability() */ return true; } @Deprecated public boolean isSupportsLowAvailability() throws CloudException, InternalException { boolean supportsLowAvailability = false; try { supportsLowAvailability = getCapabilities().isSupportsLowAvailability(); } catch( Exception e ) { } // ignore return supportsLowAvailability; } @Deprecated public boolean isSupportsMaintenanceWindows() { boolean supportsMaintenanceWindows = false; try { supportsMaintenanceWindows = getCapabilities().isSupportsMaintenanceWindows(); } catch( Exception e ) { } // ignore return supportsMaintenanceWindows; } @Deprecated public boolean isSupportsSnapshots() { /* * Google Cloud SQL backups are taken by using FLUSH TABLES WITH READ LOCK to create a snapshot. * This will prevent writes, typically for a few seconds. Even though the instance remains online, * and reads are unaffected, it is recommended to schedule backups during the quietest period for * your instance. If there is a pending operation at the time of the backup attempt, Google Cloud * SQL retries until the backup window is over. Operations that block backup are long-running * operations such as import, export, update (e.g., for an instance metadata change), and * restart (e.g., for an instance restart). */ boolean supportsSnapshots = false; try { supportsSnapshots = getCapabilities().isSupportsSnapshots(); } catch( Exception e ) { } // ignore return supportsSnapshots; } @Override public void addAccess(String providerDatabaseId, String sourceCidr) throws CloudException, InternalException { if (sourceCidr.matches("[0-9][0-9./]*[0-9]")) { addAccessAuthorizedNetworks(providerDatabaseId, sourceCidr); } else addAccessAuthorizedGaeApplications(providerDatabaseId, sourceCidr); } private void addAccessAuthorizedNetworks(String providerDatabaseId, String sourceCidr) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { DatabaseInstance instance = sqlAdmin.instances().get(ctx.getAccountNumber(), providerDatabaseId).execute(); Settings settings = instance.getSettings(); List<String> authorizedNetworks = settings.getIpConfiguration().getAuthorizedNetworks(); if (authorizedNetworks == null) authorizedNetworks = new ArrayList<String>(); authorizedNetworks.add(sourceCidr); settings.getIpConfiguration().setAuthorizedNetworks(authorizedNetworks); GoogleMethod method = new GoogleMethod(provider); InstancesUpdateResponse response = sqlAdmin.instances().update(ctx.getAccountNumber(), providerDatabaseId, instance).execute(); boolean result = method.getRDSOperationComplete(ctx, response.getOperation(), providerDatabaseId); } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } } public void addAccessAuthorizedGaeApplications(String providerDatabaseId, String authorizedApplication) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { DatabaseInstance instance = sqlAdmin.instances().get(ctx.getAccountNumber(), providerDatabaseId).execute(); if (instance != null) { Settings settings = instance.getSettings(); List<String> authorizedApplications = settings.getAuthorizedGaeApplications(); if (authorizedApplications == null) authorizedApplications = new ArrayList<String>(); authorizedApplications.add(authorizedApplication); settings.setAuthorizedGaeApplications(authorizedApplications); instance.setSettings(settings); GoogleMethod method = new GoogleMethod(provider); InstancesUpdateResponse response = sqlAdmin.instances().update(ctx.getAccountNumber(), providerDatabaseId, instance).execute(); boolean result = method.getRDSOperationComplete(ctx, response.getOperation(), providerDatabaseId); } } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } } @Override public void revokeAccess(String providerDatabaseId, String sourceCidr) throws CloudException, InternalException { if (sourceCidr.matches("[0-9][0-9./]*[0-9]")) { revokeAccessAuthorizedNetworks(providerDatabaseId, sourceCidr); } else revokeAccessAuthorizedGaeApplications(providerDatabaseId, sourceCidr); } private void revokeAccessAuthorizedGaeApplications(String providerDatabaseId, String deauthedApplication) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { DatabaseInstance instance = sqlAdmin.instances().get(ctx.getAccountNumber(), providerDatabaseId).execute(); if (instance != null) { Settings settings = instance.getSettings(); List<String> authorizedApplications = settings.getAuthorizedGaeApplications(); if (authorizedApplications == null) authorizedApplications = new ArrayList<String>(); authorizedApplications.remove(deauthedApplication); settings.setAuthorizedGaeApplications(authorizedApplications); instance.setSettings(settings); GoogleMethod method = new GoogleMethod(provider); InstancesUpdateResponse response = sqlAdmin.instances().update(ctx.getAccountNumber(), providerDatabaseId, instance).execute(); boolean result = method.getRDSOperationComplete(ctx, response.getOperation(), providerDatabaseId); } } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } } private void revokeAccessAuthorizedNetworks(String providerDatabaseId, String deauthedCidr) throws CloudException, InternalException{ ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { DatabaseInstance instance = sqlAdmin.instances().get(ctx.getAccountNumber(), providerDatabaseId).execute(); Settings settings = instance.getSettings(); List<String> authorizedNetworks = settings.getIpConfiguration().getAuthorizedNetworks(); if (authorizedNetworks == null) authorizedNetworks = new ArrayList<String>(); authorizedNetworks.remove(deauthedCidr); settings.getIpConfiguration().setAuthorizedNetworks(authorizedNetworks); GoogleMethod method = new GoogleMethod(provider); InstancesUpdateResponse response = sqlAdmin.instances().update(ctx.getAccountNumber(), providerDatabaseId, instance).execute(); boolean result = method.getRDSOperationComplete(ctx, response.getOperation(), providerDatabaseId); } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } } @Override public Iterable<String> listAccess(String toProviderDatabaseId) throws CloudException, InternalException { List<String> dbAccess = new ArrayList<String>(); ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { InstancesListResponse databases = sqlAdmin.instances().list(ctx.getAccountNumber()).execute(); for (DatabaseInstance db : databases.getItems()) { if (toProviderDatabaseId.equals(db.getInstance())) { List<String> tmpDbAccess = db.getSettings().getAuthorizedGaeApplications(); if (tmpDbAccess != null) dbAccess = tmpDbAccess; } List<String> networks = db.getSettings().getIpConfiguration().getAuthorizedNetworks(); if (networks != null) dbAccess.addAll(networks); } } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } return dbAccess; } @Override public Iterable<DatabaseConfiguration> listConfigurations() throws CloudException, InternalException { // TODO Auto-generated method stub return null; } @Override public Iterable<ResourceStatus> listDatabaseStatus() throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); java.util.List<DatabaseInstance> dbInstances = null; try { InstancesListResponse response = sqlAdmin.instances().list(ctx.getAccountNumber()).execute(); if ((response != null) && (!response.isEmpty()) && (response.getItems() != null)) dbInstances = response.getItems(); // null exception here? } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception ex) { throw new CloudException("Access denied. Verify GCE Credentials exist."); } for (DatabaseInstance instance : dbInstances) { ResourceStatus status = new ResourceStatus(instance.getInstance(), instance.getState()); list.add(status); } return list; } @Override public Iterable<Database> listDatabases() throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); ArrayList<Database> list = new ArrayList<Database>(); java.util.List<DatabaseInstance> resp = null; try { resp = sqlAdmin.instances().list(ctx.getAccountNumber()).execute().getItems(); // null exception here... } catch (IOException e) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception ex) { throw new CloudException("Access denied. Verify GCE Credentials exist."); } try { if (resp != null) for (DatabaseInstance d : resp) { String dummy = null; dummy = d.getProject(); // qa-project-2 dummy = d.getMaxDiskSize().toString(); // 268435456000 //d.getServerCaCert(); Settings s = d.getSettings(); //{"activationPolicy":"ON_DEMAND","backupConfiguration":[{"binaryLogEnabled":false,"enabled":false,"id":"f3b56cf1-e916-4611-971c-61b44c045698","kind":"sql#backupConfiguration","startTime":"12:00"}],"ipConfiguration":{"enabled":false},"kind":"sql#settings","pricingPlan":"PER_USE","replicationType":"SYNCHRONOUS","settingsVersion":"1","tier":"D0"} dummy = s.getActivationPolicy(); // "ON_DEMAND" //s.getAuthorizedGaeApplications(); java.util.List<BackupConfiguration> backupConfig = s.getBackupConfiguration(); for (BackupConfiguration backupConfigItem : backupConfig) { System.out.println(backupConfigItem.getId()); //f3b56cf1-e916-4611-971c-61b44c045698 System.out.println(backupConfigItem.getKind()); //sql#backupConfiguration System.out.println(backupConfigItem.getStartTime()); // 12:00 System.out.println(backupConfigItem.getBinaryLogEnabled()); // false System.out.println(backupConfigItem.getEnabled()); // false } java.util.List<DatabaseFlags> dbfl = s.getDatabaseFlags(); if (dbfl != null) for (DatabaseFlags dbflags : dbfl) { System.out.println(dbflags.getName() + " = " + dbflags.getValue()); } //s.getIpConfiguration(); LocationPreference lp = s.getLocationPreference(); if (lp != null) lp.getZone(); dummy = s.getPricingPlan(); // PER_USE or PACKAGE dummy = s.getReplicationType(); // SYNCHRONOUS dummy = s.getSettingsVersion().toString(); dummy = s.getTier(); Database database = new Database(); database.setAdminUser("root"); Long currentBytesUsed = d.getCurrentDiskSize(); if (currentBytesUsed != null) { int currentGBUsed = (int) (currentBytesUsed / 1073741824); database.setAllocatedStorageInGb(currentGBUsed); } //database.setConfiguration(configuration); //database.setCreationTimestamp(creationTimestamp); String googleDBState = d.getState(); // PENDING_CREATE if (googleDBState.equals("RUNNABLE")) { database.setCurrentState(DatabaseState.AVAILABLE); } else if (googleDBState.equals("SUSPENDED")) { database.setCurrentState(DatabaseState.SUSPENDED); } else if (googleDBState.equals("PENDING_CREATE")) { database.setCurrentState(DatabaseState.PENDING); } else if (googleDBState.equals("MAINTENANCE")) { database.setCurrentState(DatabaseState.MAINTENANCE); } else if (googleDBState.equals("UNKNOWN_STATE")) { database.setCurrentState(DatabaseState.UNKNOWN); } if (d.getDatabaseVersion().equals("MYSQL_5_5")) database.setEngine(DatabaseEngine.MYSQL); // MYSQL55 else if (d.getDatabaseVersion().equals("MYSQL_5_6")) database.setEngine(DatabaseEngine.MYSQL); // MYSQL56 //database.setHostName(d.getIpAddresses().get(0).getIpAddress()); // BARFS database.setHostPort(3306); // Default mysql port database.setName(d.getInstance()); // dsnrdbms317 database.setProductSize(s.getTier()); database.setProviderDatabaseId(d.getInstance()); // dsnrdbms317 database.setProviderOwnerId(provider.getContext().getAccountNumber()); // qa-project-2 database.setProviderRegionId(d.getRegion()); // us-central //database.setProviderDataCenterId(providerDataCenterId); //database.setHighAvailability(highAvailability); //database.setMaintenanceWindow(maintenanceWindow); //database.setRecoveryPointTimestamp(recoveryPointTimestamp); //database.setSnapshotRetentionInDays(snapshotRetentionInDays); //database.setSnapshotWindow(snapshotWindow); list.add(database); } return list; } catch (Exception e) { System.out.println("EXCEPTION " + e); e.printStackTrace(); } return null; } @Override public Collection<ConfigurationParameter> listParameters(String forProviderConfigurationId) throws CloudException, InternalException { // TODO Auto-generated method stub return null; } /* * NOTE: You cannot reuse a name for up to two months after you have deleted an instance. */ @Override public void removeDatabase(String providerDatabaseId) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { InstancesDeleteResponse response = sqlAdmin.instances().delete(ctx.getAccountNumber(), providerDatabaseId).execute(); } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } } @Override public void updateConfiguration(String providerConfigurationId, ConfigurationParameter... parameters) throws CloudException, InternalException { // TODO Auto-generated method stub } @Override public void resetConfiguration(String providerConfigurationId, String... parameters) throws CloudException, InternalException { // TODO Auto-generated method stub } @Override public void removeConfiguration(String providerConfigurationId) throws CloudException, InternalException { // TODO Auto-generated method stub } @Override public void restart(String providerDatabaseId, boolean blockUntilDone) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); try { GoogleMethod method = new GoogleMethod(provider); InstancesRestartResponse response = sqlAdmin.instances().restart(ctx.getAccountNumber(), providerDatabaseId).execute(); boolean result = method.getRDSOperationComplete(ctx, response.getOperation(), providerDatabaseId); } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { throw new CloudException(e); } } @Override public DatabaseSnapshot snapshot(String providerDatabaseId, String name) throws CloudException, InternalException { throw new InternalException("Take snapshot not supported"); } @Override public void removeSnapshot(String providerSnapshotId) throws CloudException, InternalException { throw new CloudException("Remove snapshot not supported"); } @Override public Iterable<DatabaseSnapshot> listSnapshots(String forOptionalProviderDatabaseId) throws CloudException, InternalException { ArrayList<DatabaseSnapshot> snapshots = new ArrayList<DatabaseSnapshot>(); return snapshots; // throw new CloudException("List snapshot not supported"); } @Override public String createFromSnapshot(String dataSourceName, String providerDatabaseId, String providerDbSnapshotId, String productSize, String providerDataCenterId, int hostPort) throws CloudException, InternalException { return null; } @Override public RelationalDatabaseCapabilities getCapabilities() throws InternalException, CloudException { return new GCERelationalDatabaseCapabilities(provider); } @Deprecated public Iterable<DatabaseProduct> getDatabaseProducts( DatabaseEngine forEngine ) throws CloudException, InternalException { return listDatabaseProducts(forEngine); } @Override public DatabaseBackup getUsableBackup(String providerDbId, String beforeTimestamp) throws CloudException, InternalException { // TODO candidate for cache optimizating. Iterable<DatabaseBackup> backupList = listBackups(null); for (DatabaseBackup backup : backupList) if (providerDbId.equals(backup.getProviderBackupId())) return backup; return null; } @Override public Iterable<DatabaseBackup> listBackups( String forOptionalProviderDatabaseId ) throws CloudException, InternalException { ArrayList<DatabaseBackup> backups = new ArrayList<DatabaseBackup>(); if (forOptionalProviderDatabaseId == null) { Iterable<Database> dataBases = listDatabases(); for (Database db : dataBases) backups.addAll(getBackupForDatabase(db.getProviderDatabaseId())); } else backups = getBackupForDatabase(forOptionalProviderDatabaseId); return backups; } @Override public void createFromBackup(DatabaseBackup backup, String databaseCloneToName) throws CloudException, InternalException { // TODO Auto-generated method stub } @Override public void removeBackup(DatabaseBackup backup) throws CloudException, InternalException { throw new CloudException("GCE Cloud SQL does not support deleting specific database backups."); } public ArrayList<DatabaseBackup> getBackupForDatabase(String forDatabaseId) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); ArrayList<DatabaseBackup> backups = new ArrayList<DatabaseBackup>(); Database db = getDatabase(forDatabaseId); BackupRunsListResponse backupRuns = null; try { backupRuns = sqlAdmin.backupRuns().list(ctx.getAccountNumber(), forDatabaseId, "").execute(); } catch( Exception e ) { throw new CloudException(e); } try { for (BackupRun backupItem : backupRuns.getItems()) { DatabaseBackup backup = new DatabaseBackup(); String instance = backupItem.getInstance(); backup.setProviderDatabaseId(instance); backup.setAdminUser(db.getAdminUser()); backup.setProviderOwnerId(db.getProviderOwnerId()); backup.setProviderRegionId(db.getProviderRegionId()); backup.setBackupConfiguration(backupItem.getBackupConfiguration()); backup.setDueTime(backupItem.getDueTime().toString()); backup.setEnqueuedTime(backupItem.getEnqueuedTime().toString()); String status = backupItem.getStatus(); if (status.equals("SUCCESSFUL")) { backup.setCurrentState(DatabaseBackupState.AVAILABLE); backup.setStartTime(backupItem.getStartTime().toString()); backup.setEndTime(backupItem.getEndTime().toString()); } else { backup.setCurrentState(DatabaseBackupState.valueOf(status)); // this will likely barf first time it gets caught mid backup, // but with backup windows being 4 hours... will have to wait to catch this one... } backup.setProviderBackupId(instance + "_" + backup.getDueTime()); // artificial concat of db name and timestamp OperationError error = backupItem.getError(); // null if (error != null) backup.setCurrentState(DatabaseBackupState.ERROR); // db.isHighAvailability(); // Unknown what to do with //String config = backup.getBackupConfiguration(); // 991a6ae6-17c7-48a1-8410-9807b8e3e2ad //Map<String, Object> keys = backup.getUnknownKeys(); //int retentionDays = db.getSnapshotRetentionInDays(); //String kind = backup.getKind(); // sql#backupRun //snapShot.setStorageInGigabytes(storageInGigabytes); // N.A. backups.add(backup); } } catch( Exception e ) { throw new InternalException(e); // TODO NPE if no backups present in any of the databases existing!!!! } return backups; } /* * WIP */ @Override public void restoreBackup(DatabaseBackup backup) throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); SQLAdmin sqlAdmin = provider.getGoogleSQLAdmin(); //2012-11-15T16:19:00.094Z String when = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000Z").format(new Date()); when = "2014-10-09T19:55:05.000Z"; //GoogleMethod method = new GoogleMethod(provider); InstancesRestoreBackupResponse response = null; try { String acct = ctx.getAccountNumber(); // from around line 920 // {"backupConfiguration":"4be91d6f-3ab7-4a21-b082-fad698a16cb0","dueTime":"2014-10-02T10:00:00.209Z","endTime":"2014-10-02T11:58:25.670Z","enqueuedTime":"2014-10-02T11:58:01.227Z","instance":"stateless-test-database","kind":"sql#backupRun","startTime":"2014-10-02T11:58:01.230Z","status":"SUCCESSFUL"} // {"backupConfiguration":"4be91d6f-3ab7-4a21-b082-fad698a16cb0","dueTime":"2014-10-08T10:00:00.134Z","enqueuedTime":"2014-10-08T12:08:57.283Z","instance":"stateless-test-database","kind":"sql#backupRun","status":"SKIPPED"} // only works when "status":"SUCCESSFUL" is used to feed it... response = sqlAdmin.instances().restoreBackup(acct, backup.getProviderDatabaseId(), "4be91d6f-3ab7-4a21-b082-fad698a16cb0", "2014-10-02T10:00:00.209Z").execute(); //boolean result = method.getRDSOperationComplete(ctx, response.getOperation(), providerDatabaseId); // Exception e -> The client is not authorized to make this request. } catch ( IOException e ) { if (e.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException)e; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException(e); } catch (Exception e) { System.out.println(e); } /* project Project ID of the project that contains the instance. * instance Cloud SQL instance ID. This does not include the project ID. * backupConfiguration The identifier of the backup configuration. This gets generated automatically when a backup configuration is created. * dueTime The time when this run is due to start in RFC 3339 format, for example 2012-11-15T16:19:00.094Z. */ } }
package test.http; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.net.ssl.SSLHandshakeException; import test.lib.NanoHTTPD; import winstone.Launcher; import junit.extensions.TestSetup; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import aQute.bnd.service.url.TaggedData; import aQute.lib.deployer.http.DefaultURLConnector; import aQute.lib.deployer.http.HttpBasicAuthURLConnector; import aQute.lib.io.IO; public class HttpConnectorTest extends TestCase { private static final int HTTP_PORT = 18081; private static final int HTTP_PORT_ALT = 18082; private static final int HTTPS_PORT = 18443; private static final String HTTP_URL_PREFIX = "http://127.0.0.1:" + HTTP_PORT + "/"; private static final String HTTP_URL_PREFIX_AUTH = "http://127.0.0.1:" + HTTP_PORT_ALT + "/"; private static final String HTTPS_URL_PREFIX = "https://127.0.0.1:" + HTTPS_PORT + "/"; private static final String EXPECTED_ETAG = "64035a95"; private NanoHTTPD httpd; private static Launcher launchWinstone(boolean ssl) throws Exception { Map<String, String> args = new HashMap<String, String>(); args.put("webroot", new File("testdata/winstone").getPath()); args.put("debug", "5"); if (ssl) { args.put("httpPort", "-1"); args.put("httpsPort", ""+ HTTPS_PORT); args.put("httpsKeyStore", "example.keystore"); args.put("httpsKeyStorePassword", "opensesame"); } else { args.put("httpPort", "" + HTTP_PORT_ALT); } args.put("ajp13Port", "-1"); args.put("argumentsRealm.passwd.AliBaba", "OpenSesame"); args.put("argumentsRealm.roles.AliBaba", "users"); Launcher.initLogger(args); Launcher launcher = new Launcher(args); return launcher; } public static Test suite() { TestSuite suite = new TestSuite(HttpConnectorTest.class); return new TestSetup(suite) { Launcher winstoneHttp; Launcher winstoneHttps; @Override protected void setUp() throws Exception { winstoneHttp = launchWinstone(false); winstoneHttps = launchWinstone(true); Thread.sleep(2000); } @Override protected void tearDown() throws Exception { winstoneHttp.shutdown(); winstoneHttps.shutdown(); Thread.sleep(2000); } }; } @Override protected void setUp() throws Exception { File tmpFile = File.createTempFile("cache", ".tmp"); tmpFile.deleteOnExit(); httpd = new NanoHTTPD(HTTP_PORT, new File("testdata/http")); } @Override protected void tearDown() throws Exception { httpd.stop(); } public void testConnectTagged() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); TaggedData data = connector.connectTagged(new URL(HTTP_URL_PREFIX + "bundles/dummybundle.jar")); assertNotNull("Data should be non-null because ETag not provided", data); data.getInputStream().close(); assertEquals("ETag is incorrect", EXPECTED_ETAG, data.getTag()); } public void testConnectKnownTag() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); TaggedData data = connector.connectTagged(new URL(HTTP_URL_PREFIX + "bundles/dummybundle.jar"), EXPECTED_ETAG); assertNull("Data should be null since ETag not modified.", data); } public void testConnectTagModified() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); TaggedData data = connector.connectTagged(new URL(HTTP_URL_PREFIX + "bundles/dummybundle.jar"), "00000000"); assertNotNull("Data should be non-null because ETag was different", data); data.getInputStream().close(); assertEquals("ETag is incorrect", EXPECTED_ETAG, data.getTag()); } public void testConnectHTTPS() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("disableServerVerify", "true"); connector.setProperties(config); InputStream stream = connector.connect(new URL(HTTPS_URL_PREFIX + "bundles/dummybundle.jar")); assertNotNull(stream); stream.close(); } public void testConnectHTTPSBadCerficate() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); InputStream stream = null; try { stream = connector.connect(new URL(HTTPS_URL_PREFIX + "bundles/dummybundle.jar")); fail ("Expected SSLHandsakeException"); } catch (SSLHandshakeException e) { // expected } finally { if (stream != null) IO.close(stream); } } public void testConnectTaggedHTTPS() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("disableServerVerify", "true"); connector.setProperties(config); TaggedData data = connector.connectTagged(new URL(HTTPS_URL_PREFIX + "bundles/dummybundle.jar")); assertNotNull(data); data.getInputStream().close(); } public void testConnectTaggedHTTPSBadCerficate() throws Exception { DefaultURLConnector connector = new DefaultURLConnector(); InputStream stream = null; try { connector.connectTagged(new URL(HTTPS_URL_PREFIX + "bundles/dummybundle.jar")); fail ("Expected SSLHandsakeException"); } catch (SSLHandshakeException e) { // expected } finally { if (stream != null) IO.close(stream); } } public void testConnectNoUserPass() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", ""); connector.setProperties(config); try { connector.connect(new URL(HTTP_URL_PREFIX_AUTH + "securebundles/dummybundle.jar")); fail("Should have thrown IOException due to missing auth"); } catch (IOException e) { // expected assertTrue(e.getMessage().startsWith("Server returned HTTP response code: 401")); } } public void testConnectWithUserPass() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", "testdata/http_auth.properties"); connector.setProperties(config); InputStream stream = connector.connect(new URL(HTTP_URL_PREFIX_AUTH + "securebundles/dummybundle.jar")); assertNotNull(stream); } public static void testConnectHTTPSBadCertificate() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", "testdata/http_auth.properties"); connector.setProperties(config); try { connector.connect(new URL(HTTPS_URL_PREFIX + "securebundles/dummybundle.jar")); fail ("Should have thrown error: invalid server certificate"); } catch (IOException e) { // expected assertTrue(e instanceof SSLHandshakeException); } } public static void testConnectWithUserPassHTTPS() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", "testdata/http_auth.properties"); config.put("disableServerVerify", "true"); connector.setProperties(config); try { InputStream stream = connector.connect(new URL(HTTPS_URL_PREFIX + "securebundles/dummybundle.jar")); assertNotNull(stream); } catch (Exception e) { e.printStackTrace(); throw e; } } public void testConnectWithWrongUserPass() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", "testdata/http_auth_wrong.properties"); connector.setProperties(config); try { connector.connect(new URL(HTTP_URL_PREFIX_AUTH + "securebundles/dummybundle.jar")); fail("Should have thrown IOException due to incorrect auth"); } catch (IOException e) { // expected assertTrue(e.getMessage().startsWith("Server returned HTTP response code: 401")); } } public void testConnectWithWrongUserPassHTTPS() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", "testdata/http_auth_wrong.properties"); config.put("disableServerVerify", "true"); connector.setProperties(config); try { connector.connect(new URL(HTTPS_URL_PREFIX + "securebundles/dummybundle.jar")); fail("Should have thrown IOException due to incorrect auth"); } catch (IOException e) { // expected assertTrue(e.getMessage().startsWith("Server returned HTTP response code: 401")); } } /** * Can no long do this test because Winstone doesn't support ETags */ public void XXXtestConnectWithUserPassAndTag() throws Exception { HttpBasicAuthURLConnector connector = new HttpBasicAuthURLConnector(); Map<String, String> config = new HashMap<String, String>(); config.put("configs", "testdata/http_auth.properties"); connector.setProperties(config); TaggedData data = connector.connectTagged(new URL(HTTP_URL_PREFIX_AUTH + "securebundles/dummybundle.jar"), EXPECTED_ETAG); assertNull("Data should be null because resource not modified", data); } }
package org.jenkinsci.plugins.p4; import com.perforce.p4java.exception.P4JavaException; import com.perforce.p4java.impl.generic.core.Label; import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixConfiguration; import hudson.matrix.MatrixExecutionStrategy; import hudson.matrix.MatrixProject; import hudson.model.AbstractBuild; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Node; import hudson.model.Run; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.PollingResult; import hudson.scm.RepositoryBrowser; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.scm.SCMRevisionState; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.LogTaskListener; import jenkins.model.Jenkins; import net.sf.json.JSONException; import net.sf.json.JSONObject; import org.jenkinsci.plugins.p4.browsers.P4Browser; import org.jenkinsci.plugins.p4.browsers.SwarmBrowser; import org.jenkinsci.plugins.p4.changes.P4ChangeEntry; import org.jenkinsci.plugins.p4.changes.P4ChangeParser; import org.jenkinsci.plugins.p4.changes.P4ChangeSet; import org.jenkinsci.plugins.p4.changes.P4Revision; import org.jenkinsci.plugins.p4.client.ConnectionHelper; import org.jenkinsci.plugins.p4.credentials.P4CredentialsImpl; import org.jenkinsci.plugins.p4.filters.Filter; import org.jenkinsci.plugins.p4.filters.FilterPollMasterImpl; import org.jenkinsci.plugins.p4.matrix.MatrixOptions; import org.jenkinsci.plugins.p4.populate.Populate; import org.jenkinsci.plugins.p4.review.ReviewProp; import org.jenkinsci.plugins.p4.tagging.TagAction; import org.jenkinsci.plugins.p4.tasks.CheckoutTask; import org.jenkinsci.plugins.p4.tasks.PollTask; import org.jenkinsci.plugins.p4.tasks.RemoveClientTask; import org.jenkinsci.plugins.p4.workspace.Workspace; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class PerforceScm extends SCM { private static Logger logger = Logger.getLogger(PerforceScm.class.getName()); private final String credential; private final Workspace workspace; private final List<Filter> filter; private final Populate populate; private final P4Browser browser; private transient List<Integer> changes; private transient P4Revision parentChange; private transient String changelogFilename; public String getCredential() { return credential; } public Workspace getWorkspace() { return workspace; } public List<Filter> getFilter() { return filter; } public Populate getPopulate() { return populate; } @Override public P4Browser getBrowser() { return browser; } public List<Integer> getChanges() { return changes; } /** * Create a constructor that takes non-transient fields, and add the * annotation @DataBoundConstructor to it. Using the annotation helps the * Stapler class to find which constructor that should be used when * automatically copying values from a web form to a class. * * @param credential Credential ID * @param workspace Workspace connection details * @param filter Polling filters * @param populate Populate options * @param browser Browser options */ @DataBoundConstructor public PerforceScm(String credential, Workspace workspace, List<Filter> filter, Populate populate, P4Browser browser) { this.credential = credential; this.workspace = workspace; this.filter = filter; this.populate = populate; this.browser = browser; } public PerforceScm(String credential, Workspace workspace, Populate populate) { this.credential = credential; this.workspace = workspace; this.filter = null; this.populate = populate; this.browser = null; } @Override public String getKey() { EnvVars env = new EnvVars(); String cng = env.expand("P4_CHANGELIST"); return "p4 " + workspace.getName() + cng; } @Override public RepositoryBrowser<?> guessBrowser() { try { String scmCredential = getCredential(); ConnectionHelper connection = new ConnectionHelper(scmCredential, null); String swarm = connection.getSwarm(); URL url = new URL(swarm); return new SwarmBrowser(url); } catch (MalformedURLException e) { logger.info("Unable to guess repository browser."); return null; } catch (P4JavaException e) { logger.info("Unable to access Perforce Property."); return null; } } /** * Calculate the state of the workspace of the given build. The returned * object is then fed into compareRemoteRevisionWith as the baseline * SCMRevisionState to determine if the build is necessary, and is added to * the build as an Action for later retrieval. */ @Override public SCMRevisionState calcRevisionsFromBuild(Run<?, ?> run, FilePath buildWorkspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { // A baseline is not required... but a baseline object is, so we'll // return the NONE object. return SCMRevisionState.NONE; } /** * This method does the actual polling and returns a PollingResult. The * change attribute of the PollingResult the significance of the changes * detected by this poll. */ @Override public PollingResult compareRemoteRevisionWith(Job<?, ?> job, Launcher launcher, FilePath buildWorkspace, TaskListener listener, SCMRevisionState baseline) throws IOException, InterruptedException { PollingResult state = PollingResult.NO_CHANGES; Node node = workspaceToNode(buildWorkspace); // Delay polling if build is in progress if (job.isBuilding()) { listener.getLogger().println("Build in progress, polling delayed."); return PollingResult.NO_CHANGES; } // Use Master for polling if required and set last build if (buildWorkspace == null || FilterPollMasterImpl.isMasterPolling(filter)) { Jenkins j = Jenkins.getInstance(); if (j == null) { listener.getLogger().println("Warning Jenkins instance is null."); return PollingResult.NO_CHANGES; } buildWorkspace = j.getRootPath(); // get last run, if none then build now. Run<?, ?> lastRun = job.getLastBuild(); if (lastRun == null) { listener.getLogger().println("No previous run found; building..."); return PollingResult.BUILD_NOW; } // get last action, if no previous action then build now. TagAction action = lastRun.getAction(TagAction.class); if (action == null) { listener.getLogger().println("No previous build found; building..."); return PollingResult.BUILD_NOW; } P4Revision last = action.getBuildChange(); FilterPollMasterImpl pollM = FilterPollMasterImpl.findSelf(filter); pollM.setLastChange(last); } if (job instanceof MatrixProject) { if (isBuildParent(job)) { // Poll PARENT only EnvVars envVars = job.getEnvironment(node, listener); state = pollWorkspace(envVars, listener, buildWorkspace); } else { // Poll CHILDREN only MatrixProject matrixProj = (MatrixProject) job; Collection<MatrixConfiguration> configs = matrixProj.getActiveConfigurations(); for (MatrixConfiguration config : configs) { EnvVars envVars = config.getEnvironment(node, listener); state = pollWorkspace(envVars, listener, buildWorkspace); // exit early if changes found if (state == PollingResult.BUILD_NOW) { return PollingResult.BUILD_NOW; } } } } else { EnvVars envVars = job.getEnvironment(node, listener); state = pollWorkspace(envVars, listener, buildWorkspace); } return state; } /** * Construct workspace from environment and then look for changes. * * @param envVars * @param listener * @throws InterruptedException * @throws IOException */ private PollingResult pollWorkspace(EnvVars envVars, TaskListener listener, FilePath buildWorkspace) throws InterruptedException, IOException { PrintStream log = listener.getLogger(); // set NODE_NAME to Node or default "master" if not set Node node = workspaceToNode(buildWorkspace); String nodeName = node.getNodeName(); nodeName = (nodeName.isEmpty()) ? "master" : nodeName; envVars.put("NODE_NAME", envVars.get("NODE_NAME", nodeName)); Workspace ws = (Workspace) workspace.clone(); ws.setExpand(envVars); // don't call setRootPath() here, polling is often on the master // Set EXPANDED client String client = ws.getFullName(); log.println("P4: Polling on: " + nodeName + " with:" + client); // Set EXPANDED pinned label/change String pin = populate.getPin(); if (pin != null && !pin.isEmpty()) { pin = ws.getExpand().format(pin, false); ws.getExpand().set(ReviewProp.LABEL.toString(), pin); } // Create task PollTask task = new PollTask(filter); task.setCredential(credential); task.setWorkspace(ws); task.setListener(listener); task.setLimit(pin); // Execute remote task changes = buildWorkspace.act(task); // Report changes if (!changes.isEmpty()) { return PollingResult.BUILD_NOW; } return PollingResult.NO_CHANGES; } /** * The checkout method is expected to check out modified files into the * project workspace. In Perforce terms a 'p4 sync' on the project's * workspace. Authorisation */ @Override public void checkout(Run<?, ?> run, Launcher launcher, FilePath buildWorkspace, TaskListener listener, File changelogFile, SCMRevisionState baseline) throws IOException, InterruptedException { PrintStream log = listener.getLogger(); boolean success = true; /** * JENKINS-37442: * We need to store the changelog file name for the build so that we can expose * it to the build environment */ changelogFilename = changelogFile.getAbsolutePath(); // Create task CheckoutTask task = new CheckoutTask(populate); task.setListener(listener); task.setCredential(credential); // Get workspace used for the Task Workspace ws = task.setEnvironment(run, workspace, buildWorkspace); // Set changes to build (used by polling), MUST clear after use. ws = task.setNextChange(ws, changes); changes = new ArrayList<Integer>(); // Set the Workspace and initialise task.setWorkspace(ws); task.initialise(); // Add tagging action to build, enabling label support. TagAction tag = new TagAction(run); tag.setCredential(credential); tag.setWorkspace(ws); tag.setBuildChange(task.getSyncChange()); run.addAction(tag); // Invoke build. String node = ws.getExpand().get("NODE_NAME"); Job<?, ?> job = run.getParent(); if (run instanceof MatrixBuild) { parentChange = task.getSyncChange(); if (isBuildParent(job)) { log.println("Building Parent on Node: " + node); success &= buildWorkspace.act(task); } else { listener.getLogger().println("Skipping Parent build..."); success = true; } } else { if (job instanceof MatrixProject) { if (parentChange != null) { log.println("Using parent change: " + parentChange); task.setBuildChange(parentChange); } log.println("Building Child on Node: " + node); } else { log.println("Building on Node: " + node); } success &= buildWorkspace.act(task); } // Only write change log if build succeeded and changeLogFile has been // set. if (success) { // Calculate changes prior to build (based on last build) listener.getLogger().println("P4 Task: saving built changes."); List<P4ChangeEntry> changes = calculateChanges(run, task); P4ChangeSet.store(changelogFile, changes); listener.getLogger().println("... done\n"); } else { String msg = "P4: Build failed"; logger.warning(msg); throw new AbortException(msg); } } // Get Matrix Execution options private MatrixExecutionStrategy getMatrixExecutionStrategy(Job<?, ?> job) { if (job instanceof MatrixProject) { MatrixProject matrixProj = (MatrixProject) job; return matrixProj.getExecutionStrategy(); } return null; } boolean isBuildParent(Job<?, ?> job) { MatrixExecutionStrategy matrix = getMatrixExecutionStrategy(job); if (matrix instanceof MatrixOptions) { return ((MatrixOptions) matrix).isBuildParent(); } else { // if user hasn't configured "Perforce: Matrix Options" execution // strategy, default to false return false; } } private List<P4ChangeEntry> calculateChanges(Run<?, ?> run, CheckoutTask task) { List<P4ChangeEntry> list = new ArrayList<P4ChangeEntry>(); // Look for all changes since the last build Run<?, ?> lastBuild = run.getPreviousSuccessfulBuild(); if (lastBuild != null) { TagAction lastTag = lastBuild.getAction(TagAction.class); if (lastTag != null) { P4Revision lastChange = lastTag.getBuildChange(); if (lastChange != null) { List<P4ChangeEntry> changes; changes = task.getChangesFull(lastChange); for (P4ChangeEntry c : changes) { list.add(c); } } } } // if empty, look for shelves in current build. The latest change // will not get listed as 'p4 changes n,n' will return no change if (list.isEmpty()) { P4Revision lastRevision = task.getBuildChange(); if (lastRevision != null) { List<P4ChangeEntry> changes; changes = task.getChangesFull(lastRevision); for (P4ChangeEntry c : changes) { list.add(c); } } } // still empty! No previous build, so add current if ((lastBuild == null) && list.isEmpty()) { list.add(task.getCurrentChange()); } return list; } @Override public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) { super.buildEnvVars(build, env); TagAction tagAction = build.getAction(TagAction.class); if (tagAction != null) { // Set P4_CHANGELIST value if (tagAction.getBuildChange() != null) { String change = getChangeNumber(tagAction); env.put("P4_CHANGELIST", change); } // Set P4_CLIENT workspace value if (tagAction.getClient() != null) { String client = tagAction.getClient(); env.put("P4_CLIENT", client); } // Set P4_PORT connection if (tagAction.getPort() != null) { String port = tagAction.getPort(); env.put("P4_PORT", port); } // Set P4_USER connection if (tagAction.getUser() != null) { String user = tagAction.getUser(); env.put("P4_USER", user); } // Set P4_TICKET connection Jenkins j = Jenkins.getInstance(); if (j != null) { @SuppressWarnings("unchecked") Descriptor<SCM> scm = j.getDescriptor(PerforceScm.class); DescriptorImpl p4scm = (DescriptorImpl) scm; if (tagAction.getTicket() != null && !p4scm.isHideTicket()) { String ticket = tagAction.getTicket(); env.put("P4_TICKET", ticket); } } // JENKINS-37442: Make the log file name available env.put("HUDSON_CHANGELOG_FILE", changelogFilename); } } private String getChangeNumber(TagAction tagAction) { P4Revision buildChange = tagAction.getBuildChange(); if (!buildChange.isLabel()) { // its a change, so return... return buildChange.toString(); } try { // it is really a change number, so add change... int change = Integer.parseInt(buildChange.toString()); return String.valueOf(change); } catch (NumberFormatException n) { } ConnectionHelper p4 = new ConnectionHelper(getCredential(), null); String name = buildChange.toString(); try { Label label = p4.getLabel(name); String spec = label.getRevisionSpec(); if (spec != null && !spec.isEmpty()) { if (spec.startsWith("@")) { spec = spec.substring(1); } return spec; } else { // a label, but no RevisionSpec return name; } } catch (Exception e) { // not a label return name; } finally { p4.disconnect(); } } /** * The checkout method should, besides checking out the modified files, * write a changelog.xml file that contains the changes for a certain build. * The changelog.xml file is specific for each SCM implementation, and the * createChangeLogParser returns a parser that can parse the file and return * a ChangeLogSet. */ @Override public ChangeLogParser createChangeLogParser() { return new P4ChangeParser(); } /** * Called before a workspace is deleted on the given node, to provide SCM an * opportunity to perform clean up. */ @Override public boolean processWorkspaceBeforeDeletion(Job<?, ?> job, FilePath buildWorkspace, Node node) throws IOException, InterruptedException { logger.info("processWorkspaceBeforeDeletion"); String scmCredential = getCredential(); Run<?, ?> run = job.getLastBuild(); if (run == null) { logger.warning("P4: No previous builds found"); return false; } // exit early if client workspace is undefined LogTaskListener listener = new LogTaskListener(logger, Level.INFO); EnvVars envVars = run.getEnvironment(listener); String client = envVars.get("P4_CLIENT"); if (client == null || client.isEmpty()) { logger.warning("P4: Unable to read P4_CLIENT"); return false; } // exit early if client workspace does not exist ConnectionHelper connection = new ConnectionHelper(scmCredential, null); try { if (!connection.isClient(client)) { logger.warning("P4: client not found:" + client); return false; } } catch (Exception e) { logger.warning("P4: Not able to get connection"); return false; } // Setup Cleanup Task RemoveClientTask task = new RemoveClientTask(client); task.setListener(listener); task.setCredential(credential); // Set workspace used for the Task Workspace ws = task.setEnvironment(run, workspace, buildWorkspace); task.setWorkspace(ws); boolean clean = buildWorkspace.act(task); logger.info("clean: " + clean); return clean; } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } /** * The relationship of Descriptor and SCM (the describable) is akin to class * and object. What this means is that the descriptor is used to create * instances of the describable. Usually the Descriptor is an internal class * in the SCM class named DescriptorImpl. The Descriptor should also contain * the global configuration options as fields, just like the SCM class * contains the configurations options for a job. * * @author pallen */ @Extension public static class DescriptorImpl extends SCMDescriptor<PerforceScm> { private boolean autoSave; private String credential; private String clientName; private String depotPath; private boolean deleteClient; private boolean deleteFiles; private boolean hideTicket; public boolean isAutoSave() { return autoSave; } public String getCredential() { return credential; } public String getClientName() { return clientName; } public String getDepotPath() { return depotPath; } public boolean isDeleteClient() { return deleteClient; } public boolean isDeleteFiles() { return deleteFiles; } public boolean isHideTicket() { return hideTicket; } /** * public no-argument constructor */ public DescriptorImpl() { super(PerforceScm.class, P4Browser.class); load(); } /** * Returns the name of the SCM, this is the name that will show up next * to CVS and Subversion when configuring a job. */ @Override public String getDisplayName() { return "Perforce Software"; } @Override public boolean isApplicable(Job project) { return true; } @Override public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException { PerforceScm scm = (PerforceScm) super.newInstance(req, formData); return scm; } /** * The configure method is invoked when the global configuration page is * submitted. In the method the data in the web form should be copied to * the Descriptor's fields. To persist the fields to the global * configuration XML file, the save() method must be called. Data is * defined in the global.jelly page. */ @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { try { autoSave = json.getBoolean("autoSave"); credential = json.getString("credential"); clientName = json.getString("clientName"); depotPath = json.getString("depotPath"); } catch (JSONException e) { logger.info("Unable to read Auto Version configuration."); autoSave = false; } try { deleteClient = json.getBoolean("deleteClient"); deleteFiles = json.getBoolean("deleteFiles"); } catch (JSONException e) { logger.info("Unable to read client cleanup configuration."); deleteClient = false; deleteFiles = false; } try { hideTicket = json.getBoolean("hideTicket"); } catch (JSONException e) { logger.info("Unable to read TICKET security configuration."); hideTicket = false; } save(); return true; } /** * Credentials list, a Jelly config method for a build job. * * @return A list of Perforce credential items to populate the jelly * Select list. */ public ListBoxModel doFillCredentialItems() { return P4CredentialsImpl.doFillCredentialItems(); } public FormValidation doCheckCredential(@QueryParameter String value) { return P4CredentialsImpl.doCheckCredential(value); } } /** * This methods determines if the SCM plugin can be used for polling */ @Override public boolean supportsPolling() { return true; } /** * This method should return true if the SCM requires a workspace for * polling. Perforce however can report submitted, pending and shelved * changes without needing a workspace */ @Override public boolean requiresWorkspaceForPolling() { if (FilterPollMasterImpl.isMasterPolling(filter)) { return false; } return true; } /** * Helper: find the Remote/Local Computer used for build * * @param workspace */ private static Computer workspaceToComputer(FilePath workspace) { Jenkins jenkins = Jenkins.getInstance(); if (workspace != null && workspace.isRemote()) { for (Computer computer : jenkins.getComputers()) { if (computer.getChannel() == workspace.getChannel()) { return computer; } } } return null; } /** * Helper: find the Node for slave build or return current instance. * * @param workspace */ private static Node workspaceToNode(FilePath workspace) { Computer computer = workspaceToComputer(workspace); if (computer != null) { return computer.getNode(); } Jenkins jenkins = Jenkins.getInstance(); return jenkins; } }
package experimentalcode.erich; import java.text.NumberFormat; import java.util.BitSet; import java.util.Locale; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.util.SVGConstants; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.svg.SVGDocument; import experimentalcode.erich.scales.LinearScale; public class SVGPlot { // format for serializing numbers into SVG public static final NumberFormat FMT = NumberFormat.getInstance(Locale.ROOT); static { FMT.setMaximumFractionDigits(8); } protected SVGDocument document; protected Element root; protected Element defs; BitSet definedMarkers = new BitSet(); public SVGPlot() { super(); // Get a DOMImplementation. DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation(); DocumentType dt = domImpl.createDocumentType("svg", SVGConstants.SVG_PUBLIC_ID, SVGConstants.SVG_SYSTEM_ID); // Workaround: sometimes DocumentType doesn't work right, which // causes problems with // serialization... if(dt.getName() == null) { dt = null; } document = (SVGDocument) domImpl.createDocument(SVGConstants.SVG_NAMESPACE_URI, "svg", dt); root = document.getDocumentElement(); // setup common SVG namespaces root.setAttribute("xmlns", SVGConstants.SVG_NAMESPACE_URI); root.setAttributeNS(SVGConstants.XMLNS_NAMESPACE_URI, SVGConstants.XMLNS_PREFIX + ":" + SVGConstants.XLINK_PREFIX, SVGConstants.XLINK_NAMESPACE_URI); // create element for SVG definitions defs = svgElement(document, root, "defs"); } public void drawAxis(Element parent, LinearScale scale, double w, double h) { Element line = svgElement(document, parent, "line"); line.setAttribute("x1", FMT.format(0.0)); line.setAttribute("y1", FMT.format(1.0)); line.setAttribute("x2", FMT.format(0.0 + w)); line.setAttribute("y2", FMT.format(1.0 - h)); line.setAttribute("style", "stroke:silver; stroke-width:0.2%;"); double tx = w; double ty = h; // ticks are orthogonal double tw = ty * 0.01; double th = tx * 0.01; // anchor String anchor = (w < h/2) ? "end" : "middle"; // vertical text offset; align approximately with middle instead of baseline. double textvoff = 0.007; // draw ticks on x axis for(double tick = scale.getMin(); tick <= scale.getMax(); tick += scale.getRes()) { Element tickline = svgElement(document, parent, "line"); double x = tx * scale.getScaled(tick); double y = ty * scale.getScaled(tick); tickline.setAttribute("x1", FMT.format(x - tw)); tickline.setAttribute("y1", FMT.format(1 - y - th)); tickline.setAttribute("x2", FMT.format(x + tw)); tickline.setAttribute("y2", FMT.format(1 - y + th)); tickline.setAttribute("style", "stroke:black; stroke-width:0.1%;"); Element text = svgElement(document, parent, "text"); text.setAttribute("x", FMT.format(x - tw * 2)); text.setAttribute("y", FMT.format(1 - y + th * 3 + textvoff )); text.setAttribute("style", "font-size: 0.2%"); text.setAttribute("text-anchor", anchor); text.setTextContent(scale.formatValue(tick)); } } public void drawAxis(Element parent, LinearScale scale, double x1, double y1, double x2, double y2) { Element line = svgElement(document, parent, "line"); line.setAttribute("x1", FMT.format(x1)); line.setAttribute("y1", FMT.format(- y1)); line.setAttribute("x2", FMT.format(x2)); line.setAttribute("y2", FMT.format(- y2)); line.setAttribute("style", "stroke:silver; stroke-width:0.2%;"); double tx = x2-x1; double ty = y2-y1; // ticks are orthogonal double tw = ty * 0.01; double th = tx * 0.01; // anchor String anchor = (tx < ty/2) ? "end" : "middle"; // vertical text offset; align approximately with middle instead of baseline. double textvoff = 0.007; // draw ticks on x axis for(double tick = scale.getMin(); tick <= scale.getMax(); tick += scale.getRes()) { Element tickline = svgElement(document, parent, "line"); double x = x1 + tx * scale.getScaled(tick); double y = y1 + ty * scale.getScaled(tick); tickline.setAttribute("x1", FMT.format(x - tw)); tickline.setAttribute("y1", FMT.format(- y - th)); tickline.setAttribute("x2", FMT.format(x + tw)); tickline.setAttribute("y2", FMT.format(- y + th)); tickline.setAttribute("style", "stroke:black; stroke-width:0.1%;"); Element text = svgElement(document, parent, "text"); text.setAttribute("x", FMT.format(x - tw * 2)); text.setAttribute("y", FMT.format(- y + th * 3 + textvoff )); text.setAttribute("style", "font-size: 0.2%"); text.setAttribute("text-anchor", anchor); text.setTextContent(scale.formatValue(tick)); } } public static Element svgElement(Document document, Element parent, String name) { Element neu = document.createElementNS(SVGConstants.SVG_NAMESPACE_URI, name); if (parent != null) { parent.appendChild(neu); } return neu; } public static void plotMarker(Document document, Element parent, double x, double y, int style, double size) { // TODO: add more styles. String[] colors = { "red", "blue", "green", "orange", "cyan", "magenta", "yellow" }; String colorstr = colors[style % colors.length]; switch(style % 8){ case 0: { // + cross Element line1 = svgElement(document, parent, "line"); line1.setAttribute("x1", FMT.format(x)); line1.setAttribute("y1", FMT.format(y - size / 2)); line1.setAttribute("x2", FMT.format(x)); line1.setAttribute("y2", FMT.format(y + size / 2)); line1.setAttribute("style", "stroke:" + colorstr + "; stroke-width:" + FMT.format(size / 6)); Element line2 = svgElement(document, parent, "line"); line2.setAttribute("x1", FMT.format(x - size / 2)); line2.setAttribute("y1", FMT.format(y)); line2.setAttribute("x2", FMT.format(x + size / 2)); line2.setAttribute("y2", FMT.format(y)); line2.setAttribute("style", "stroke:" + colorstr + "; stroke-width: " + FMT.format(size / 6)); break; } case 1: { // X cross Element line1 = svgElement(document, parent, "line"); line1.setAttribute("x1", FMT.format(x - size / 2)); line1.setAttribute("y1", FMT.format(y - size / 2)); line1.setAttribute("x2", FMT.format(x + size / 2)); line1.setAttribute("y2", FMT.format(y + size / 2)); line1.setAttribute("style", "stroke:" + colorstr + "; stroke-width: " + FMT.format(size / 6)); Element line2 = svgElement(document, parent, "line"); line2.setAttribute("x1", FMT.format(x - size / 2)); line2.setAttribute("y1", FMT.format(y + size / 2)); line2.setAttribute("x2", FMT.format(x + size / 2)); line2.setAttribute("y2", FMT.format(y - size / 2)); line2.setAttribute("style", "stroke:" + colorstr + "; stroke-width: " + FMT.format(size / 6)); break; } case 2: { // O filled circle Element circ = svgElement(document, parent, "circle"); circ.setAttribute("cx", FMT.format(x)); circ.setAttribute("cy", FMT.format(y)); circ.setAttribute("r", FMT.format(size / 2)); circ.setAttribute("style", "fill:" + colorstr); break; } case 3: { // [] filled rectangle Element rect = svgElement(document, parent, "rect"); rect.setAttribute("x", FMT.format(x - size / 2)); rect.setAttribute("y", FMT.format(y - size / 2)); rect.setAttribute("width", FMT.format(size)); rect.setAttribute("height", FMT.format(size)); rect.setAttribute("style", "fill:" + colorstr); break; } case 4: { // <> filled diamond Element rect = svgElement(document, parent, "rect"); rect.setAttribute("x", FMT.format(x - size / 2)); rect.setAttribute("y", FMT.format(y - size / 2)); rect.setAttribute("width", FMT.format(size)); rect.setAttribute("height", FMT.format(size)); rect.setAttribute("style", "fill:" + colorstr); rect.setAttribute("transform", "rotate(45," + FMT.format(x) + "," + FMT.format(y) + ")"); break; } case 5: { // O hollow circle Element circ = svgElement(document, parent, "circle"); circ.setAttribute("cx", FMT.format(x)); circ.setAttribute("cy", FMT.format(y)); circ.setAttribute("r", FMT.format(size / 2)); circ.setAttribute("style", "fill: none; stroke: " + colorstr + "; stroke-width: " + FMT.format(size / 6)); break; } case 6: { // [] hollow rectangle Element rect = svgElement(document, parent, "rect"); rect.setAttribute("x", FMT.format(x - size / 2)); rect.setAttribute("y", FMT.format(y - size / 2)); rect.setAttribute("width", FMT.format(size)); rect.setAttribute("height", FMT.format(size)); rect.setAttribute("style", "fill: none; stroke: " + colorstr + "; stroke-width: " + FMT.format(size / 6)); break; } case 7: { // <> hollow diamond Element rect = svgElement(document, parent, "rect"); rect.setAttribute("x", FMT.format(x - size / 2)); rect.setAttribute("y", FMT.format(y - size / 2)); rect.setAttribute("width", FMT.format(size)); rect.setAttribute("height", FMT.format(size)); rect.setAttribute("style", "fill: none; stroke: " + colorstr + "; stroke-width: " + FMT.format(size / 6)); rect.setAttribute("transform", "rotate(45," + FMT.format(x) + "," + FMT.format(y) + ")"); break; } } } public void useMarker(Element parent, double x, double y, int style, double size) { if (!definedMarkers.get(style)) { Element symbol = svgElement(document, defs, "symbol"); symbol.setAttribute("id", "s" + style); symbol.setAttribute("viewBox", "-1 -1 2 2"); plotMarker(document, symbol, 0, 0, style, 2); definedMarkers.set(style); } Element use = svgElement(document, parent, "use"); use.setAttributeNS(SVGConstants.XLINK_NAMESPACE_URI, SVGConstants.XLINK_HREF_QNAME, "#s" + style); use.setAttribute("x", FMT.format(x - size)); use.setAttribute("y", FMT.format(y - size)); use.setAttribute("width", FMT.format(size*2)); use.setAttribute("height", FMT.format(size*2)); } public SVGDocument getDocument() { return document; } }
package org.jlib.core.collections.list; import java.util.ArrayList; import org.jlib.core.collections.Collection; /** * <p> * Fixed sized array. Replacement for the standard Java arrays with special features. * </p> * <p> * The only syntactical difference to Java arrays lies in the syntax of setting and * getting objects and getting the array size: * </p> * * <pre> * {@literal * // good(?) old Java array // cool(!) new jlib Array class * String[] stringArray = new String[10]; Array<String> stringArray = new Array<String>(10); * stringArray[4] = "good(?) old Java array"; stringArray.set(4, "cool(!) new jlib Array class"); * String s = stringArray[4]; String s = stringArray.get(4); * int size = stringArray.length; int size = stringArray.size(); } * </pre> * * <p> * Special features: * </p> * <ul> * <li> Minimum and maximum index: <br/> On instantiation, you can specify the minimum and * the maximum index of the Array. Thus, no offset is necessary for Arrays starting at * other indices than 0. The following example illustrates how an Array is filled with * numbers from 1 to 10: * * <pre> * {@literal * // good(?) old Java array // cool(!) new jlib Array class * Integer[] integerArray = new Integer[10]; Array<Integer> integerArray = new Array<Integer>(1, 10); * for (int i = 1; i <= 10; i ++) for (int i = 1; i <= 10; i ++) * integerArray[i - 1] = i; integerArray.set(i, i); } * </pre> * * </li> * <li> Conformance to the Java Collections framework <br/> The class implements the * {@code java.util.Collection} interface and thus behaves like all Java Collections. * </li> * <br /> * <li> Full support for generics:<br/> The Java arrays do not support generic classes. * For example, you cannot create an array of String lists: * * <pre> * {@literal * // FORBIDDEN! * List<String>[] stringListArray = new List<String>[10]; * * // PERMITTED! * Array<List<String>> stringListArray = new Array<List<String>>(10);} * </pre> * * </li> * <li> Easy to create:<br /> * * <pre> * {@literal * // creating an Array with three Strings * Array<String> stringArray = new Array<String>("cool", "Array", "class!"); * * // creating an Array with three Strings starting at index 1 * Array<String> stringArray = new Array<String>(1, "jlib", "is", "cool!");} * </pre> * * A small problem arises if you want to create Arrays of Integers. The Java autoboxing * feature forbids the following Array creation: * * <pre> * {@literal * // FORBIDDEN! * Array<Integer> integerArray = new Array<Integer>(1, 2, 3, 4, 5, 6);} * </pre> * * The compiler claims: * * <pre> * {@literal The constructor Array<Integer>(Integer[]) is ambiguous} * </pre> * * It doesn't know whether the first parameter is meant as the minimum index of the Array * or the first Element of the list. You could pass a Java array of Integers instead which * is the equivalent to the list form for the argument {@code Integer... elements} but * this class provides an easier way: the factory methods * {@link #newIntegerArray(Integer[])} or {@link #newIntegerArrayFrom(int, Integer[])}. * The latter form takes the minimum index as first argument. * * <pre> * // possible but not handy * Array&lt;Integer&gt; integerArray = new Array&lt;Integer&gt;(new Integer[] {1, 2, 3, 4, 5, 6}); * Array&lt;Integer&gt; integerArray = new Array&lt;Integer&gt;(1, new Integer[] {1, 2, 3, 4, 5, 6}); * * // easier to use (needs the static import of the factory method(s)) * Array&lt;Integer&gt; integerArray = newIntegerArray(1, 2, 3, 4, 5); * Array&lt;Integer&gt; integerArray = newIntegerArrayFrom(1, 1, 2, 3, 4, 5); * </pre> * * </li> * </ul> * * @param <Element> * type of elements held in the List * @author Igor Akkerman */ public class Array<Element> extends AbstractEditableIndexList<Element> implements Cloneable { /** ArrayList containing the Elements of this Array */ private ArrayList<Element> backingList; /** * Creates a new empty Array. */ public Array() { super(); construct(); } public Array(int size) { super(); if (size != 0) construct(0, size - 1); else construct(); } public Array(int minIndex, int maxIndex) { super(); construct(minIndex, maxIndex); } /** * Creates a new Array containing the specified Elements. That is, the index * of the first Element of the specified list in this Array is 0. The fixed * size of this Array is the size of the specified list. * * @param elements * comma separated list of Elements to store or Java array containing * those Elements */ public Array(Element... elements) { this(0, elements); } /** * Creates a new Array containing the specified Integer Elements. That is, * the index of the first Element of the specified list in this Array is 0. * The fixed size of this Array is the size of the specified list. * * @param elements * comma separated list of Integer Elements to store or Java array * containing those Elements * @return the new Array of Integers */ public static Array<Integer> newIntegerArray(Integer... elements) { return new Array<Integer>(0, elements); } /** * Creates a new Array containing the specified Elements having a specified * minimum index. That is, the index of the first Element of the specified * list in this Array can be specified. The fixed size of this Array is the * size of the specified list. * * @param minIndex * integer specifying the minimum index of this Array * @param elements * comma separated list of Elements to store or Java array containing * those Elements */ public Array(int minIndex, Element... elements) { super(); if (elements.length != 0) construct(minIndex, minIndex + elements.length - 1); else construct(); for (int index = 0; index < elements.length; index ++) backingList.set(index, elements[index]); } /** * Creates a new Array containing the specified Integer Elements having a * specified minimum index. That is, the index of the first Element of the * specified list in this Array can be specified. The fixed size of this * Array is the size of the specified list. * * @param minIndex * integer specifying the minimum index of this Array * @param elements * comma separated list of Integer elements to store or Java array * containing those Elements * @return the new Array of Integers */ public static Array<Integer> newIntegerArrayFrom(int minIndex, Integer... elements) { return new Array<Integer>(minIndex, elements); } /** * Creates a new Array containing the Elements of the specified Collection. * The index of the first Element of the specified Collection in this Array * is 0. The fixed size of this Array is the size of the specified * Collection. * * @param collection * Collection of which the Elements are copied to this Array * @throws NullPointerException * if {@code collection} is {@code null} */ public Array(Collection<Element> collection) { this(0, collection); } /** * Creates a new Array containing the Elements of the specified Java * Collection. The index of the first Element of the specified Collection in * this Array is 0. The fixed size of this Array is the size of the * specified Collection. * * @param collection * Java Collection of which the Elements are copied to this Array * @throws NullPointerException * if {@code collection} is {@code null} */ public Array(java.util.Collection<Element> collection) { this(0, collection); } public Array(int minIndex, Collection<Element> collection) { super(); if (minIndex < 0) throw new IllegalArgumentException(); int collectionSize = collection.size(); backingList = new ArrayList<Element>(collectionSize); for (Element collectionElement : collection) backingList.add(collectionElement); this.minIndex = minIndex; this.maxIndex = minIndex + collectionSize - 1; } public Array(int minIndex, java.util.Collection<Element> collection) { super(); if (minIndex < 0) throw new IllegalArgumentException(); backingList = new ArrayList<Element>(collection); this.minIndex = minIndex; this.maxIndex = minIndex + backingList.size() - 1; } /** * Constructs this Array as empty. */ private void construct() { backingList = new ArrayList<Element>(0); minIndex = -1; maxIndex = -2; } @SuppressWarnings("hiding") private void construct(int minIndex, int maxIndex) { if (minIndex < 0 || minIndex > maxIndex) throw new IllegalArgumentException(); int size = maxIndex - minIndex + 1; backingList = new ArrayList<Element>(size); for (int index = 0; index < size; index ++) backingList.add(null); this.minIndex = minIndex; this.maxIndex = maxIndex; } // @see org.jlib.core.collections.list.IndexList#get(int) public Element get(int index) throws ListIndexOutOfBoundsException { try { return backingList.get(index - minIndex); } catch (IndexOutOfBoundsException exception) { throw new ListIndexOutOfBoundsException(index); } } // @see org.jlib.core.collections.list.EditableIndexList#set(int, java.lang.Object) public Element set(int index, Element element) throws ListIndexOutOfBoundsException { try { Element oldElement = get(index); backingList.set(index - minIndex, element); return oldElement; } catch (IndexOutOfBoundsException exception) { throw new ListIndexOutOfBoundsException(index); } } // @see org.jlib.core.collections.AbstractCollection#contains(java.lang.Object) @Override // overridden for efficiency public boolean contains(Object object) { return backingList.contains(object); } // @see org.jlib.core.collections.AbstractCollection#containsAll(org.jlib.core.collections.Collection) // overridden for efficiency @Override public boolean containsAll(java.util.Collection<?> javaCollection) { return backingList.containsAll(javaCollection); } // @see java.lang.Object#clone() @Override @SuppressWarnings("unchecked") public Object clone() throws CloneNotSupportedException { Array<Element> clonedArray = (Array<Element>) super.clone(); clonedArray.backingList = (ArrayList<Element>) backingList.clone(); return clonedArray; } // @see org.jlib.core.collections.list.IndexList#equals(java.lang.Object) @Override public boolean equals(Object otherObject) { if (!(otherObject instanceof Array<?>)) return false; Array<?> otherArray = (Array<?>) otherObject; return minIndex == otherArray.minIndex && maxIndex == otherArray.maxIndex && backingList.equals(otherArray.backingList); } }
package org.mitre.synthea.export; import static org.mitre.synthea.export.ExportHelper.nextFriday; import com.google.gson.JsonObject; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import org.mitre.synthea.helpers.SimpleCSV; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.world.agents.Payer; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.agents.Provider.ProviderType; import org.mitre.synthea.world.concepts.HealthRecord; import org.mitre.synthea.world.concepts.HealthRecord.EncounterType; import org.mitre.synthea.world.concepts.HealthRecord.Medication; /** * BlueButton 2 Exporter. */ public class BB2Exporter implements Flushable { private SynchronizedBBLineWriter beneficiary; private SynchronizedBBLineWriter beneficiaryHistory; private SynchronizedBBLineWriter outpatient; private SynchronizedBBLineWriter inpatient; private SynchronizedBBLineWriter carrier; private SynchronizedBBLineWriter prescription; private AtomicInteger claimId; // per claim per encounter private AtomicInteger claimGroupId; // per encounter private AtomicInteger pdeId; // per medication claim private List<LinkedHashMap<String, String>> carrierLookup; private stateCodeMapper stateLookup; private static final String BB2_BENE_ID = "BB2_BENE_ID"; private static final String BB2_HIC_ID = "BB2_HIC_ID"; /** * Day-Month-Year date format. */ private static final SimpleDateFormat BB2_DATE_FORMAT = new SimpleDateFormat("dd-MMM-yyyy"); /** * Get a date string in the format DD-MMM-YY from the given time stamp. */ private static String bb2DateFromTimestamp(long time) { synchronized (BB2_DATE_FORMAT) { return BB2_DATE_FORMAT.format(new Date(time)); } } /** * Create the output folder and files. Write headers to each file. */ private BB2Exporter() { claimId = new AtomicInteger(); claimGroupId = new AtomicInteger(); pdeId = new AtomicInteger(); try { String csv = Utilities.readResource("payers/carriers.csv"); if (csv.startsWith("\uFEFF")) { csv = csv.substring(1); // Removes BOM. } carrierLookup = SimpleCSV.parse(csv); } catch (IOException e) { throw new RuntimeException(e); } stateLookup = new stateCodeMapper(); try { prepareOutputFiles(); } catch (IOException e) { // wrap the exception in a runtime exception. // the singleton pattern below doesn't work if the constructor can throw // and if these do throw ioexceptions there's nothing we can do anyway throw new RuntimeException(e); } } /** * Create the output folder and files. Write headers to each file. */ final void prepareOutputFiles() throws IOException { // Clean up any existing output files if (beneficiary != null) { beneficiary.close(); } if (beneficiaryHistory != null) { beneficiaryHistory.close(); } if (inpatient != null) { inpatient.close(); } if (outpatient != null) { outpatient.close(); } if (carrier != null) { carrier.close(); } if (prescription != null) { prescription.close(); } // Initialize output files File output = Exporter.getOutputFolder("bb2", null); output.mkdirs(); Path outputDirectory = output.toPath(); File beneficiaryFile = outputDirectory.resolve("beneficiary.csv").toFile(); beneficiary = new SynchronizedBBLineWriter(beneficiaryFile); beneficiary.writeHeader(BeneficiaryFields.class); File beneficiaryHistoryFile = outputDirectory.resolve("beneficiary_history.csv").toFile(); beneficiaryHistory = new SynchronizedBBLineWriter(beneficiaryHistoryFile); beneficiaryHistory.writeHeader(BeneficiaryHistoryFields.class); File outpatientFile = outputDirectory.resolve("outpatient.csv").toFile(); outpatient = new SynchronizedBBLineWriter(outpatientFile); outpatient.writeHeader(OutpatientFields.class); File inpatientFile = outputDirectory.resolve("inpatient.csv").toFile(); inpatient = new SynchronizedBBLineWriter(inpatientFile); inpatient.writeHeader(InpatientFields.class); File carrierFile = outputDirectory.resolve("carrier.csv").toFile(); carrier = new SynchronizedBBLineWriter(carrierFile); carrier.writeHeader(CarrierFields.class); File prescriptionFile = outputDirectory.resolve("prescription.csv").toFile(); prescription = new SynchronizedBBLineWriter(prescriptionFile); prescription.writeHeader(PrescriptionFields.class); } /** * Export a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ void export(Person person, long stopTime) throws IOException { exportBeneficiary(person, stopTime); exportBeneficiaryHistory(person, stopTime); exportOutpatient(person, stopTime); exportInpatient(person, stopTime); exportCarrier(person, stopTime); exportPrescription(person, stopTime); } /** * Export a beneficiary details for single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportBeneficiary(Person person, long stopTime) throws IOException { HashMap<BeneficiaryFields, String> fieldValues = new HashMap<>(); fieldValues.put(BeneficiaryFields.DML_IND, "INSERT"); String personId = (String)person.attributes.get(Person.ID); String beneId = personId.split("-")[4]; // last segment of UUID person.attributes.put(BB2_BENE_ID, beneId); fieldValues.put(BeneficiaryFields.BENE_ID, beneId); //String hicId = personId.split("-")[0]; // first segment of UUID String hicId = person.attributes.get(Person.IDENTIFIER_SSN).toString(); hicId = hicId.replace("-","") + "A"; // hicId = SSN + letter (A means retired beneficiary but other options too). System.out.println("HIC: " + hicId); person.attributes.put(BB2_HIC_ID, hicId); fieldValues.put(BeneficiaryFields.BENE_CRNT_HIC_NUM, hicId); fieldValues.put(BeneficiaryFields.BENE_SEX_IDENT_CD, (String)person.attributes.get(Person.GENDER)); fieldValues.put(BeneficiaryFields.BENE_COUNTY_CD, (String)person.attributes.get("county")); fieldValues.put(BeneficiaryFields.STATE_CODE, (String)person.attributes.get(Person.STATE)); fieldValues.put(BeneficiaryFields.BENE_ZIP_CD, (String)person.attributes.get(Person.ZIP)); fieldValues.put(BeneficiaryFields.BENE_RACE_CD, bb2RaceCode( (String)person.attributes.get(Person.ETHNICITY), (String)person.attributes.get(Person.RACE))); fieldValues.put(BeneficiaryFields.BENE_SRNM_NAME, (String)person.attributes.get(Person.LAST_NAME)); fieldValues.put(BeneficiaryFields.BENE_GVN_NAME, (String)person.attributes.get(Person.FIRST_NAME)); long birthdate = (long) person.attributes.get(Person.BIRTHDATE); fieldValues.put(BeneficiaryFields.BENE_BIRTH_DT, bb2DateFromTimestamp(birthdate)); fieldValues.put(BeneficiaryFields.RFRNC_YR, String.valueOf(getYear(stopTime))); fieldValues.put(BeneficiaryFields.AGE, String.valueOf(ageAtEndOfYear(birthdate, stopTime))); if (person.attributes.get(Person.DEATHDATE) != null) { long deathDate = (long) person.attributes.get(Person.DEATHDATE); fieldValues.put(BeneficiaryFields.DEATH_DT, bb2DateFromTimestamp(deathDate)); } beneficiary.writeValues(BeneficiaryFields.class, fieldValues); } /** * Export a beneficiary history for single person. Assumes exportBeneficiary * was called first to set up various ID on person * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportBeneficiaryHistory(Person person, long stopTime) throws IOException { HashMap<BeneficiaryHistoryFields, String> fieldValues = new HashMap<>(); fieldValues.put(BeneficiaryHistoryFields.DML_IND, "INSERT"); String beneId = (String)person.attributes.get(BB2_BENE_ID); fieldValues.put(BeneficiaryHistoryFields.BENE_ID, beneId); String hicId = (String)person.attributes.get(BB2_HIC_ID); fieldValues.put(BeneficiaryHistoryFields.BENE_CRNT_HIC_NUM, hicId); fieldValues.put(BeneficiaryHistoryFields.BENE_SEX_IDENT_CD, (String)person.attributes.get(Person.GENDER)); long birthdate = (long) person.attributes.get(Person.BIRTHDATE); fieldValues.put(BeneficiaryHistoryFields.BENE_BIRTH_DT, bb2DateFromTimestamp(birthdate)); fieldValues.put(BeneficiaryHistoryFields.BENE_COUNTY_CD, (String)person.attributes.get("county")); fieldValues.put(BeneficiaryHistoryFields.STATE_CODE, (String)person.attributes.get(Person.STATE)); fieldValues.put(BeneficiaryHistoryFields.BENE_ZIP_CD, (String)person.attributes.get(Person.ZIP)); fieldValues.put(BeneficiaryHistoryFields.BENE_RACE_CD, bb2RaceCode( (String)person.attributes.get(Person.ETHNICITY), (String)person.attributes.get(Person.RACE))); fieldValues.put(BeneficiaryHistoryFields.BENE_SRNM_NAME, (String)person.attributes.get(Person.LAST_NAME)); fieldValues.put(BeneficiaryHistoryFields.BENE_GVN_NAME, (String)person.attributes.get(Person.FIRST_NAME)); beneficiaryHistory.writeValues(BeneficiaryHistoryFields.class, fieldValues); } /** * Get the year of a point in time. * @param time point in time specified as number of milliseconds since the epoch * @return the year as a four figure value, e.g. 1971 */ private static int getYear(long time) { return 1900 + new Date(time).getYear(); } /** * Calculate the age of a person at the end of the year of a reference point in time. * @param birthdate a person's birthdate specified as number of milliseconds since the epoch * @param stopTime a reference point in time specified as number of milliseconds since the epoch * @return the person's age */ private static int ageAtEndOfYear(long birthdate, long stopTime) { return getYear(stopTime) - getYear(birthdate); } /** * Export outpatient claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportOutpatient(Person person, long stopTime) throws IOException { HashMap<OutpatientFields, String> fieldValues = new HashMap<>(); for (HealthRecord.Encounter encounter : person.record.encounters) { boolean isAmbulatory = encounter.type.equals(EncounterType.AMBULATORY.toString()); boolean isOutpatient = encounter.type.equals(EncounterType.OUTPATIENT.toString()); boolean isUrgent = encounter.type.equals(EncounterType.URGENTCARE.toString()); boolean isWellness = encounter.type.equals(EncounterType.WELLNESS.toString()); boolean isPrimary = (ProviderType.PRIMARY == encounter.provider.type); int claimId = this.claimId.incrementAndGet(); int claimGroupId = this.claimGroupId.incrementAndGet(); if (isPrimary || !(isAmbulatory || isOutpatient || isUrgent || isWellness)) { continue; } fieldValues.clear(); // The REQUIRED fields fieldValues.put(OutpatientFields.DML_IND, "INSERT"); fieldValues.put(OutpatientFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(OutpatientFields.CLM_ID, "" + claimId); fieldValues.put(OutpatientFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(OutpatientFields.FINAL_ACTION, "F"); fieldValues.put(OutpatientFields.NCH_NEAR_LINE_REC_IDENT_CD, "W"); // W=outpatient fieldValues.put(OutpatientFields.NCH_CLM_TYPE_CD, "40"); // 40=outpatient fieldValues.put(OutpatientFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(OutpatientFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(OutpatientFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(nextFriday(encounter.stop))); fieldValues.put(OutpatientFields.CLAIM_QUERY_CODE, "3"); // 1=Interim, 3=Final, 5=Debit fieldValues.put(OutpatientFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(OutpatientFields.CLM_FAC_TYPE_CD, "1"); // 1=Hospital, 2=SNF, 7=Dialysis fieldValues.put(OutpatientFields.CLM_SRVC_CLSFCTN_TYPE_CD, "3"); // depends on value of above fieldValues.put(OutpatientFields.CLM_FREQ_CD, "1"); // 1=Admit-Discharge, 9=Final fieldValues.put(OutpatientFields.CLM_PMT_AMT, "" + encounter.claim.getTotalClaimCost()); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(OutpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(OutpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, "" + encounter.claim.getCoveredCost()); } //fieldValues.put(OutpatientFields.PRVDR_STATE_CD, encounter.provider.state); String state_code = stateLookup.getStateCode(encounter.provider.state); System.out.println("StateCD: " + state_code); fieldValues.put(OutpatientFields.PRVDR_STATE_CD, state_code); // PTNT_DSCHRG_STUS_CD: 1=home, 2=transfer, 3=SNF, 20=died, 30=still here String field = null; if (encounter.ended) { field = "1"; } else { field = "30"; // the patient is still here } if (!person.alive(encounter.stop)) { field = "20"; // the patient died before the encounter ended } fieldValues.put(OutpatientFields.PTNT_DSCHRG_STUS_CD, field); fieldValues.put(OutpatientFields.CLM_TOT_CHRG_AMT, "" + encounter.claim.getTotalClaimCost()); // TODO required in the mapping, but not in the Enum // fieldValues.put(OutpatientFields.CLM_IP_ADMSN_TYPE_CD, null); // fieldValues.put(OutpatientFields.CLM_PASS_THRU_PER_DIEM_AMT, null); // fieldValues.put(OutpatientFields.NCH_BENE_IP_DDCTBL_AMT, null); // fieldValues.put(OutpatientFields.NCH_BENE_PTA_COINSRNC_LBLTY_AM, null); fieldValues.put(OutpatientFields.NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, "0"); fieldValues.put(OutpatientFields.NCH_PROFNL_CMPNT_CHRG_AMT, "4"); // fixed $ amount? // TODO required in the mapping, but not in the Enum // fieldValues.put(OutpatientFields.NCH_IP_NCVRD_CHRG_AMT, null); // fieldValues.put(OutpatientFields.NCH_IP_TOT_DDCTN_AMT, null); // fieldValues.put(OutpatientFields.CLM_UTLZTN_DAY_CNT, null); // fieldValues.put(OutpatientFields.BENE_TOT_COINSRNC_DAYS_CNT, null); // fieldValues.put(OutpatientFields.CLM_NON_UTLZTN_DAYS_CNT, null); // fieldValues.put(OutpatientFields.NCH_BLOOD_PNTS_FRNSHD_QTY, null); // fieldValues.put(OutpatientFields.CLM_DRG_OUTLIER_STAY_CD, null); fieldValues.put(OutpatientFields.CLM_LINE_NUM, "1"); fieldValues.put(OutpatientFields.REV_CNTR, "0001"); // total charge, lots of alternatives fieldValues.put(OutpatientFields.REV_CNTR_UNIT_CNT, "0"); fieldValues.put(OutpatientFields.REV_CNTR_RATE_AMT, "0"); fieldValues.put(OutpatientFields.REV_CNTR_TOT_CHRG_AMT, "" + encounter.claim.getCoveredCost()); fieldValues.put(OutpatientFields.REV_CNTR_NCVRD_CHRG_AMT, "" + encounter.claim.getPatientCost()); outpatient.writeValues(OutpatientFields.class, fieldValues); } } /** * Export inpatient claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportInpatient(Person person, long stopTime) throws IOException { HashMap<InpatientFields, String> fieldValues = new HashMap<>(); HealthRecord.Encounter previous = null; boolean previousInpatient = false; boolean previousEmergency = false; for (HealthRecord.Encounter encounter : person.record.encounters) { boolean isInpatient = encounter.type.equals(EncounterType.INPATIENT.toString()); boolean isEmergency = encounter.type.equals(EncounterType.EMERGENCY.toString()); int claimId = this.claimId.incrementAndGet(); int claimGroupId = this.claimGroupId.incrementAndGet(); if (!(isInpatient || isEmergency)) { previous = encounter; previousInpatient = false; previousEmergency = false; continue; } fieldValues.clear(); // The REQUIRED fields fieldValues.put(InpatientFields.DML_IND, "INSERT"); fieldValues.put(InpatientFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(InpatientFields.CLM_ID, "" + claimId); fieldValues.put(InpatientFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(InpatientFields.FINAL_ACTION, "F"); // F or V fieldValues.put(InpatientFields.NCH_NEAR_LINE_REC_IDENT_CD, "V"); // V = inpatient fieldValues.put(InpatientFields.NCH_CLM_TYPE_CD, "60"); // Always 60 for inpatient claims fieldValues.put(InpatientFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(InpatientFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(InpatientFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(nextFriday(encounter.stop))); fieldValues.put(InpatientFields.CLAIM_QUERY_CODE, "3"); // 1=Interim, 3=Final, 5=Debit fieldValues.put(InpatientFields.PRVDR_NUM, encounter.provider.id); fieldValues.put(InpatientFields.CLM_FAC_TYPE_CD, "1"); // 1=Hospital, 2=SNF, 7=Dialysis fieldValues.put(InpatientFields.CLM_SRVC_CLSFCTN_TYPE_CD, "1"); // depends on value of above fieldValues.put(InpatientFields.CLM_FREQ_CD, "1"); // 1=Admit-Discharge, 9=Final fieldValues.put(InpatientFields.CLM_PMT_AMT, "" + encounter.claim.getTotalClaimCost()); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(InpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, "0"); } else { fieldValues.put(InpatientFields.NCH_PRMRY_PYR_CLM_PD_AMT, "" + encounter.claim.getCoveredCost()); } fieldValues.put(InpatientFields.PRVDR_STATE_CD, encounter.provider.state); fieldValues.put(InpatientFields.PRVDR_STATE_CD, stateLookup.getStateCode(encounter.provider.state)); // PTNT_DSCHRG_STUS_CD: 1=home, 2=transfer, 3=SNF, 20=died, 30=still here String field = null; if (encounter.ended) { field = "1"; // TODO 2=transfer if the next encounter is also inpatient } else { field = "30"; // the patient is still here } if (!person.alive(encounter.stop)) { field = "20"; // the patient died before the encounter ended } fieldValues.put(InpatientFields.PTNT_DSCHRG_STUS_CD, field); fieldValues.put(InpatientFields.CLM_TOT_CHRG_AMT, "" + encounter.claim.getTotalClaimCost()); if (isEmergency) { field = "1"; // emergency } else if (previousEmergency) { field = "2"; // urgent } else { field = "3"; // elective } fieldValues.put(InpatientFields.CLM_IP_ADMSN_TYPE_CD, field); fieldValues.put(InpatientFields.CLM_PASS_THRU_PER_DIEM_AMT, "10"); // fixed $ amount? fieldValues.put(InpatientFields.NCH_BENE_IP_DDCTBL_AMT, "" + encounter.claim.getDeductiblePaid()); fieldValues.put(InpatientFields.NCH_BENE_PTA_COINSRNC_LBLTY_AM, "" + encounter.claim.getCoinsurancePaid()); fieldValues.put(InpatientFields.NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, "0"); fieldValues.put(InpatientFields.NCH_PROFNL_CMPNT_CHRG_AMT, "4"); // fixed $ amount? fieldValues.put(InpatientFields.NCH_IP_NCVRD_CHRG_AMT, "" + encounter.claim.getPatientCost()); fieldValues.put(InpatientFields.NCH_IP_TOT_DDCTN_AMT, "" + encounter.claim.getPatientCost()); int days = (int) ((encounter.stop - encounter.start) / (1000 * 60 * 60 * 24)); fieldValues.put(InpatientFields.CLM_UTLZTN_DAY_CNT, "" + days); if (days > 60) { field = "" + (days - 60); } else { field = "0"; } fieldValues.put(InpatientFields.BENE_TOT_COINSRNC_DAYS_CNT, field); fieldValues.put(InpatientFields.CLM_NON_UTLZTN_DAYS_CNT, "0"); fieldValues.put(InpatientFields.NCH_BLOOD_PNTS_FRNSHD_QTY, "0"); if (days > 60) { field = "1"; // days outlier } else if (encounter.claim.getTotalClaimCost() > 100_000) { field = "2"; // cost outlier } else { field = "0"; // no outlier } fieldValues.put(InpatientFields.CLM_DRG_OUTLIER_STAY_CD, field); fieldValues.put(InpatientFields.CLM_LINE_NUM, "1"); fieldValues.put(InpatientFields.REV_CNTR, "0001"); // total charge, lots of alternatives fieldValues.put(InpatientFields.REV_CNTR_UNIT_CNT, "0"); fieldValues.put(InpatientFields.REV_CNTR_RATE_AMT, "0"); fieldValues.put(InpatientFields.REV_CNTR_TOT_CHRG_AMT, "" + encounter.claim.getCoveredCost()); fieldValues.put(InpatientFields.REV_CNTR_NCVRD_CHRG_AMT, "" + encounter.claim.getPatientCost()); previous = encounter; previousInpatient = isInpatient; previousEmergency = isEmergency; inpatient.writeValues(InpatientFields.class, fieldValues); } } /** * Export carrier claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportCarrier(Person person, long stopTime) throws IOException { HashMap<CarrierFields, String> fieldValues = new HashMap<>(); HealthRecord.Encounter previous = null; double latestHemoglobin = 0; for (HealthRecord.Encounter encounter : person.record.encounters) { boolean isPrimary = (ProviderType.PRIMARY == encounter.provider.type); int claimId = this.claimId.incrementAndGet(); int claimGroupId = this.claimGroupId.incrementAndGet(); for (HealthRecord.Observation observation : encounter.observations) { if (observation.containsCode("718-7", "http://loinc.org")) { latestHemoglobin = (double) observation.value; } } if (!isPrimary) { previous = encounter; continue; } fieldValues.clear(); // The REQUIRED fields fieldValues.put(CarrierFields.DML_IND, "INSERT"); fieldValues.put(CarrierFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(CarrierFields.CLM_ID, "" + claimId); fieldValues.put(CarrierFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(CarrierFields.FINAL_ACTION, "F"); // F or V fieldValues.put(CarrierFields.NCH_NEAR_LINE_REC_IDENT_CD, "O"); // O=physician fieldValues.put(CarrierFields.NCH_CLM_TYPE_CD, "71"); // local carrier, non-DME fieldValues.put(CarrierFields.CLM_FROM_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(CarrierFields.CLM_THRU_DT, bb2DateFromTimestamp(encounter.stop)); fieldValues.put(CarrierFields.NCH_WKLY_PROC_DT, bb2DateFromTimestamp(nextFriday(encounter.stop))); fieldValues.put(CarrierFields.CARR_CLM_ENTRY_CD, "1"); fieldValues.put(CarrierFields.CLM_DISP_CD, "01"); fieldValues.put(CarrierFields.CARR_NUM, getCarrier(encounter.provider.state, CarrierFields.CARR_NUM)); fieldValues.put(CarrierFields.CARR_CLM_PMT_DNL_CD, "1"); // 1=paid to physician fieldValues.put(CarrierFields.CLM_PMT_AMT, "" + encounter.claim.getTotalClaimCost()); if (encounter.claim.payer == Payer.getGovernmentPayer("Medicare")) { fieldValues.put(CarrierFields.CARR_CLM_PRMRY_PYR_PD_AMT, "0"); } else { fieldValues.put(CarrierFields.CARR_CLM_PRMRY_PYR_PD_AMT, "" + encounter.claim.getCoveredCost()); } fieldValues.put(CarrierFields.NCH_CLM_PRVDR_PMT_AMT, "" + encounter.claim.getTotalClaimCost()); fieldValues.put(CarrierFields.NCH_CLM_BENE_PMT_AMT, "0"); fieldValues.put(CarrierFields.NCH_CARR_CLM_SBMTD_CHRG_AMT, "" + encounter.claim.getTotalClaimCost()); fieldValues.put(CarrierFields.NCH_CARR_CLM_ALOWD_AMT, "" + encounter.claim.getCoveredCost()); fieldValues.put(CarrierFields.CARR_CLM_CASH_DDCTBL_APLD_AMT, "" + encounter.claim.getDeductiblePaid()); fieldValues.put(CarrierFields.CARR_CLM_RFRNG_PIN_NUM, encounter.provider.id); fieldValues.put(CarrierFields.LINE_NUM, "1"); fieldValues.put(CarrierFields.CARR_PRFRNG_PIN_NUM, encounter.provider.id); fieldValues.put(CarrierFields.CARR_LINE_PRVDR_TYPE_CD, "0"); fieldValues.put(CarrierFields.TAX_NUM, "" + encounter.clinician.attributes.get(Person.IDENTIFIER_SSN)); fieldValues.put(CarrierFields.CARR_LINE_RDCD_PMT_PHYS_ASTN_C, "0"); fieldValues.put(CarrierFields.LINE_SRVC_CNT, "" + encounter.claim.items.size()); fieldValues.put(CarrierFields.LINE_CMS_TYPE_SRVC_CD, "1"); fieldValues.put(CarrierFields.LINE_PLACE_OF_SRVC_CD, "11"); // 11=office fieldValues.put(CarrierFields.CARR_LINE_PRCNG_LCLTY_CD, getCarrier(encounter.provider.state, CarrierFields.CARR_LINE_PRCNG_LCLTY_CD)); fieldValues.put(CarrierFields.LINE_NCH_PMT_AMT, "" + encounter.claim.getCoveredCost()); fieldValues.put(CarrierFields.LINE_BENE_PMT_AMT, "0"); fieldValues.put(CarrierFields.LINE_PRVDR_PMT_AMT, "" + encounter.claim.getCoveredCost()); fieldValues.put(CarrierFields.LINE_BENE_PTB_DDCTBL_AMT, "" + encounter.claim.getDeductiblePaid()); fieldValues.put(CarrierFields.LINE_BENE_PRMRY_PYR_PD_AMT, "0"); fieldValues.put(CarrierFields.LINE_COINSRNC_AMT, "" + encounter.claim.getCoinsurancePaid()); fieldValues.put(CarrierFields.LINE_SBMTD_CHRG_AMT, "" + encounter.claim.getTotalClaimCost()); fieldValues.put(CarrierFields.LINE_ALOWD_CHRG_AMT, "" + encounter.claim.getCoveredCost()); // length of encounter in minutes fieldValues.put(CarrierFields.CARR_LINE_MTUS_CNT, "" + ((encounter.stop - encounter.start) / (1000 * 60))); fieldValues.put(CarrierFields.LINE_HCT_HGB_RSLT_NUM, "" + latestHemoglobin); fieldValues.put(CarrierFields.CARR_LINE_ANSTHSA_UNIT_CNT, "0"); carrier.writeValues(CarrierFields.class, fieldValues); } } /** * Export prescription claims details for a single person. * @param person the person to export * @param stopTime end time of simulation * @throws IOException if something goes wrong */ private void exportPrescription(Person person, long stopTime) throws IOException { HashMap<PrescriptionFields, String> fieldValues = new HashMap<>(); HashMap<String, Integer> fillNum = new HashMap<>(); double costs = 0; int costYear = 0; for (HealthRecord.Encounter encounter : person.record.encounters) { for (Medication medication : encounter.medications) { int pdeId = this.pdeId.incrementAndGet(); int claimGroupId = this.claimGroupId.incrementAndGet(); fieldValues.clear(); // The REQUIRED fields fieldValues.put(PrescriptionFields.DML_IND, "INSERT"); fieldValues.put(PrescriptionFields.PDE_ID, "" + pdeId); fieldValues.put(PrescriptionFields.CLM_GRP_ID, "" + claimGroupId); fieldValues.put(PrescriptionFields.FINAL_ACTION, "F"); fieldValues.put(PrescriptionFields.BENE_ID, (String) person.attributes.get(BB2_BENE_ID)); fieldValues.put(PrescriptionFields.SRVC_DT, bb2DateFromTimestamp(encounter.start)); fieldValues.put(PrescriptionFields.SRVC_PRVDR_ID_QLFYR_CD, "01"); // undefined fieldValues.put(PrescriptionFields.SRVC_PRVDR_ID, encounter.provider.id); fieldValues.put(PrescriptionFields.PRSCRBR_ID_QLFYR_CD, "01"); // undefined fieldValues.put(PrescriptionFields.PRSCRBR_ID, "" + (9_999_999_999L - encounter.clinician.identifier)); fieldValues.put(PrescriptionFields.RX_SRVC_RFRNC_NUM, "" + pdeId); // TODO this should be an NDC code, not RxNorm fieldValues.put(PrescriptionFields.PROD_SRVC_ID, medication.codes.get(0).code); // H=hmo, R=ppo, S=stand-alone, E=employer direct, X=limited income fieldValues.put(PrescriptionFields.PLAN_CNTRCT_REC_ID, ("R" + Math.abs( UUID.fromString(medication.claim.payer.uuid) .getMostSignificantBits())).substring(0, 5)); fieldValues.put(PrescriptionFields.PLAN_PBP_REC_NUM, "999"); // 0=not specified, 1=not compound, 2=compound fieldValues.put(PrescriptionFields.CMPND_CD, "0"); fieldValues.put(PrescriptionFields.DAW_PROD_SLCTN_CD, "" + (int) person.rand(0, 9)); fieldValues.put(PrescriptionFields.QTY_DSPNSD_NUM, "" + getQuantity(medication, stopTime)); fieldValues.put(PrescriptionFields.DAYS_SUPLY_NUM, "" + getDays(medication, stopTime)); Integer fill = 1; if (fillNum.containsKey(medication.codes.get(0).code)) { fill = 1 + fillNum.get(medication.codes.get(0).code); } fillNum.put(medication.codes.get(0).code, fill); fieldValues.put(PrescriptionFields.FILL_NUM, "" + fill); fieldValues.put(PrescriptionFields.DRUG_CVRG_STUS_CD, "C"); int year = Utilities.getYear(medication.start); if (year != costYear) { costYear = year; costs = 0; } costs += medication.claim.getPatientCost(); if (costs <= 4550.00) { fieldValues.put(PrescriptionFields.GDC_BLW_OOPT_AMT, "" + costs); fieldValues.put(PrescriptionFields.GDC_ABV_OOPT_AMT, "0"); } else { fieldValues.put(PrescriptionFields.GDC_BLW_OOPT_AMT, "4550.00"); fieldValues.put(PrescriptionFields.GDC_ABV_OOPT_AMT, "" + (costs - 4550)); } fieldValues.put(PrescriptionFields.PTNT_PAY_AMT, "" + medication.claim.getPatientCost()); fieldValues.put(PrescriptionFields.OTHR_TROOP_AMT, "0"); fieldValues.put(PrescriptionFields.LICS_AMT, "0"); fieldValues.put(PrescriptionFields.PLRO_AMT, "0"); fieldValues.put(PrescriptionFields.CVRD_D_PLAN_PD_AMT, "" + medication.claim.getCoveredCost()); fieldValues.put(PrescriptionFields.NCVRD_PLAN_PD_AMT, "" + medication.claim.getPatientCost()); fieldValues.put(PrescriptionFields.TOT_RX_CST_AMT, "" + medication.claim.getTotalClaimCost()); fieldValues.put(PrescriptionFields.RPTD_GAP_DSCNT_NUM, "0"); fieldValues.put(PrescriptionFields.PHRMCY_SRVC_TYPE_CD, "0" + (int) person.rand(1, 8)); // 00=not specified, 01=home, 02=SNF, 03=long-term, 11=hospice, 14=homeless if (person.attributes.containsKey("homeless") && ((Boolean) person.attributes.get("homeless") == true)) { fieldValues.put(PrescriptionFields.PTNT_RSDNC_CD, "14"); } else { fieldValues.put(PrescriptionFields.PTNT_RSDNC_CD, "01"); } prescription.writeValues(PrescriptionFields.class, fieldValues); } } } /** * Flush contents of any buffered streams to disk. * @throws IOException if something goes wrong */ @Override public void flush() throws IOException { beneficiary.flush(); beneficiaryHistory.flush(); inpatient.flush(); outpatient.flush(); carrier.flush(); prescription.flush(); } /** * Get the BB2 race code. BB2 uses a single code to represent race and ethnicity, we assume * ethnicity gets priority here. * @param ethnicity the Synthea ethnicity * @param race the Synthea race * @return the BB2 race code */ private String bb2RaceCode(String ethnicity, String race) { if ("hispanic".equals(ethnicity)) { return "5"; } else { String bbRaceCode = "0"; // unknown switch (race) { case "white": bbRaceCode = "1"; break; case "black": bbRaceCode = "2"; break; case "asian": bbRaceCode = "4"; break; case "native": bbRaceCode = "6"; break; case "other": default: bbRaceCode = "3"; break; } return bbRaceCode; } } private String getCarrier(String state, CarrierFields column) { for (LinkedHashMap<String, String> row : carrierLookup) { if (row.get("STATE").equals(state) || row.get("STATE_CODE").equals(state)) { return row.get(column.toString()); } } return "0"; } private int getQuantity(Medication medication, long stopTime) { double amountPerDay = 1; double days = getDays(medication, stopTime); if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("dosage")) { JsonObject dosage = medication.prescriptionDetails.getAsJsonObject("dosage"); long amount = dosage.get("amount").getAsLong(); long frequency = dosage.get("frequency").getAsLong(); long period = dosage.get("period").getAsLong(); String units = dosage.get("unit").getAsString(); long periodTime = Utilities.convertTime(units, period); long perPeriod = amount * frequency; amountPerDay = (double) ((double) (perPeriod * periodTime) / (1000.0 * 60 * 60 * 24)); if (amountPerDay == 0) { amountPerDay = 1; } } return (int) (amountPerDay * days); } private int getDays(Medication medication, long stopTime) { double days = 1; long stop = medication.stop; if (stop == 0L) { stop = stopTime; } long medDuration = stop - medication.start; days = (double) (medDuration / (1000 * 60 * 60 * 24)); if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("duration")) { JsonObject duration = medication.prescriptionDetails.getAsJsonObject("duration"); long quantity = duration.get("quantity").getAsLong(); String unit = duration.get("unit").getAsString(); long durationTime = Utilities.convertTime(unit, quantity); double durationTimeInDays = (double) (durationTime / (1000 * 60 * 60 * 24)); if (durationTimeInDays > days) { days = durationTimeInDays; } } return (int) days; } /** * Utility class for converting state names and abbreviations to provider state codes */ class stateCodeMapper { private HashMap<String, String> ProviderStateCodes; private Map<String, String> StateToAbbrev = this.buildStateAbbrevTable(); private Map<String, String> AbbrevToState; public stateCodeMapper(){ this.ProviderStateCodes = this.buildProviderStateTable(); this.StateToAbbrev = this.buildStateAbbrevTable(); // support two-way conversion between state name and abbreviations Map<String, String> AbbrevToState = new HashMap<String, String>(); for(Map.Entry<String, String> entry : StateToAbbrev.entrySet()){ AbbrevToState.put(entry.getValue(), entry.getKey()); } this.AbbrevToState = AbbrevToState; } /** * Return state code for a given state * @param state (either state name or abbreviation) * @return 2-digit state code */ private String getStateCode(String state){ if (state.length() == 2) { state = this.changeStateFormat(state); }else{ state = this.capitalizeWords(state); } String res = this.ProviderStateCodes.getOrDefault(state, "NONE"); return res; } /** * Switch between state name and abbreviation. If state is abbreviation, will return name, and vice versa * @param state * @return */ private String changeStateFormat(String state){ if (state.length() == 2) { return this.AbbrevToState.getOrDefault(state.toUpperCase(), null); }else{ String stateClean = this.capitalizeWords(state.toLowerCase()); return this.StateToAbbrev.getOrDefault(stateClean, null); } } private Map<String, String> buildStateAbbrevTable(){ Map<String, String> states = new HashMap<String, String>(); states.put("Alabama","AL"); states.put("Alaska","AK"); states.put("Alberta","AB"); states.put("American Samoa","AS"); states.put("Arizona","AZ"); states.put("Arkansas","AR"); states.put("Armed Forces (AE)","AE"); states.put("Armed Forces Americas","AA"); states.put("Armed Forces Pacific","AP"); states.put("British Columbia","BC"); states.put("California","CA"); states.put("Colorado","CO"); states.put("Connecticut","CT"); states.put("Delaware","DE"); states.put("District Of Columbia","DC"); states.put("Florida","FL"); states.put("Georgia","GA"); states.put("Guam","GU"); states.put("Hawaii","HI"); states.put("Idaho","ID"); states.put("Illinois","IL"); states.put("Indiana","IN"); states.put("Iowa","IA"); states.put("Kansas","KS"); states.put("Kentucky","KY"); states.put("Louisiana","LA"); states.put("Maine","ME"); states.put("Manitoba","MB"); states.put("Maryland","MD"); states.put("Massachusetts","MA"); states.put("Michigan","MI"); states.put("Minnesota","MN"); states.put("Mississippi","MS"); states.put("Missouri","MO"); states.put("Montana","MT"); states.put("Nebraska","NE"); states.put("Nevada","NV"); states.put("New Brunswick","NB"); states.put("New Hampshire","NH"); states.put("New Jersey","NJ"); states.put("New Mexico","NM"); states.put("New York","NY"); states.put("Newfoundland","NF"); states.put("North Carolina","NC"); states.put("North Dakota","ND"); states.put("Northwest Territories","NT"); states.put("Nova Scotia","NS"); states.put("Nunavut","NU"); states.put("Ohio","OH"); states.put("Oklahoma","OK"); states.put("Ontario","ON"); states.put("Oregon","OR"); states.put("Pennsylvania","PA"); states.put("Prince Edward Island","PE"); states.put("Puerto Rico","PR"); states.put("Quebec","QC"); states.put("Rhode Island","RI"); states.put("Saskatchewan","SK"); states.put("South Carolina","SC"); states.put("South Dakota","SD"); states.put("Tennessee","TN"); states.put("Texas","TX"); states.put("Utah","UT"); states.put("Vermont","VT"); states.put("Virgin Islands","VI"); states.put("Virginia","VA"); states.put("Washington","WA"); states.put("West Virginia","WV"); states.put("Wisconsin","WI"); states.put("Wyoming","WY"); states.put("Yukon Territory","YT"); return states; } private HashMap<String, String> buildProviderStateTable(){ HashMap<String, String> ProviderStateCode = new HashMap<String, String>(); ProviderStateCode.put("Alabama", "01"); ProviderStateCode.put("Alaska", "02"); ProviderStateCode.put("Arizona", "03"); ProviderStateCode.put("Arkansas", "04"); ProviderStateCode.put("California", "05"); ProviderStateCode.put("Colorado", "06"); ProviderStateCode.put("Connecticut", "07"); ProviderStateCode.put("Delaware", "08"); ProviderStateCode.put("District of Columbia", "09"); ProviderStateCode.put("Florida", "10"); ProviderStateCode.put("Georgia", "11"); ProviderStateCode.put("Hawaii", "12"); ProviderStateCode.put("Idaho", "13"); ProviderStateCode.put("Illinois", "14"); ProviderStateCode.put("Indiana", "15"); ProviderStateCode.put("Iowa", "16"); ProviderStateCode.put("Kansas", "17"); ProviderStateCode.put("Kentucky", "18"); ProviderStateCode.put("Louisiana", "19"); ProviderStateCode.put("Maine", "20"); ProviderStateCode.put("Maryland", "21"); ProviderStateCode.put("Massachusetts", "22"); ProviderStateCode.put("Michigan", "23"); ProviderStateCode.put("Minnesota", "24"); ProviderStateCode.put("Mississippi", "25"); ProviderStateCode.put("Missouri", "26"); ProviderStateCode.put("Montana", "27"); ProviderStateCode.put("Nebraska", "28"); ProviderStateCode.put("Nevada", "29"); ProviderStateCode.put("New Hampshire", "30"); ProviderStateCode.put("New Jersey", "31"); ProviderStateCode.put("New Mexico", "32"); ProviderStateCode.put("New York", "33"); ProviderStateCode.put("North Carolina", "34"); ProviderStateCode.put("North Dakota", "35"); ProviderStateCode.put("Ohio", "36"); ProviderStateCode.put("Oklahoma", "37"); ProviderStateCode.put("Oregon", "38"); ProviderStateCode.put("Pennsylvania", "39"); ProviderStateCode.put("Puerto Rico", "40"); ProviderStateCode.put("Rhode Island", "41"); ProviderStateCode.put("South Carolina", "42"); ProviderStateCode.put("South Dakota", "43"); ProviderStateCode.put("Tennessee", "44"); ProviderStateCode.put("Texas", "45"); ProviderStateCode.put("Utah", "46"); ProviderStateCode.put("Vermont", "47"); ProviderStateCode.put("Virgin Islands", "48"); ProviderStateCode.put("Virginia", "49"); ProviderStateCode.put("Washington", "50"); ProviderStateCode.put("West Virginia", "51"); ProviderStateCode.put("Wisconsin", "52"); ProviderStateCode.put("Wyoming", "53"); ProviderStateCode.put("Africa", "54"); ProviderStateCode.put("California", "55"); ProviderStateCode.put("Canada & Islands", "56"); ProviderStateCode.put("Central America and West Indies", "57"); ProviderStateCode.put("Europe", "58"); ProviderStateCode.put("Mexico", "59"); ProviderStateCode.put("Oceania", "60"); ProviderStateCode.put("Philippines", "61"); ProviderStateCode.put("South America", "62"); ProviderStateCode.put("U.S. Possessions", "63"); ProviderStateCode.put("American Samoa", "64"); ProviderStateCode.put("Guam", "65"); ProviderStateCode.put("Commonwealth of the Northern Marianas Islands", "66"); return ProviderStateCode; } private String capitalizeWords(String str){ String words[]=str.split("\\s"); String capitalizeWords=""; for(String w:words){ String first=w.substring(0,1); String afterFirst=w.substring(1); capitalizeWords+=first.toUpperCase()+afterFirst+" "; } return capitalizeWords.trim(); } } /** * Defines the fields used in the beneficiary file. Note that order is significant, columns will * be written in the order specified. */ private enum BeneficiaryFields { DML_IND, BENE_ID, STATE_CODE, BENE_COUNTY_CD, BENE_ZIP_CD, BENE_BIRTH_DT, BENE_SEX_IDENT_CD, BENE_RACE_CD, BENE_ENTLMT_RSN_ORIG, BENE_ENTLMT_RSN_CURR, BENE_ESRD_IND, BENE_MDCR_STATUS_CD, BENE_PTA_TRMNTN_CD, BENE_PTB_TRMNTN_CD, // BENE_PTD_TRMNTN_CD, // The spreadsheet has a gap for this column, examples do not include it BENE_CRNT_HIC_NUM, BENE_SRNM_NAME, BENE_GVN_NAME, BENE_MDL_NAME, MBI_NUM, DEATH_DT, RFRNC_YR, A_MO_CNT, B_MO_CNT, BUYIN_MO_CNT, HMO_MO_CNT, RDS_MO_CNT, ENRL_SRC, SAMPLE_GROUP, EFIVEPCT, CRNT_BIC, AGE, COVSTART, DUAL_MO_CNT, FIPS_STATE_CNTY_JAN_CD, FIPS_STATE_CNTY_FEB_CD, FIPS_STATE_CNTY_MAR_CD, FIPS_STATE_CNTY_APR_CD, FIPS_STATE_CNTY_MAY_CD, FIPS_STATE_CNTY_JUN_CD, FIPS_STATE_CNTY_JUL_CD, FIPS_STATE_CNTY_AUG_CD, FIPS_STATE_CNTY_SEPT_CD, FIPS_STATE_CNTY_OCT_CD, FIPS_STATE_CNTY_NOV_CD, FIPS_STATE_CNTY_DEC_CD, V_DOD_SW, RTI_RACE_CD, MDCR_STUS_JAN_CD, MDCR_STUS_FEB_CD, MDCR_STUS_MAR_CD, MDCR_STUS_APR_CD, MDCR_STUS_MAY_CD, MDCR_STUS_JUN_CD, MDCR_STUS_JUL_CD, MDCR_STUS_AUG_CD, MDCR_STUS_SEPT_CD, MDCR_STUS_OCT_CD, MDCR_STUS_NOV_CD, MDCR_STUS_DEC_CD, PLAN_CVRG_MO_CNT, MDCR_ENTLMT_BUYIN_1_IND, MDCR_ENTLMT_BUYIN_2_IND, MDCR_ENTLMT_BUYIN_3_IND, MDCR_ENTLMT_BUYIN_4_IND, MDCR_ENTLMT_BUYIN_5_IND, MDCR_ENTLMT_BUYIN_6_IND, MDCR_ENTLMT_BUYIN_7_IND, MDCR_ENTLMT_BUYIN_8_IND, MDCR_ENTLMT_BUYIN_9_IND, MDCR_ENTLMT_BUYIN_10_IND, MDCR_ENTLMT_BUYIN_11_IND, MDCR_ENTLMT_BUYIN_12_IND, HMO_1_IND, HMO_2_IND, HMO_3_IND, HMO_4_IND, HMO_5_IND, HMO_6_IND, HMO_7_IND, HMO_8_IND, HMO_9_IND, HMO_10_IND, HMO_11_IND, HMO_12_IND, PTC_CNTRCT_JAN_ID, PTC_CNTRCT_FEB_ID, PTC_CNTRCT_MAR_ID, PTC_CNTRCT_APR_ID, PTC_CNTRCT_MAY_ID, PTC_CNTRCT_JUN_ID, PTC_CNTRCT_JUL_ID, PTC_CNTRCT_AUG_ID, PTC_CNTRCT_SEPT_ID, PTC_CNTRCT_OCT_ID, PTC_CNTRCT_NOV_ID, PTC_CNTRCT_DEC_ID, PTC_PBP_JAN_ID, PTC_PBP_FEB_ID, PTC_PBP_MAR_ID, PTC_PBP_APR_ID, PTC_PBP_MAY_ID, PTC_PBP_JUN_ID, PTC_PBP_JUL_ID, PTC_PBP_AUG_ID, PTC_PBP_SEPT_ID, PTC_PBP_OCT_ID, PTC_PBP_NOV_ID, PTC_PBP_DEC_ID, PTC_PLAN_TYPE_JAN_CD, PTC_PLAN_TYPE_FEB_CD, PTC_PLAN_TYPE_MAR_CD, PTC_PLAN_TYPE_APR_CD, PTC_PLAN_TYPE_MAY_CD, PTC_PLAN_TYPE_JUN_CD, PTC_PLAN_TYPE_JUL_CD, PTC_PLAN_TYPE_AUG_CD, PTC_PLAN_TYPE_SEPT_CD, PTC_PLAN_TYPE_OCT_CD, PTC_PLAN_TYPE_NOV_CD, PTC_PLAN_TYPE_DEC_CD, PTD_CNTRCT_JAN_ID, PTD_CNTRCT_FEB_ID, PTD_CNTRCT_MAR_ID, PTD_CNTRCT_APR_ID, PTD_CNTRCT_MAY_ID, PTD_CNTRCT_JUN_ID, PTD_CNTRCT_JUL_ID, PTD_CNTRCT_AUG_ID, PTD_CNTRCT_SEPT_ID, PTD_CNTRCT_OCT_ID, PTD_CNTRCT_NOV_ID, PTD_CNTRCT_DEC_ID, PTD_PBP_JAN_ID, PTD_PBP_FEB_ID, PTD_PBP_MAR_ID, PTD_PBP_APR_ID, PTD_PBP_MAY_ID, PTD_PBP_JUN_ID, PTD_PBP_JUL_ID, PTD_PBP_AUG_ID, PTD_PBP_SEPT_ID, PTD_PBP_OCT_ID, PTD_PBP_NOV_ID, PTD_PBP_DEC_ID, PTD_SGMT_JAN_ID, PTD_SGMT_FEB_ID, PTD_SGMT_MAR_ID, PTD_SGMT_APR_ID, PTD_SGMT_MAY_ID, PTD_SGMT_JUN_ID, PTD_SGMT_JUL_ID, PTD_SGMT_AUG_ID, PTD_SGMT_SEPT_ID, PTD_SGMT_OCT_ID, PTD_SGMT_NOV_ID, PTD_SGMT_DEC_ID, RDS_JAN_IND, RDS_FEB_IND, RDS_MAR_IND, RDS_APR_IND, RDS_MAY_IND, RDS_JUN_IND, RDS_JUL_IND, RDS_AUG_IND, RDS_SEPT_IND, RDS_OCT_IND, RDS_NOV_IND, RDS_DEC_IND, META_DUAL_ELGBL_STUS_JAN_CD, META_DUAL_ELGBL_STUS_FEB_CD, META_DUAL_ELGBL_STUS_MAR_CD, META_DUAL_ELGBL_STUS_APR_CD, META_DUAL_ELGBL_STUS_MAY_CD, META_DUAL_ELGBL_STUS_JUN_CD, META_DUAL_ELGBL_STUS_JUL_CD, META_DUAL_ELGBL_STUS_AUG_CD, META_DUAL_ELGBL_STUS_SEPT_CD, META_DUAL_ELGBL_STUS_OCT_CD, META_DUAL_ELGBL_STUS_NOV_CD, META_DUAL_ELGBL_STUS_DEC_CD, CST_SHR_GRP_JAN_CD, CST_SHR_GRP_FEB_CD, CST_SHR_GRP_MAR_CD, CST_SHR_GRP_APR_CD, CST_SHR_GRP_MAY_CD, CST_SHR_GRP_JUN_CD, CST_SHR_GRP_JUL_CD, CST_SHR_GRP_AUG_CD, CST_SHR_GRP_SEPT_CD, CST_SHR_GRP_OCT_CD, CST_SHR_GRP_NOV_CD, CST_SHR_GRP_DEC_CD } private enum BeneficiaryHistoryFields { DML_IND, BENE_ID, STATE_CODE, BENE_COUNTY_CD, BENE_ZIP_CD, BENE_BIRTH_DT, BENE_SEX_IDENT_CD, BENE_RACE_CD, BENE_ENTLMT_RSN_ORIG, BENE_ENTLMT_RSN_CURR, BENE_ESRD_IND, BENE_MDCR_STATUS_CD, BENE_PTA_TRMNTN_CD, BENE_PTB_TRMNTN_CD, BENE_CRNT_HIC_NUM, BENE_SRNM_NAME, BENE_GVN_NAME, BENE_MDL_NAME, MBI_NUM } private enum OutpatientFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, CLAIM_QUERY_CODE, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, OP_PHYSN_UPIN, OP_PHYSN_NPI, OT_PHYSN_UPIN, OT_PHYSN_NPI, CLM_MCO_PD_SW, PTNT_DSCHRG_STUS_CD, CLM_TOT_CHRG_AMT, NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, NCH_PROFNL_CMPNT_CHRG_AMT, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, ICD_PRCDR_CD1, ICD_PRCDR_VRSN_CD1, PRCDR_DT1, ICD_PRCDR_CD2, ICD_PRCDR_VRSN_CD2, PRCDR_DT2, ICD_PRCDR_CD3, ICD_PRCDR_VRSN_CD3, PRCDR_DT3, ICD_PRCDR_CD4, ICD_PRCDR_VRSN_CD4, PRCDR_DT4, ICD_PRCDR_CD5, ICD_PRCDR_VRSN_CD5, PRCDR_DT5, ICD_PRCDR_CD6, ICD_PRCDR_VRSN_CD6, PRCDR_DT6, ICD_PRCDR_CD7, ICD_PRCDR_VRSN_CD7, PRCDR_DT7, ICD_PRCDR_CD8, ICD_PRCDR_VRSN_CD8, PRCDR_DT8, ICD_PRCDR_CD9, ICD_PRCDR_VRSN_CD9, PRCDR_DT9, ICD_PRCDR_CD10, ICD_PRCDR_VRSN_CD10, PRCDR_DT10, ICD_PRCDR_CD11, ICD_PRCDR_VRSN_CD11, PRCDR_DT11, ICD_PRCDR_CD12, ICD_PRCDR_VRSN_CD12, PRCDR_DT12, ICD_PRCDR_CD13, ICD_PRCDR_VRSN_CD13, PRCDR_DT13, ICD_PRCDR_CD14, ICD_PRCDR_VRSN_CD14, PRCDR_DT14, ICD_PRCDR_CD15, ICD_PRCDR_VRSN_CD15, PRCDR_DT15, ICD_PRCDR_CD16, ICD_PRCDR_VRSN_CD16, PRCDR_DT16, ICD_PRCDR_CD17, ICD_PRCDR_VRSN_CD17, PRCDR_DT17, ICD_PRCDR_CD18, ICD_PRCDR_VRSN_CD18, PRCDR_DT18, ICD_PRCDR_CD19, ICD_PRCDR_VRSN_CD19, PRCDR_DT19, ICD_PRCDR_CD20, ICD_PRCDR_VRSN_CD20, PRCDR_DT20, ICD_PRCDR_CD21, ICD_PRCDR_VRSN_CD21, PRCDR_DT21, ICD_PRCDR_CD22, ICD_PRCDR_VRSN_CD22, PRCDR_DT22, ICD_PRCDR_CD23, ICD_PRCDR_VRSN_CD23, PRCDR_DT23, ICD_PRCDR_CD24, ICD_PRCDR_VRSN_CD24, PRCDR_DT24, ICD_PRCDR_CD25, ICD_PRCDR_VRSN_CD25, PRCDR_DT25, RSN_VISIT_CD1, RSN_VISIT_VRSN_CD1, RSN_VISIT_CD2, RSN_VISIT_VRSN_CD2, RSN_VISIT_CD3, RSN_VISIT_VRSN_CD3, NCH_BENE_PTB_DDCTBL_AMT, NCH_BENE_PTB_COINSRNC_AMT, CLM_OP_PRVDR_PMT_AMT, CLM_OP_BENE_PMT_AMT, CLM_LINE_NUM, REV_CNTR, REV_CNTR_DT, REV_CNTR_1ST_ANSI_CD, REV_CNTR_2ND_ANSI_CD, REV_CNTR_3RD_ANSI_CD, REV_CNTR_4TH_ANSI_CD, REV_CNTR_APC_HIPPS_CD, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, REV_CNTR_PMT_MTHD_IND_CD, REV_CNTR_DSCNT_IND_CD, REV_CNTR_PACKG_IND_CD, REV_CNTR_OTAF_PMT_CD, REV_CNTR_IDE_NDC_UPC_NUM, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_BLOOD_DDCTBL_AMT, REV_CNTR_CASH_DDCTBL_AMT, REV_CNTR_COINSRNC_WGE_ADJSTD_C, REV_CNTR_RDCD_COINSRNC_AMT, REV_CNTR_1ST_MSP_PD_AMT, REV_CNTR_2ND_MSP_PD_AMT, REV_CNTR_PRVDR_PMT_AMT, REV_CNTR_BENE_PMT_AMT, REV_CNTR_PTNT_RSPNSBLTY_PMT, REV_CNTR_PMT_AMT_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_STUS_IND_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } private enum InpatientFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, FI_CLM_PROC_DT, CLAIM_QUERY_CODE, PRVDR_NUM, CLM_FAC_TYPE_CD, CLM_SRVC_CLSFCTN_TYPE_CD, CLM_FREQ_CD, FI_NUM, CLM_MDCR_NON_PMT_RSN_CD, CLM_PMT_AMT, NCH_PRMRY_PYR_CLM_PD_AMT, NCH_PRMRY_PYR_CD, FI_CLM_ACTN_CD, PRVDR_STATE_CD, ORG_NPI_NUM, AT_PHYSN_UPIN, AT_PHYSN_NPI, OP_PHYSN_UPIN, OP_PHYSN_NPI, OT_PHYSN_UPIN, OT_PHYSN_NPI, CLM_MCO_PD_SW, PTNT_DSCHRG_STUS_CD, CLM_PPS_IND_CD, CLM_TOT_CHRG_AMT, CLM_ADMSN_DT, CLM_IP_ADMSN_TYPE_CD, CLM_SRC_IP_ADMSN_CD, NCH_PTNT_STATUS_IND_CD, CLM_PASS_THRU_PER_DIEM_AMT, NCH_BENE_IP_DDCTBL_AMT, NCH_BENE_PTA_COINSRNC_LBLTY_AM, NCH_BENE_BLOOD_DDCTBL_LBLTY_AM, NCH_PROFNL_CMPNT_CHRG_AMT, NCH_IP_NCVRD_CHRG_AMT, NCH_IP_TOT_DDCTN_AMT, CLM_TOT_PPS_CPTL_AMT, CLM_PPS_CPTL_FSP_AMT, CLM_PPS_CPTL_OUTLIER_AMT, CLM_PPS_CPTL_DSPRPRTNT_SHR_AMT, CLM_PPS_CPTL_IME_AMT, CLM_PPS_CPTL_EXCPTN_AMT, CLM_PPS_OLD_CPTL_HLD_HRMLS_AMT, CLM_PPS_CPTL_DRG_WT_NUM, CLM_UTLZTN_DAY_CNT, BENE_TOT_COINSRNC_DAYS_CNT, BENE_LRD_USED_CNT, CLM_NON_UTLZTN_DAYS_CNT, NCH_BLOOD_PNTS_FRNSHD_QTY, NCH_VRFD_NCVRD_STAY_FROM_DT, NCH_VRFD_NCVRD_STAY_THRU_DT, NCH_ACTV_OR_CVRD_LVL_CARE_THRU, NCH_BENE_MDCR_BNFTS_EXHTD_DT_I, NCH_BENE_DSCHRG_DT, CLM_DRG_CD, CLM_DRG_OUTLIER_STAY_CD, NCH_DRG_OUTLIER_APRVD_PMT_AMT, ADMTG_DGNS_CD, ADMTG_DGNS_VRSN_CD, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, CLM_POA_IND_SW1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, CLM_POA_IND_SW2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, CLM_POA_IND_SW3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, CLM_POA_IND_SW4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, CLM_POA_IND_SW5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, CLM_POA_IND_SW6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, CLM_POA_IND_SW7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, CLM_POA_IND_SW8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, CLM_POA_IND_SW9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, CLM_POA_IND_SW10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, CLM_POA_IND_SW11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, CLM_POA_IND_SW12, ICD_DGNS_CD13, ICD_DGNS_VRSN_CD13, CLM_POA_IND_SW13, ICD_DGNS_CD14, ICD_DGNS_VRSN_CD14, CLM_POA_IND_SW14, ICD_DGNS_CD15, ICD_DGNS_VRSN_CD15, CLM_POA_IND_SW15, ICD_DGNS_CD16, ICD_DGNS_VRSN_CD16, CLM_POA_IND_SW16, ICD_DGNS_CD17, ICD_DGNS_VRSN_CD17, CLM_POA_IND_SW17, ICD_DGNS_CD18, ICD_DGNS_VRSN_CD18, CLM_POA_IND_SW18, ICD_DGNS_CD19, ICD_DGNS_VRSN_CD19, CLM_POA_IND_SW19, ICD_DGNS_CD20, ICD_DGNS_VRSN_CD20, CLM_POA_IND_SW20, ICD_DGNS_CD21, ICD_DGNS_VRSN_CD21, CLM_POA_IND_SW21, ICD_DGNS_CD22, ICD_DGNS_VRSN_CD22, CLM_POA_IND_SW22, ICD_DGNS_CD23, ICD_DGNS_VRSN_CD23, CLM_POA_IND_SW23, ICD_DGNS_CD24, ICD_DGNS_VRSN_CD24, CLM_POA_IND_SW24, ICD_DGNS_CD25, ICD_DGNS_VRSN_CD25, CLM_POA_IND_SW25, FST_DGNS_E_CD, FST_DGNS_E_VRSN_CD, ICD_DGNS_E_CD1, ICD_DGNS_E_VRSN_CD1, CLM_E_POA_IND_SW1, ICD_DGNS_E_CD2, ICD_DGNS_E_VRSN_CD2, CLM_E_POA_IND_SW2, ICD_DGNS_E_CD3, ICD_DGNS_E_VRSN_CD3, CLM_E_POA_IND_SW3, ICD_DGNS_E_CD4, ICD_DGNS_E_VRSN_CD4, CLM_E_POA_IND_SW4, ICD_DGNS_E_CD5, ICD_DGNS_E_VRSN_CD5, CLM_E_POA_IND_SW5, ICD_DGNS_E_CD6, ICD_DGNS_E_VRSN_CD6, CLM_E_POA_IND_SW6, ICD_DGNS_E_CD7, ICD_DGNS_E_VRSN_CD7, CLM_E_POA_IND_SW7, ICD_DGNS_E_CD8, ICD_DGNS_E_VRSN_CD8, CLM_E_POA_IND_SW8, ICD_DGNS_E_CD9, ICD_DGNS_E_VRSN_CD9, CLM_E_POA_IND_SW9, ICD_DGNS_E_CD10, ICD_DGNS_E_VRSN_CD10, CLM_E_POA_IND_SW10, ICD_DGNS_E_CD11, ICD_DGNS_E_VRSN_CD11, CLM_E_POA_IND_SW11, ICD_DGNS_E_CD12, ICD_DGNS_E_VRSN_CD12, CLM_E_POA_IND_SW12, ICD_PRCDR_CD1, ICD_PRCDR_VRSN_CD1, PRCDR_DT1, ICD_PRCDR_CD2, ICD_PRCDR_VRSN_CD2, PRCDR_DT2, ICD_PRCDR_CD3, ICD_PRCDR_VRSN_CD3, PRCDR_DT3, ICD_PRCDR_CD4, ICD_PRCDR_VRSN_CD4, PRCDR_DT4, ICD_PRCDR_CD5, ICD_PRCDR_VRSN_CD5, PRCDR_DT5, ICD_PRCDR_CD6, ICD_PRCDR_VRSN_CD6, PRCDR_DT6, ICD_PRCDR_CD7, ICD_PRCDR_VRSN_CD7, PRCDR_DT7, ICD_PRCDR_CD8, ICD_PRCDR_VRSN_CD8, PRCDR_DT8, ICD_PRCDR_CD9, ICD_PRCDR_VRSN_CD9, PRCDR_DT9, ICD_PRCDR_CD10, ICD_PRCDR_VRSN_CD10, PRCDR_DT10, ICD_PRCDR_CD11, ICD_PRCDR_VRSN_CD11, PRCDR_DT11, ICD_PRCDR_CD12, ICD_PRCDR_VRSN_CD12, PRCDR_DT12, ICD_PRCDR_CD13, ICD_PRCDR_VRSN_CD13, PRCDR_DT13, ICD_PRCDR_CD14, ICD_PRCDR_VRSN_CD14, PRCDR_DT14, ICD_PRCDR_CD15, ICD_PRCDR_VRSN_CD15, PRCDR_DT15, ICD_PRCDR_CD16, ICD_PRCDR_VRSN_CD16, PRCDR_DT16, ICD_PRCDR_CD17, ICD_PRCDR_VRSN_CD17, PRCDR_DT17, ICD_PRCDR_CD18, ICD_PRCDR_VRSN_CD18, PRCDR_DT18, ICD_PRCDR_CD19, ICD_PRCDR_VRSN_CD19, PRCDR_DT19, ICD_PRCDR_CD20, ICD_PRCDR_VRSN_CD20, PRCDR_DT20, ICD_PRCDR_CD21, ICD_PRCDR_VRSN_CD21, PRCDR_DT21, ICD_PRCDR_CD22, ICD_PRCDR_VRSN_CD22, PRCDR_DT22, ICD_PRCDR_CD23, ICD_PRCDR_VRSN_CD23, PRCDR_DT23, ICD_PRCDR_CD24, ICD_PRCDR_VRSN_CD24, PRCDR_DT24, ICD_PRCDR_CD25, ICD_PRCDR_VRSN_CD25, PRCDR_DT25, IME_OP_CLM_VAL_AMT, DSH_OP_CLM_VAL_AMT, CLM_LINE_NUM, REV_CNTR, HCPCS_CD, REV_CNTR_UNIT_CNT, REV_CNTR_RATE_AMT, REV_CNTR_TOT_CHRG_AMT, REV_CNTR_NCVRD_CHRG_AMT, REV_CNTR_DDCTBL_COINSRNC_CD, REV_CNTR_NDC_QTY, REV_CNTR_NDC_QTY_QLFR_CD, RNDRNG_PHYSN_UPIN, RNDRNG_PHYSN_NPI } private enum CarrierFields { DML_IND, BENE_ID, CLM_ID, CLM_GRP_ID, FINAL_ACTION, NCH_NEAR_LINE_REC_IDENT_CD, NCH_CLM_TYPE_CD, CLM_FROM_DT, CLM_THRU_DT, NCH_WKLY_PROC_DT, CARR_CLM_ENTRY_CD, CLM_DISP_CD, CARR_NUM, CARR_CLM_PMT_DNL_CD, CLM_PMT_AMT, CARR_CLM_PRMRY_PYR_PD_AMT, RFR_PHYSN_UPIN, RFR_PHYSN_NPI, CARR_CLM_PRVDR_ASGNMT_IND_SW, NCH_CLM_PRVDR_PMT_AMT, NCH_CLM_BENE_PMT_AMT, NCH_CARR_CLM_SBMTD_CHRG_AMT, NCH_CARR_CLM_ALOWD_AMT, CARR_CLM_CASH_DDCTBL_APLD_AMT, CARR_CLM_HCPCS_YR_CD, CARR_CLM_RFRNG_PIN_NUM, PRNCPAL_DGNS_CD, PRNCPAL_DGNS_VRSN_CD, ICD_DGNS_CD1, ICD_DGNS_VRSN_CD1, ICD_DGNS_CD2, ICD_DGNS_VRSN_CD2, ICD_DGNS_CD3, ICD_DGNS_VRSN_CD3, ICD_DGNS_CD4, ICD_DGNS_VRSN_CD4, ICD_DGNS_CD5, ICD_DGNS_VRSN_CD5, ICD_DGNS_CD6, ICD_DGNS_VRSN_CD6, ICD_DGNS_CD7, ICD_DGNS_VRSN_CD7, ICD_DGNS_CD8, ICD_DGNS_VRSN_CD8, ICD_DGNS_CD9, ICD_DGNS_VRSN_CD9, ICD_DGNS_CD10, ICD_DGNS_VRSN_CD10, ICD_DGNS_CD11, ICD_DGNS_VRSN_CD11, ICD_DGNS_CD12, ICD_DGNS_VRSN_CD12, CLM_CLNCL_TRIL_NUM, LINE_NUM, CARR_PRFRNG_PIN_NUM, PRF_PHYSN_UPIN, PRF_PHYSN_NPI, ORG_NPI_NUM, CARR_LINE_PRVDR_TYPE_CD, TAX_NUM, PRVDR_STATE_CD, PRVDR_ZIP, PRVDR_SPCLTY, PRTCPTNG_IND_CD, CARR_LINE_RDCD_PMT_PHYS_ASTN_C, LINE_SRVC_CNT, LINE_CMS_TYPE_SRVC_CD, LINE_PLACE_OF_SRVC_CD, CARR_LINE_PRCNG_LCLTY_CD, LINE_1ST_EXPNS_DT, LINE_LAST_EXPNS_DT, HCPCS_CD, HCPCS_1ST_MDFR_CD, HCPCS_2ND_MDFR_CD, BETOS_CD, LINE_NCH_PMT_AMT, LINE_BENE_PMT_AMT, LINE_PRVDR_PMT_AMT, LINE_BENE_PTB_DDCTBL_AMT, LINE_BENE_PRMRY_PYR_CD, LINE_BENE_PRMRY_PYR_PD_AMT, LINE_COINSRNC_AMT, LINE_SBMTD_CHRG_AMT, LINE_ALOWD_CHRG_AMT, LINE_PRCSG_IND_CD, LINE_PMT_80_100_CD, LINE_SERVICE_DEDUCTIBLE, CARR_LINE_MTUS_CNT, CARR_LINE_MTUS_CD, LINE_ICD_DGNS_CD, LINE_ICD_DGNS_VRSN_CD, HPSA_SCRCTY_IND_CD, CARR_LINE_RX_NUM, LINE_HCT_HGB_RSLT_NUM, LINE_HCT_HGB_TYPE_CD, LINE_NDC_CD, CARR_LINE_CLIA_LAB_NUM, CARR_LINE_ANSTHSA_UNIT_CNT } public enum PrescriptionFields { DML_IND, PDE_ID, CLM_GRP_ID, FINAL_ACTION, BENE_ID, SRVC_DT, PD_DT, SRVC_PRVDR_ID_QLFYR_CD, SRVC_PRVDR_ID, PRSCRBR_ID_QLFYR_CD, PRSCRBR_ID, RX_SRVC_RFRNC_NUM, PROD_SRVC_ID, PLAN_CNTRCT_REC_ID, PLAN_PBP_REC_NUM, CMPND_CD, DAW_PROD_SLCTN_CD, QTY_DSPNSD_NUM, DAYS_SUPLY_NUM, FILL_NUM, DSPNSNG_STUS_CD, DRUG_CVRG_STUS_CD, ADJSTMT_DLTN_CD, NSTD_FRMT_CD, PRCNG_EXCPTN_CD, CTSTRPHC_CVRG_CD, GDC_BLW_OOPT_AMT, GDC_ABV_OOPT_AMT, PTNT_PAY_AMT, OTHR_TROOP_AMT, LICS_AMT, PLRO_AMT, CVRD_D_PLAN_PD_AMT, NCVRD_PLAN_PD_AMT, TOT_RX_CST_AMT, RX_ORGN_CD, RPTD_GAP_DSCNT_NUM, BRND_GNRC_CD, PHRMCY_SRVC_TYPE_CD, PTNT_RSDNC_CD, SUBMSN_CLR_CD } private static class SingletonHolder { /** * Singleton instance of the CSVExporter. */ private static final BB2Exporter instance = new BB2Exporter(); } /** * Get the current instance of the BBExporter. * * @return the current instance of the BBExporter. */ public static BB2Exporter getInstance() { return SingletonHolder.instance; } /** * Utility class for writing to BB2 files. */ private static class SynchronizedBBLineWriter extends BufferedWriter { private static final String BB_FIELD_SEPARATOR = "|"; /** * Construct a new instance. * @param file the file to write to * @throws IOException if something goes wrong */ public SynchronizedBBLineWriter(File file) throws IOException { super(new FileWriter(file)); } /** * Write a line of output consisting of one or more fields separated by '|' and terminated with * a system new line. * @param fields the fields that will be concatenated into the line * @throws IOException if something goes wrong */ private void writeLine(String... fields) throws IOException { String line = String.join(BB_FIELD_SEPARATOR, fields); synchronized (lock) { write(line); newLine(); } } /** * Write a BB2 file header. * @param enumClass the enumeration class whose members define the column names * @throws IOException if something goes wrong */ public <E extends Enum<E>> void writeHeader(Class<E> enumClass) throws IOException { String[] fields = Arrays.stream(enumClass.getEnumConstants()).map(Enum::name) .toArray(String[]::new); writeLine(fields); } /** * Write a BB2 file line. * @param enumClass the enumeration class whose members define the column names * @param fieldValues a sparse map of column names to values, missing values will result in * empty values in the corresponding column * @throws IOException if something goes wrong */ public <E extends Enum<E>> void writeValues(Class<E> enumClass, Map<E, String> fieldValues) throws IOException { String[] fields = Arrays.stream(enumClass.getEnumConstants()) .map((e) -> fieldValues.getOrDefault(e, "")).toArray(String[]::new); writeLine(fields); } } }
package com.gravity.root; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.GameContainer; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.StateBasedGame; import com.google.common.collect.Lists; import com.gravity.levels.LevelInfo; /** * Main root class for the entire game. In order to add levels to the game, please add an entry to the levels table below, using the style of previous * levels before you. Namely: * * <pre> * <code> * new LevelInfo("Level Title", "Short Description for us", "path/to/level", levelID), * </code> * </pre> * * The level id can be any number greater than 1000 which is not used by another level already. Try to be sane about it and pick the next highest one. * ^_^ * * @author dxiao */ public class PlatformerGame extends StateBasedGame { //@formatter:off private LevelInfo[] levels = { // Very Hard (1) new LevelInfo("Moving", VictoryText.MOVING, "assets/Levels/moving.tmx"), // Impossible new LevelInfo("Falling", VictoryText.FALLING, "assets/Levels/falling.tmx"), new LevelInfo("Split World", VictoryText.SLINGSHOT, "assets/Levels/split_world.tmx"), // Very Hard (1) new LevelInfo("Bouncy 2", VictoryText.BOUNCY2, "assets/Levels/Bouncy_2.tmx"), // Hard (4) new LevelInfo("Bouncy 1", VictoryText.BOUNCY1, "assets/Levels/Bouncy_1.tmx"), new LevelInfo("Test Stomps", VictoryText.TEST, "assets/Levels/checkpointing.tmx"), new LevelInfo("Checkpointing", VictoryText.TEST, "assets/Levels/checkpointing.tmx"), new LevelInfo("intro_tutorial", VictoryText.PROCEDURES, "assets/Levels/intro_tutorial.tmx"), // Medium (4) new LevelInfo("Elevators", VictoryText.ELEVATORS, "assets/levels/Elevators.tmx"), new LevelInfo("Shortcuts", VictoryText.SHORTCUTS, "assets/levels/shortcuts.tmx"), new LevelInfo("Slingshot", VictoryText.SLINGSHOT, "assets/Levels/slingshot_intro.tmx"), new LevelInfo("Platformer", VictoryText.PLATFORMER, "assets/Levels/platform.tmx"), // Easy (2) new LevelInfo("Lab Procedures", VictoryText.PROCEDURES, "assets/Levels/tutorial.tmx"), new LevelInfo("Lab Safety", VictoryText.SAFETY, "assets/Levels/enemies_tutorial.tmx"), }; //@formatter:on public PlatformerGame() { super("Psychic Psycho Bunnies v1.1"); } @Override public void initStatesList(GameContainer gc) throws SlickException { addState(new GameLoaderState(Lists.newArrayList(levels), 100)); } public static void main(String args[]) throws SlickException { AppGameContainer app = new AppGameContainer(new PlatformerGame()); app.setDisplayMode(1024, 768, false); app.setMaximumLogicUpdateInterval(100); app.setMinimumLogicUpdateInterval(10); app.setTargetFrameRate(60); app.setAlwaysRender(true); app.setVSync(true); if (app.supportsMultiSample()) { app.setMultiSample(4); } // app.setSmoothDeltas(true); boolean isDebugging = false; try { isDebugging = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0; } catch (Exception e) { e.printStackTrace(); } app.setFullscreen(!isDebugging); app.start(); } }
package io.spine.server.aggregate; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.protobuf.Any; import com.google.protobuf.Empty; import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.core.CommandClass; import io.spine.core.CommandContext; import io.spine.core.CommandEnvelope; import io.spine.core.Event; import io.spine.core.EventClass; import io.spine.core.EventContext; import io.spine.core.EventEnvelope; import io.spine.core.MessageEnvelope; import io.spine.core.RejectionEnvelope; import io.spine.core.Version; import io.spine.core.Versions; import io.spine.protobuf.AnyPacker; import io.spine.server.command.CommandHandlerMethod; import io.spine.server.command.CommandHandlingEntity; import io.spine.server.command.dispatch.Dispatch; import io.spine.server.command.dispatch.DispatchResult; import io.spine.server.entity.EventPlayer; import io.spine.server.entity.EventPlayers; import io.spine.server.event.EventFactory; import io.spine.server.event.EventReactorMethod; import io.spine.server.model.Model; import io.spine.server.rejection.RejectionReactorMethod; import io.spine.validate.ValidatingBuilder; import java.util.Collection; import java.util.Iterator; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static com.google.common.collect.Lists.newLinkedList; import static io.spine.base.Time.getCurrentTime; import static io.spine.core.Events.getMessage; import static io.spine.validate.Validate.isNotDefault; /** * Abstract base for aggregates. * * <p>An aggregate is the main building block of a business model. * Aggregates guarantee consistency of data modifications in response to * commands they receive. * * <p>An aggregate modifies its state in response to a command and produces * one or more events. These events are used later to restore the state of the * aggregate. * * <h2>Creating an aggregate class</h2> * * <p>In order to create a new aggregate class you need to: * <ol> * <li>Select a type for identifiers of the aggregate. * If you select to use a typed identifier (which is recommended), * you need to define a protobuf message for the ID type. * <li>Define the structure of the aggregate state as a Protobuf message. * <li>Generate Java code for ID and state types. * <li>Create new Java class derived from {@code Aggregate} passing ID and * state types as generic parameters. * </ol> * * <h2>Adding command handler methods</h2> * * <p>Command handling methods of an {@code Aggregate} are defined in * the same way as described in {@link CommandHandlingEntity}. * * <p>Event(s) returned by command handling methods are posted to * the {@link io.spine.server.event.EventBus EventBus} automatically * by {@link AggregateRepository}. * * <h2>Adding event applier methods</h2> * * <p>Aggregate data is stored as a sequence of events it produces. * The state of the aggregate is restored by re-playing the history of * events and invoking corresponding <em>event applier methods</em>. * * <p>An event applier is a method that changes the state of the aggregate * in response to an event. An event applier takes a single parameter of the * event message it handles and returns {@code void}. * * <p>The modification of the state is done via a builder instance obtained * from {@link #getBuilder()}. * * <p>An {@code Aggregate} class must have applier methods for * <em>all</em> types of the events that it produces. * * <h2>Performance considerations for aggregate state</h2> * * <p>In order to improve performance of loading aggregates an * {@link AggregateRepository} periodically stores aggregate snapshots. * See {@link AggregateRepository#setSnapshotTrigger(int)} for details. * * @param <I> the type for IDs of this class of aggregates * @param <S> the type of the state held by the aggregate * @param <B> the type of the aggregate state builder * * @author Alexander Yevsyukov * @author Alexander Litus * @author Mikhail Melnik */ @SuppressWarnings("OverlyCoupledClass") // OK for this central class. public abstract class Aggregate<I, S extends Message, B extends ValidatingBuilder<S, ? extends Message.Builder>> extends CommandHandlingEntity<I, S, B> implements EventPlayer { /** * Events generated in the process of handling commands that were not yet committed. * * @see #commitEvents() */ private final List<Event> uncommittedEvents = newLinkedList(); /** A guard for ensuring idempotency of messages dispatched by this aggregate. */ private IdempotencyGuard idempotencyGuard; /** * Creates a new instance. * * <p>Constructors of derived classes should have package access level * because of the following reasons: * <ol> * <li>These constructors are not public API of an application. * Commands and aggregate IDs are. * <li>These constructors need to be accessible from tests in the same package. * </ol> * * <p>Because of the last reason consider annotating constructors with * {@code @VisibleForTesting}. The package access is needed only for tests. * Otherwise aggregate constructors (that are invoked by {@link AggregateRepository} * via Reflection) may be left {@code private}. * * @param id the ID for the new aggregate */ protected Aggregate(I id) { super(id); setIdempotencyGuard(); } /** * Creates and assigns the aggregate an {@link IdempotencyGuard idempotency guard}. */ private void setIdempotencyGuard() { idempotencyGuard = new IdempotencyGuard(this); } /** * Obtains model class for this aggregate. */ @Override protected AggregateClass<?> thisClass() { return (AggregateClass<?>)super.thisClass(); } /** * Obtains the model class as {@link Model#asAggregateClass(Class) AggregateClass}. */ @Override protected AggregateClass<?> getModelClass() { return Model.getInstance() .asAggregateClass(getClass()); } @Override protected B getBuilder() { return super.getBuilder(); } /** * Obtains a method for the passed command and invokes it. * * <p>Dispatching the commands results in emitting event messages. All the * {@linkplain Empty empty} messages are filtered out from the result. * * @param command the envelope with the command to dispatch * @return a list of event messages that the aggregate produces by handling the command */ @Override protected List<? extends Message> dispatchCommand(CommandEnvelope command) { idempotencyGuard.check(command); CommandHandlerMethod method = thisClass().getHandler(command.getMessageClass()); Dispatch<CommandEnvelope> dispatch = Dispatch.of(command).to(this, method); DispatchResult dispatchResult = dispatch.perform(); return dispatchResult.asMessages(); } /** * Dispatches the event on which the aggregate reacts. * * <p>Reacting on a event may result in emitting event messages. All the {@linkplain Empty empty} * messages are filtered out from the result. * * @param event the envelope with the event to dispatch * @return a list of event messages that the aggregate produces in reaction to the event or * an empty list if the aggregate state does not change in reaction to the event */ List<? extends Message> reactOn(EventEnvelope event) { EventReactorMethod method = thisClass().getReactor(event.getMessageClass()); Dispatch<EventEnvelope> dispatch = Dispatch.of(event).to(this, method); DispatchResult dispatchResult = dispatch.perform(); return dispatchResult.asMessages(); } /** * Dispatches the rejection to which the aggregate reacts. * * <p>Reacting on a rejection may result in emitting event messages. All the * {@linkplain Empty empty} messages are filtered out from the result. * * @param rejection the envelope with the rejection * @return a list of event messages that the aggregate produces in reaction to * the rejection, or an empty list if the aggregate state does not change in * response to this rejection */ List<? extends Message> reactOn(RejectionEnvelope rejection) { CommandClass commandClass = CommandClass.of(rejection.getCommandMessage()); RejectionReactorMethod method = thisClass().getReactor(rejection.getMessageClass(), commandClass); Dispatch<RejectionEnvelope> dispatch = Dispatch.of(rejection).to(this, method); DispatchResult dispatchResult = dispatch.perform(); return dispatchResult.asMessages(); } /** * Invokes applier method for the passed event message. * * @param eventMessage the event message to apply */ void invokeApplier(Message eventMessage) { final EventApplierMethod method = thisClass().getApplier(EventClass.of(eventMessage)); method.invoke(this, eventMessage); } @Override public void play(Iterable<Event> events) { EventPlayers.forTransactionOf(this) .play(events); } void play(AggregateStateRecord aggregateStateRecord) { final Snapshot snapshot = aggregateStateRecord.getSnapshot(); if (isNotDefault(snapshot)) { restore(snapshot); } final List<Event> events = aggregateStateRecord.getEventList(); play(events); remember(events); } /** * Applies event messages. * * @param eventMessages the event messages or events to apply * @param origin the envelope of a message which caused the events * @see #ensureEventMessage(Message) */ @CanIgnoreReturnValue Collection<Event> apply(Iterable<? extends Message> eventMessages, MessageEnvelope origin) { final List<? extends Message> messages = newArrayList(eventMessages); final EventFactory eventFactory = EventFactory.on(origin, getProducerId()); final List<Event> events = newArrayListWithCapacity(messages.size()); Version projectedEventVersion = getVersion(); for (Message eventOrMessage : messages) { /* Applying each message would increment the entity version. Therefore, we should simulate this behaviour. */ projectedEventVersion = Versions.increment(projectedEventVersion); final Message eventMessage = ensureEventMessage(eventOrMessage); final Event event; if (eventOrMessage instanceof Event) { /* If we get instances of Event, it means we are dealing with an import command, which contains these events in the body. So we deal with a command envelope. */ final CommandEnvelope ce = (CommandEnvelope)origin; event = importEvent((Event) eventOrMessage, ce.getCommandContext(), projectedEventVersion); } else { event = eventFactory.createEvent(eventMessage, projectedEventVersion); } events.add(event); } play(events); uncommittedEvents.addAll(events); return events; } /** * Creates an event based on the event received in an import command. * * @param event the event to import * @param commandContext the context of the import command * @param version the version of the aggregate to use for the event * @return an event with updated command context and entity version */ private static Event importEvent(Event event, CommandContext commandContext, Version version) { final EventContext eventContext = event.getContext() .toBuilder() .setCommandContext(commandContext) .setTimestamp(getCurrentTime()) .setVersion(version) .build(); final Event result = event.toBuilder() .setContext(eventContext) .build(); return result; } /** * Ensures that an event applier gets an instance of an event message, * not {@link Event}. * * <p>Instances of {@code Event} may be passed to an applier during * importing events or processing integration events. This may happen because * corresponding command handling method returned either {@code List<Event>} * or {@code Event}. * * @param eventOrMsg an event message or {@code Event} * @return the passed instance or an event message extracted from the passed * {@code Event} instance */ private static Message ensureEventMessage(Message eventOrMsg) { final Message eventMsg; if (eventOrMsg instanceof Event) { final Event event = (Event) eventOrMsg; eventMsg = getMessage(event); } else { eventMsg = eventOrMsg; } return eventMsg; } /** * Restores the state and version from the passed snapshot. * * <p>If this method is called during a {@linkplain #play(AggregateStateRecord) replay} * (because the snapshot was encountered) the method uses the state * {@linkplain #getBuilder() builder}, which is used during the replay. * * <p>If not in replay, the method sets the state and version directly to the aggregate. * * @param snapshot the snapshot with the state to restore */ void restore(Snapshot snapshot) { final S stateToRestore = AnyPacker.unpack(snapshot.getState()); final Version versionFromSnapshot = snapshot.getVersion(); setInitialState(stateToRestore, versionFromSnapshot); } /** * Returns all uncommitted events. * * @return immutable view of all uncommitted events */ List<Event> getUncommittedEvents() { return ImmutableList.copyOf(uncommittedEvents); } /** * Obtains the number of uncommitted events. */ @Internal @VisibleForTesting protected int uncommittedEventsCount() { return uncommittedEvents.size(); } /** * Returns and clears all the events that were uncommitted before the call of this method. * * @return the list of events */ List<Event> commitEvents() { final List<Event> result = ImmutableList.copyOf(uncommittedEvents); uncommittedEvents.clear(); remember(result); return result; } /** * Instructs to modify the state of an aggregate only within an event applier method. */ @Override protected String getMissingTxMessage() { return "Modification of aggregate state or its lifecycle flags is not available this way." + " Make sure to modify those only from an event applier method."; } /** * Transforms the current state of the aggregate into the {@link Snapshot} instance. * * @return new snapshot */ Snapshot toShapshot() { final Any state = AnyPacker.pack(getState()); final Snapshot.Builder builder = Snapshot.newBuilder() .setState(state) .setVersion(getVersion()) .setTimestamp(getCurrentTime()); final Snapshot snapshot = builder.build(); return snapshot; } /** * {@inheritDoc} * * <p>Opens the method for the repository. */ @Override protected void clearRecentHistory() { super.clearRecentHistory(); } /** * Creates an iterator of the aggregate event history with reverse traversal. * * <p>The records are returned sorted by timestamp in a descending order (from newer to older). * * <p>The iterator is empty if there's no history for the aggregate. * * @return new iterator instance */ protected Iterator<Event> historyBackward() { return recentHistory().iterator(); } /** * {@inheritDoc} * * <p>Overrides to expose the method to the package. */ @Override @VisibleForTesting protected int versionNumber() { return super.versionNumber(); } }
package org.mitre.synthea.export; import static org.mitre.synthea.export.ExportHelper.dateFromTimestamp; import static org.mitre.synthea.export.ExportHelper.iso8601Timestamp; import com.google.gson.JsonObject; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import org.apache.sis.geometry.DirectPosition2D; import org.mitre.synthea.engine.Event; import org.mitre.synthea.helpers.FactTable; import org.mitre.synthea.helpers.Utilities; import org.mitre.synthea.modules.Immunizations; import org.mitre.synthea.world.agents.Person; import org.mitre.synthea.world.agents.Provider; import org.mitre.synthea.world.concepts.Costs; import org.mitre.synthea.world.concepts.HealthRecord; import org.mitre.synthea.world.concepts.HealthRecord.CarePlan; import org.mitre.synthea.world.concepts.HealthRecord.Code; import org.mitre.synthea.world.concepts.HealthRecord.Encounter; import org.mitre.synthea.world.concepts.HealthRecord.EncounterType; import org.mitre.synthea.world.concepts.HealthRecord.Entry; import org.mitre.synthea.world.concepts.HealthRecord.ImagingStudy; import org.mitre.synthea.world.concepts.HealthRecord.Immunization; import org.mitre.synthea.world.concepts.HealthRecord.Medication; import org.mitre.synthea.world.concepts.HealthRecord.Observation; import org.mitre.synthea.world.concepts.HealthRecord.Procedure; import org.mitre.synthea.world.geography.Location; public class CDWExporter { /** * Table key sequence generators. */ private Map<FileWriter,AtomicInteger> sids; private FactTable maritalStatus = new FactTable(); private FactTable sta3n = new FactTable(); private FactTable location = new FactTable(); // private FactTable appointmentStatus = new FactTable(); // private FactTable appointmentType = new FactTable(); private FactTable immunizationName = new FactTable(); private FactTable reaction = new FactTable(); private FactTable localDrug = new FactTable(); private FactTable nationalDrug = new FactTable(); private FactTable dosageForm = new FactTable(); private FactTable pharmacyOrderableItem = new FactTable(); private FactTable orderStatus = new FactTable(); private FactTable vistaPackage = new FactTable(); /** * Writers for patient data. */ private FileWriter lookuppatient; private FileWriter spatient; private FileWriter spatientaddress; private FileWriter spatientphone; private FileWriter patientrace; private FileWriter patientethnicity; /** * Writers for encounter data. */ private FileWriter consult; private FileWriter visit; private FileWriter appointment; private FileWriter inpatient; /** * Writers for immunization data. */ private FileWriter immunization; /** * Writers for allergy data. */ private FileWriter allergy; private FileWriter allergyreaction; private FileWriter allergycomment; /** * Writers for condition data. */ private FileWriter problemlist; private FileWriter vdiagnosis; /** * Writers for medications data. */ private FileWriter rxoutpatient; private FileWriter nonvamed; private FileWriter cprsorder; /** * System-dependent string for a line break. (\n on Mac, *nix, \r\n on Windows) */ private static final String NEWLINE = System.lineSeparator(); /** * Constructor for the CDWExporter - * initialize the required files and associated writers. */ private CDWExporter() { sids = new HashMap<FileWriter,AtomicInteger>(); try { File output = Exporter.getOutputFolder("cdw", null); output.mkdirs(); Path outputDirectory = output.toPath(); // Patient Data lookuppatient = openFileWriter(outputDirectory, "lookuppatient.csv"); spatient = openFileWriter(outputDirectory, "spatient.csv"); spatientaddress = openFileWriter(outputDirectory, "spatientaddress.csv"); spatientphone = openFileWriter(outputDirectory, "spatientphone.csv"); patientrace = openFileWriter(outputDirectory, "patientrace.csv"); patientethnicity = openFileWriter(outputDirectory, "patientethnicity.csv"); // Encounter Data consult = openFileWriter(outputDirectory, "consult.csv"); visit = openFileWriter(outputDirectory, "visit.csv"); appointment = openFileWriter(outputDirectory, "appointment.csv"); inpatient = openFileWriter(outputDirectory, "inpatient.csv"); // Immunization Data immunization = openFileWriter(outputDirectory, "immunization.csv"); // Allergy Data allergy = openFileWriter(outputDirectory, "allergy.csv"); allergyreaction = openFileWriter(outputDirectory, "allergyreaction.csv"); allergycomment = openFileWriter(outputDirectory, "allergycomment.csv"); // Condition Data problemlist = openFileWriter(outputDirectory, "problemlist.csv"); vdiagnosis = openFileWriter(outputDirectory, "vdiagnosis.csv"); // Medications Data rxoutpatient = openFileWriter(outputDirectory, "rxoutpatient.csv"); nonvamed = openFileWriter(outputDirectory, "nonvamed.csv"); cprsorder = openFileWriter(outputDirectory, "cprsorder.csv"); writeCSVHeaders(); } catch (IOException e) { // wrap the exception in a runtime exception. // the singleton pattern below doesn't work if the constructor can throw // and if these do throw ioexceptions there's nothing we can do anyway throw new RuntimeException(e); } } private FileWriter openFileWriter(Path outputDirectory, String filename) throws IOException { File file = outputDirectory.resolve(filename).toFile(); return new FileWriter(file); } /** * Write the headers to each of the CSV files. * @throws IOException if any IO error occurs */ private void writeCSVHeaders() throws IOException { // Fact Tables maritalStatus.setHeader("MaritalStatusSID,MaritalStatusCode"); sta3n.setHeader("Sta3n,Sta3nName,TimeZone"); location.setHeader("LocationSID,LocationName"); immunizationName.setHeader("ImmunizationNameSID,ImmunizationName,CVXCode,MaxInSeries"); reaction.setHeader("ReactionSID,Reaction,VUID"); localDrug.setHeader("LocalDrugSID,LocalDrugIEN,Sta3n,LocalDrugNameWithDose," + "NationalDrugSID,NationalDrugNameWithDose"); nationalDrug.setHeader("NationalDrugSID,DrugNameWithDose,DosageFormSID," + "InactivationDate,VUID"); dosageForm.setHeader("DosageFormSID,DosageFormIEN,DosageForm"); pharmacyOrderableItem.setHeader("PharmacyOrderableItemSID,PharmacyOrderableItem,SupplyFlag"); orderStatus.setHeader("OrderStatusSID,OrderStatus"); vistaPackage.setHeader("VistaPackageSID,VistaPackage"); // Patient Tables lookuppatient.write("PatientSID,Sta3n,PatientIEN,PatientICN,PatientFullCN," + "PatientName,TestPatient"); lookuppatient.write(NEWLINE); spatient.write("PatientSID,PatientName,PatientLastName,PatientFirstName,PatientSSN,Age," + "BirthDateTime,DeceasedFlag,DeathDateTime,Gender,SelfIdentifiedGender,Religion," + "MaritalStatus,MaritalStatusSID,PatientEnteredDateTime"); spatient.write(NEWLINE); spatientaddress.write("SPatientAddressSID,PatientSID,AddressType,NameOfContact," + "RelationshipToPatient,StreetAddress1,StreetAddress2,StreetAddress3," + "City,State,Zip,PostalCode,Country,GISMatchScore,GISStreetSide," + "GISPatientAddressLongitude,GISPatientAddressLatitude,GISFIPSCode"); spatientaddress.write(NEWLINE); spatientphone.write("SPatientPhoneSID,PatientSID,PatientContactType,NameOfContact," + "RelationshipToPatient,PhoneNumber,WorkPhoneNumber,EmailAddress"); spatientphone.write(NEWLINE); patientrace.write("PatientRaceSID,PatientSID,Race"); patientrace.write(NEWLINE); patientethnicity.write("PatientEthnicitySID,PatientSID,Ethnicity"); patientethnicity.write(NEWLINE); // Encounter Tables consult.write("ConsultSID,ToRequestServiceSID"); consult.write(NEWLINE); visit.write("VisitSID,VisitDateTime,CreatedByStaffSID,LocationSID,PatientSID"); visit.write(NEWLINE); appointment.write("AppointmentSID,Sta3n,PatientSID,AppointmentDateTime,AppointmentMadeDate," + "AppointmentTypeSID,AppointmentStatus,VisitSID,LocationSID,PurposeOfVisit," + "SchedulingRequestType,FollowUpVisitFlag,LengthOfAppointment,ConsultSID," + "CheckInDateTime,CheckOutDateTime"); appointment.write(NEWLINE); inpatient.write("InpatientSID,PatientSID,AdmitDateTime"); inpatient.write(NEWLINE); // Immunization Table immunization.write("ImmunizationSID,ImmunizationIEN,Sta3n,PatientSID,ImmunizationNameSID," + "Series,Reaction,VisitDateTime,ImmunizationDateTime,OrderingStaffSID,ImmunizingStaffSID," + "VisitSID,ImmunizationComments,ImmunizationRemarks"); immunization.write(NEWLINE); // Allergy Tables allergy.write("AllergySID,AllergyIEN,Sta3n,PatientSID,AllergyType,AllergicReactant," + "LocalDrugSID,DrugNameWithoutDoseSID,DrugClassSID,ReactantSID,DrugIngredientSID," + "OriginationDateTime,OriginatingStaffSID,ObservedHistorical,Mechanism,VerifiedFlag," + "VerificatiionDateTime,VerifyingStaffSID,EnteredInErrorFlag"); allergy.write(NEWLINE); allergyreaction.write("AllergicReactionSID,AllergySID,AllergyIEN,Sta3n,ReactionSID"); allergyreaction.write(NEWLINE); allergycomment.write("AllergyCommentSID,AllergySID,AllergyIEN,Sta3n,PatientSID," + "OriginationDateTime,EnteringStaffSID,AllergyComment,CommentEnteredDateTime"); allergycomment.write(NEWLINE); // Condition Tables problemlist.write("ProblemListSID,Sta3n,ICD9SID,ICD10SID,PatientSID,ProviderNarrativeSID," + "EnteredDateTime,OnsetDateTime,ProblemListCondition,RecordingProviderSID," + "ResolvedDateTime,SNOMEDCTConceptCode"); problemlist.write(NEWLINE); vdiagnosis.write("VDiagnosisSID,Sta3n,ICD9SID,ICD10SID,PatientSID,VisitSID," + "VisitDateTime,VDiagnosisDateTime,ProviderNarrativeSID,ProblemListSID," + "OrderingProviderSID,EncounterProviderSID"); vdiagnosis.write(NEWLINE); // Medications Tables rxoutpatient.write("RxOutpatSID,Sta3n,RxNumber,IssueDate,CancelDate,FinishingDateTime," + "PatientSID,ProviderSID,EnteredByStaffSID,LocalDrugSID,NationalDrugSID," + "PharmacyOrderableItemSID,MaxRefills,RxStatus,OrderedQuantity"); rxoutpatient.write(NEWLINE); nonvamed.write("NonVAMedSID,PatientSID,NonVAMedIEN,Sta3n,LocalDrugSID,Dosage," + "MedicationRoute,Schedule,NonVAMedStatus,CPRSOrderSID,StartDateTime," + "DocumentedDateTime,NonVAMedComments"); nonvamed.write(NEWLINE); cprsorder.write("CPRSOrderID,Sta3n,PatientSID,OrderStaffSID,EnteredByStaffSID," + "EnteredDateTime,OrderStatusSID,VistaPackageSID,OrderStartDateTime,OrderStopDateTime," + "PackageReference"); cprsorder.write(NEWLINE); } private static class SingletonHolder { /** * Singleton instance of the CDWExporter. */ private static final CDWExporter instance = new CDWExporter(); } /** * Get the current instance of the CDWExporter. * @return the current instance of the CDWExporter. */ public static CDWExporter getInstance() { return SingletonHolder.instance; } /** * Add a single Person's health record info to the CSV records. * @param person Person to write record data for * @param time Time the simulation ended * @throws IOException if any IO error occurs */ public void export(Person person, long time) throws IOException { // TODO Ignore civilians, only consider the veteran population. // if (!person.attributes.containsKey("veteran")) { // return; int primarySta3n = -1; Provider provider = person.getAmbulatoryProvider(time); if (provider != null) { String state = Location.getStateName(provider.state); String tz = Location.getTimezoneByState(state); primarySta3n = sta3n.addFact(provider.id, clean(provider.name) + "," + tz); } int personID = patient(person, primarySta3n, time); for (Encounter encounter : person.record.encounters) { int encounterID = encounter(personID, person, encounter); for (HealthRecord.Entry condition : encounter.conditions) { condition(personID, encounterID, encounter, condition); } for (HealthRecord.Entry allergy : encounter.allergies) { allergy(personID, person, encounterID, encounter, allergy); } for (Observation observation : encounter.observations) { observation(personID, encounterID, observation); } for (Procedure procedure : encounter.procedures) { procedure(personID, encounterID, procedure); } for (Medication medication : encounter.medications) { medication(personID, encounterID, encounter, medication); } for (Immunization immunization : encounter.immunizations) { immunization(personID, person, encounterID, encounter, immunization); } for (CarePlan careplan : encounter.careplans) { careplan(personID, encounterID, careplan); } for (ImagingStudy imagingStudy : encounter.imagingStudies) { imagingStudy(personID, encounterID, imagingStudy); } } // Patient Data lookuppatient.flush(); spatient.flush(); spatientaddress.flush(); spatientphone.flush(); patientrace.flush(); patientethnicity.flush(); // Encounter Data consult.flush(); visit.flush(); appointment.flush(); inpatient.flush(); // Immunization Data immunization.flush(); // Allergy Data allergy.flush(); allergyreaction.flush(); allergycomment.flush(); // Condition Data problemlist.flush(); vdiagnosis.flush(); } /** * Fact Tables should only be written after all patients have completed export. */ public void writeFactTables() { try { File output = Exporter.getOutputFolder("cdw", null); output.mkdirs(); Path outputDirectory = output.toPath(); maritalStatus.write(openFileWriter(outputDirectory,"maritalstatus.csv")); sta3n.write(openFileWriter(outputDirectory,"sta3n.csv")); location.write(openFileWriter(outputDirectory,"location.csv")); immunizationName.write(openFileWriter(outputDirectory,"immunizationname.csv")); reaction.write(openFileWriter(outputDirectory,"reaction.csv")); localDrug.write(openFileWriter(outputDirectory,"localdrug.csv")); nationalDrug.write(openFileWriter(outputDirectory,"nationaldrug.csv")); dosageForm.write(openFileWriter(outputDirectory,"dosageform.csv")); pharmacyOrderableItem.write(openFileWriter(outputDirectory,"pharmacyorderableitem.csv")); orderStatus.write(openFileWriter(outputDirectory,"orderstatus.csv")); vistaPackage.write(openFileWriter(outputDirectory,"vistapackage.csv")); } catch (IOException e) { // wrap the exception in a runtime exception. // the singleton pattern below doesn't work if the constructor can throw // and if these do throw ioexceptions there's nothing we can do anyway throw new RuntimeException(e); } } /** * Record a Patient. * * @param person Person to write data for * @param sta3n The primary station ID for this patient * @param time Time the simulation ended, to calculate age/deceased status * @return the patient's ID, to be referenced as a "foreign key" if necessary * @throws IOException if any IO error occurs */ private int patient(Person person, int sta3n, long time) throws IOException { // Generate full name and ID StringBuilder s = new StringBuilder(); if (person.attributes.containsKey(Person.NAME_PREFIX)) { s.append(person.attributes.get(Person.NAME_PREFIX)).append(' '); } s.append(person.attributes.get(Person.FIRST_NAME)).append(' '); s.append(person.attributes.get(Person.LAST_NAME)); if (person.attributes.containsKey(Person.NAME_SUFFIX)) { s.append(' ').append(person.attributes.get(Person.NAME_SUFFIX)); } String patientName = s.toString(); int personID = getNextKey(spatient); // lookuppatient.write("PatientSID,Sta3n,PatientIEN,PatientICN,PatientFullCN," // + "PatientName,TestPatient"); s.setLength(0); s.append(personID).append(','); s.append(sta3n).append(','); s.append(personID).append(','); s.append(personID).append(','); s.append(personID).append(','); s.append(patientName).append(",1"); s.append(NEWLINE); write(s.toString(), lookuppatient); // spatient.write("PatientSID,PatientName,PatientLastName,PatientFirstName,PatientSSN,Age," // + "BirthDateTime,DeceasedFlag,DeathDateTime,Gender,SelfIdentifiedGender,Religion," // + "MaritalStatus,MaritalStatusSID,PatientEnteredDateTime"); s.setLength(0); s.append(personID).append(','); s.append(patientName); s.append(',').append(clean((String) person.attributes.getOrDefault(Person.LAST_NAME, ""))); s.append(',').append(clean((String) person.attributes.getOrDefault(Person.FIRST_NAME, ""))); s.append(',').append(clean((String) person.attributes.getOrDefault(Person.IDENTIFIER_SSN, ""))); boolean alive = person.alive(time); int age = 0; if (alive) { age = person.ageInYears(time); } else { age = person.ageInYears(person.events.event(Event.DEATH).time); } s.append(',').append(age); s.append(',').append(iso8601Timestamp((long) person.attributes.get(Person.BIRTHDATE))); if (alive) { s.append(',').append('N').append(','); } else { s.append(',').append('Y'); s.append(',').append(iso8601Timestamp(person.events.event(Event.DEATH).time)); } if (person.attributes.get(Person.GENDER).equals("M")) { s.append(",M,Male"); } else { s.append(",F,Female"); } s.append(",None"); // Religion // Currently there are no divorces or widows String marital = ((String) person.attributes.get(Person.MARITAL_STATUS)); if (marital != null) { if (marital.equals("M")) { s.append(",Married"); } else { marital = "N"; s.append(",Never Married"); } } else { marital = "U"; s.append(",Unknown"); } s.append(',').append(maritalStatus.addFact(marital, marital)); // TODO Need an enlistment date or date they became a veteran. s.append(',').append(iso8601Timestamp(time - Utilities.convertTime("years", 10))); s.append(NEWLINE); write(s.toString(), spatient); // spatientaddress.write("SPatientAddressSID,PatientSID,AddressType,NameOfContact," // + "RelationshipToPatient,StreetAddress1,StreetAddress2,StreetAddress3," // + "City,State,Zip,PostalCode,Country,GISMatchScore,GISStreetSide," // + "GISPatientAddressLongitude,GISPatientAddressLatitude,GISFIPSCode"); s.setLength(0); s.append(getNextKey(spatientaddress)).append(','); s.append(personID).append(','); s.append("Legal Residence").append(','); s.append(person.attributes.get(Person.FIRST_NAME)).append(' '); s.append(person.attributes.get(Person.LAST_NAME)).append(','); s.append("Self").append(','); s.append(person.attributes.get(Person.ADDRESS)).append(",,,"); s.append(person.attributes.get(Person.CITY)).append(','); s.append(person.attributes.get(Person.STATE)).append(','); s.append(person.attributes.get(Person.ZIP)); s.append(person.attributes.get(Person.ZIP)).append(",USA,,,"); DirectPosition2D coord = (DirectPosition2D) person.attributes.get(Person.COORDINATE); if (coord != null) { s.append(coord.x).append(',').append(coord.y).append(','); } else { s.append(",,"); } s.append(NEWLINE); write(s.toString(), spatientaddress); //spatientphone.write("SPatientPhoneSID,PatientSID,PatientContactType,NameOfContact," // + "RelationshipToPatient,PhoneNumber,WorkPhoneNumber,EmailAddress"); s.setLength(0); s.append(getNextKey(spatientphone)).append(','); s.append(personID).append(','); s.append("Patient Cell Phone").append(','); s.append(person.attributes.get(Person.FIRST_NAME)).append(' '); s.append(person.attributes.get(Person.LAST_NAME)).append(','); s.append("Self").append(','); s.append(person.attributes.get(Person.TELECOM)).append(",,"); s.append(NEWLINE); write(s.toString(), spatientphone); if (person.random.nextBoolean()) { // Add an email address s.setLength(0); s.append(getNextKey(spatientphone)).append(','); s.append(personID).append(','); s.append("Patient Email").append(','); s.append(person.attributes.get(Person.FIRST_NAME)).append(' '); s.append(person.attributes.get(Person.LAST_NAME)).append(','); s.append("Self").append(','); s.append(",,"); s.append(person.attributes.get(Person.FIRST_NAME)).append('.'); s.append(person.attributes.get(Person.LAST_NAME)).append("@email.example"); s.append(NEWLINE); write(s.toString(), spatientphone); } //patientrace.write("PatientRaceSID,PatientSID,Race"); String race = (String) person.attributes.get(Person.RACE); if (race.equals("white")) { race = "WHITE NOT OF HISP ORIG"; } else if (race.equals("hispanic")) { race = "WHITE"; } else if (race.equals("black")) { race = "BLACK OR AFRICAN AMERICAN"; } else if (race.equals("asian")) { race = "ASIAN"; } else if (race.equals("native")) { if (person.attributes.get(Person.STATE).equals("Hawaii")) { race = "NATIVE HAWAIIAN OR OTHER PACIFIC ISLANDER"; } else { race = "AMERICAN INDIAN OR ALASKA NATIVE"; } } else { // race.equals("other") race = "ASIAN"; } s.setLength(0); s.append(getNextKey(patientrace)).append(','); s.append(personID).append(','); s.append(race); s.append(NEWLINE); write(s.toString(), patientrace); //patientethnicity.write("PatientEthnicitySID,PatientSID,Ethnicity"); s.setLength(0); s.append(getNextKey(patientethnicity)).append(','); s.append(personID).append(','); race = (String) person.attributes.get(Person.RACE); if (race.equals("hispanic")) { s.append("HISPANIC OR LATINO"); } else { s.append("NOT HISPANIC OR LATINO"); } s.append(NEWLINE); write(s.toString(), patientethnicity); return personID; } /** * Write a single Encounter line to encounters.csv. * * @param personID The ID of the person that had this encounter * @param person The person attending the encounter * @param encounter The encounter itself * @return The encounter ID, to be referenced as a "foreign key" if necessary * @throws IOException if any IO error occurs */ private int encounter(int personID, Person person, Encounter encounter) throws IOException { StringBuilder s = new StringBuilder(); // consult.write("ConsultSID,ToRequestServiceSID"); int consultSid = getNextKey(consult); s.append(consultSid).append(',').append(consultSid).append(NEWLINE); write(s.toString(), consult); // visit.write("VisitSID,VisitDateTime,CreatedByStaffSID,LocationSID,PatientSID"); int visitSid = getNextKey(visit); s.setLength(0); s.append(visitSid).append(','); s.append(iso8601Timestamp(encounter.start)).append(','); s.append(','); // CreatedByStaffID == null Integer locationSid = null; if (encounter.provider != null) { locationSid = location.addFact(encounter.provider.id, clean(encounter.provider.name)); s.append(locationSid).append(','); } else { s.append(','); } s.append(personID); s.append(NEWLINE); write(s.toString(), visit); // appointment.write("AppointmentSID,Sta3n,PatientSID,AppointmentDateTime,AppointmentMadeDate," // + "AppointmentTypeSID,AppointmentStatus,VisitSID,LocationSID,PurposeOfVisit," // + "SchedulingRequestType,FollowUpVisitFlag,LengthOfAppointment,ConsultSID," // + "CheckInDateTime,CheckOutDateTime"); s.setLength(0); s.append(getNextKey(appointment)).append(','); if (encounter.provider != null) { String state = Location.getStateName(encounter.provider.state); String tz = Location.getTimezoneByState(state); s.append(sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz)); } s.append(','); s.append(personID).append(','); s.append(iso8601Timestamp(encounter.start)).append(','); s.append(iso8601Timestamp(encounter.start)).append(','); s.append(",,"); // skip: AppointmentTypeSID, AppointmentStatus s.append(visitSid).append(','); if (locationSid != null) { s.append(locationSid).append(','); } else { s.append(","); } s.append("3,"); // 3:SCHEDULED VISIT s.append(person.rand(new String[] {"N", "C", "P", "W", "M", "A", "O"})).append(','); s.append(person.randInt(1)).append(','); s.append((encounter.stop - encounter.start) / (60 * 1000)).append(','); s.append(consultSid).append(','); s.append(iso8601Timestamp(encounter.start)).append(','); s.append(iso8601Timestamp(encounter.stop)).append(NEWLINE); write(s.toString(), appointment); if (encounter.type.equalsIgnoreCase(EncounterType.INPATIENT.toString())) { // inpatient.write("InpatientSID,PatientSID,AdmitDateTime"); s.setLength(0); s.append(getNextKey(inpatient)).append(','); s.append(personID).append(','); s.append(iso8601Timestamp(encounter.start)).append(NEWLINE); write(s.toString(), inpatient); } return visitSid; } /** * Write a single Condition to conditions.csv. * * @param personID ID of the person that has the condition. * @param encounterID ID of the encounter where the condition was diagnosed * @param encounter The encounter * @param condition The condition itself * @throws IOException if any IO error occurs */ private void condition(int personID, int encounterID, Encounter encounter, Entry condition) throws IOException { StringBuilder s = new StringBuilder(); Integer sta3nValue = null; if (encounter.provider != null) { String state = Location.getStateName(encounter.provider.state); String tz = Location.getTimezoneByState(state); sta3nValue = sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz); } // problemlist.write("ProblemListSID,Sta3n,ICD9SID,ICD10SID,PatientSID,ProviderNarrativeSID," // + "EnteredDateTime,OnsetDateTime,ProblemListCondition,RecordingProviderSID," // + "ResolvedDateTime,SNOMEDCTConceptCode"); int problemListSid = getNextKey(problemlist); s.append(problemListSid).append(','); if (sta3nValue != null) { s.append(sta3nValue); } s.append(','); s.append(",,"); // skip icd 9 and icd 10 s.append(personID).append(','); s.append(','); // provider narrative -- history of present illness s.append(iso8601Timestamp(encounter.start)).append(','); s.append(iso8601Timestamp(condition.start)).append(','); s.append("P,"); s.append("-1,"); if (condition.stop != 0L) { s.append(iso8601Timestamp(condition.stop)); } s.append(','); s.append(condition.codes.get(0).code); s.append(NEWLINE); write(s.toString(), problemlist); // vdiagnosis.write("VDiagnosisSID,Sta3n,ICD9SID,ICD10SID,PatientSID,VisitSID," // + "VisitDateTime,VDiagnosisDateTime,ProviderNarrativeSID,ProblemListSID," // + "OrderingProviderSID,EncounterProviderSID"); s.setLength(0); s.append(getNextKey(vdiagnosis)); s.append(','); if (sta3nValue != null) { s.append(sta3nValue); } s.append(','); s.append(",,"); // skip icd 9 and icd 10 s.append(personID).append(','); s.append(encounterID).append(','); s.append(iso8601Timestamp(encounter.start)).append(','); s.append(iso8601Timestamp(condition.start)).append(','); s.append(','); // provider narrative -- history of present illness s.append(problemListSid).append(','); s.append("-1,"); s.append("-1"); s.append(NEWLINE); write(s.toString(), vdiagnosis); } /** * Write a single Allergy to allergies.csv. * * @param personID ID of the person that has the allergy. * @param person The person * @param encounterID ID of the encounter where the allergy was diagnosed * @param encounter The encounter * @param allergyEntry The allergy itself * @throws IOException if any IO error occurs */ private void allergy(int personID, Person person, int encounterID, Encounter encounter, Entry allergyEntry) throws IOException { StringBuilder s = new StringBuilder(); Integer sta3nValue = null; if (encounter.provider != null) { String state = Location.getStateName(encounter.provider.state); String tz = Location.getTimezoneByState(state); sta3nValue = sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz); } Code code = allergyEntry.codes.get(0); boolean food = code.display.matches(".*(nut|peanut|milk|dairy|eggs|shellfish|wheat).*"); // allergy.write("AllergySID,AllergyIEN,Sta3n,PatientSID,AllergyType,AllergicReactant," // + "LocalDrugSID,DrugNameWithoutDoseSID,DrugClassSID,ReactantSID,DrugIngredientSID," // + "OriginationDateTime,OriginatingStaffSID,ObservedHistorical,Mechanism,VerifiedFlag," // + "VerificatiionDateTime,VerifyingStaffSID,EnteredInErrorFlag"); int allergySID = getNextKey(allergy); s.append(allergySID).append(','); s.append(allergySID).append(','); if (encounter.provider != null) { s.append(sta3nValue); } s.append(','); s.append(personID).append(','); if (food) { s.append('F').append(','); // F: Food allergy } else { s.append('O').append(','); // O: Other } s.append(clean(code.display)).append(','); // AllergicReactant s.append(','); // LocalDrugSID s.append(','); // DrugNameWithoutDoseSID s.append(','); // DrugClassSID s.append(','); // ReactantSID s.append(','); // DrugIngredientSID s.append(iso8601Timestamp(allergyEntry.start)).append(','); s.append("-1,"); s.append(person.rand(new String[] {"o", "h"})).append(','); s.append("A,"); s.append("1,"); // Verified s.append(iso8601Timestamp(allergyEntry.start)).append(','); s.append("-1,"); s.append(','); s.append(NEWLINE); write(s.toString(), allergy); // allergyreaction.write("AllergicReactionSID,AllergySID,AllergyIEN,Sta3n,ReactionSID"); String reactionDisplay = person.rand( new String[] {"Sneezing and Coughing", "Inflammation of Skin", "Itchy Watery Eyes", "Difficulty Breathing"}); s.setLength(0); int allergyreactionSID = getNextKey(allergyreaction); s.append(allergyreactionSID); s.append(allergySID).append(','); s.append(allergySID).append(','); if (encounter.provider != null) { s.append(sta3nValue); } s.append(','); s.append(reaction.addFact(reactionDisplay, reactionDisplay + "," + allergyreactionSID)); s.append(NEWLINE); write(s.toString(), allergyreaction); // allergycomment.write("AllergyCommentSID,AllergySID,AllergyIEN,Sta3n,PatientSID," // + "OriginationDateTime,EnteringStaffSID,AllergyComment,CommentEnteredDateTime"); s.setLength(0); int allergyCommentSid = getNextKey(allergycomment); s.append(allergyCommentSid).append(','); s.append(allergySID).append(','); s.append(allergySID).append(','); if (encounter.provider != null) { s.append(sta3nValue); } s.append(','); s.append(personID).append(','); s.append(iso8601Timestamp(allergyEntry.start)).append(','); s.append("-1,"); s.append(clean(code.display)).append(','); s.append(iso8601Timestamp(allergyEntry.start)); s.append(NEWLINE); write(s.toString(), allergycomment); } /** * Write a single Observation to observations.csv. * * @param personID ID of the person to whom the observation applies. * @param encounterID ID of the encounter where the observation was taken * @param observation The observation itself * @throws IOException if any IO error occurs */ private void observation(int personID, int encounterID, Observation observation) throws IOException { if (observation.value == null) { if (observation.observations != null && !observation.observations.isEmpty()) { // just loop through the child observations for (Observation subObs : observation.observations) { observation(personID, encounterID, subObs); } } // no value so nothing more to report here return; } // DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,VALUE,UNITS StringBuilder s = new StringBuilder(); s.append(dateFromTimestamp(observation.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = observation.codes.get(0); s.append(coding.code).append(','); s.append(clean(coding.display)).append(','); String value = ExportHelper.getObservationValue(observation); String type = ExportHelper.getObservationType(observation); s.append(value).append(','); s.append(observation.unit).append(','); s.append(type); s.append(NEWLINE); //write(s.toString(), observations); } /** * Write a single Procedure to procedures.csv. * * @param personID ID of the person on whom the procedure was performed. * @param encounterID ID of the encounter where the procedure was performed * @param procedure The procedure itself * @throws IOException if any IO error occurs */ private void procedure(int personID, int encounterID, Procedure procedure) throws IOException { // DATE,PATIENT,ENCOUNTER,CODE,DESCRIPTION,COST,REASONCODE,REASONDESCRIPTION StringBuilder s = new StringBuilder(); s.append(dateFromTimestamp(procedure.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = procedure.codes.get(0); s.append(coding.code).append(','); s.append(clean(coding.display)).append(','); s.append(String.format("%.2f", Costs.calculateCost(procedure, true))).append(','); if (procedure.reasons.isEmpty()) { s.append(','); // reason code & desc } else { Code reason = procedure.reasons.get(0); s.append(reason.code).append(','); s.append(clean(reason.display)); } s.append(NEWLINE); //write(s.toString(), procedures); } /** * Write a single Medication to medications.csv. * * @param personID ID of the person prescribed the medication. * @param encounterID ID of the encounter where the medication was prescribed * @param encounter The encounter * @param medication The medication itself * @throws IOException if any IO error occurs */ private void medication(int personID, int encounterID, Encounter encounter, Medication medication) throws IOException { StringBuilder s = new StringBuilder(); Integer sta3nValue = null; if (encounter.provider != null) { String state = Location.getStateName(encounter.provider.state); String tz = Location.getTimezoneByState(state); sta3nValue = sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz); } Code code = medication.codes.get(0); // pharmacyOrderableItem ("PharmacyOrderableItemSID,PharmacyOrderableItem,SupplyFlag"); int pharmSID = pharmacyOrderableItem.addFact(code.code, clean(code.display) + ",1"); // dosageForm.setHeader("DosageFormSID,DosageFormIEN,DosageForm"); Integer dosageSID = null; if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("dosage")) { JsonObject dosage = medication.prescriptionDetails.get("dosage").getAsJsonObject(); s.setLength(0); s.append(dosage.get("amount").getAsInt()); s.append(" dose(s) "); s.append(dosage.get("frequency").getAsInt()); s.append(" time(s) per "); s.append(dosage.get("period").getAsInt()); s.append(" "); s.append(dosage.get("unit").getAsString()); dosageSID = dosageForm.addFact(code.code, pharmSID + "," + s.toString()); } // nationalDrug.setHeader("NationalDrugSID,DrugNameWithDose,DosageFormSID," // + "InactivationDate,VUID"); s.setLength(0); s.append(clean(code.display)); s.append(','); if (dosageSID != null) { s.append(dosageSID); } s.append(",,"); s.append(code.code); int ndrugSID = nationalDrug.addFact(code.code, s.toString()); // localDrug.setHeader("LocalDrugSID,LocalDrugIEN,Sta3n,LocalDrugNameWithDose," // + "NationalDrugSID,NationalDrugNameWithDose"); s.setLength(0); s.append(ndrugSID).append(','); if (sta3nValue != null) { s.append(sta3nValue); } s.append(','); s.append(clean(code.display)).append(','); s.append(ndrugSID).append(','); s.append(clean(code.display)); int ldrugSID = localDrug.addFact(code.code, s.toString()); // rxoutpatient.write("RxOutpatSID,Sta3n,RxNumber,IssueDate,CancelDate,FinishingDateTime," // + "PatientSID,ProviderSID,EnteredByStaffSID,LocalDrugSID,NationalDrugSID," // + "PharmacyOrderableItemSID,MaxRefills,RxStatus,OrderedQuantity"); s.setLength(0); int rxNum = getNextKey(rxoutpatient); s.append(rxNum).append(','); if (sta3nValue != null) { s.append(sta3nValue); } s.append(','); s.append(rxNum).append(','); s.append(iso8601Timestamp(medication.start)).append(','); if (medication.stop != 0L) { s.append(iso8601Timestamp(medication.stop)); } s.append(','); if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("duration")) { JsonObject duration = medication.prescriptionDetails.get("duration").getAsJsonObject(); long time = Utilities.convertTime( duration.get("unit").getAsString(), duration.get("quantity").getAsLong()); s.append(iso8601Timestamp(medication.start + time)); } s.append(','); s.append(personID).append(','); s.append("-1,"); // Provider s.append("-1,"); // Entered by staff s.append(ldrugSID).append(','); s.append(ndrugSID).append(','); s.append(pharmSID).append(','); if (medication.prescriptionDetails != null && medication.prescriptionDetails.has("refills")) { s.append(medication.prescriptionDetails.get("refills").getAsInt()); } s.append(','); if (medication.stop == 0L) { s.append("0,"); // Active } else { s.append("10,"); // Done } s.append(NEWLINE); write(s.toString(), rxoutpatient); // cprsorder.write("CPRSOrderID,Sta3n,PatientSID,OrderStaffSID,EnteredByStaffSID," // + "EnteredDateTime,OrderStatusSID,VistaPackageSID,OrderStartDateTime,OrderStopDateTime," // + "PackageReference"); int cprsSID = getNextKey(cprsorder); s.setLength(0); s.append(cprsSID).append(','); if (sta3nValue != null) { s.append(sta3nValue); } s.append(','); s.append(personID).append(','); s.append("-1,"); // OrderStaffSID s.append("-1,"); // EnteredByStaffSID s.append(iso8601Timestamp(medication.start)).append(','); int orderStatusSID = -1; if (medication.stop != 0L) { orderStatusSID = orderStatus.addFact("EXPIRED", "EXPIRED"); } else { orderStatusSID = orderStatus.addFact("ACTIVE", "ACTIVE"); } s.append(orderStatusSID).append(','); s.append(vistaPackage.addFact("OUTPATIENT PHARMACY", "OUTPATIENT PHARMACY")).append(','); s.append(iso8601Timestamp(medication.start)).append(','); if (medication.stop != 0L) { s.append(iso8601Timestamp(medication.stop)); } s.append(','); s.append("OUTPATIENT PHARMACY"); s.append(NEWLINE); write(s.toString(), cprsorder); // nonvamed.write("NonVAMedSID,PatientSID,NonVAMedIEN,Sta3n,LocalDrugSID,Dosage," // + "MedicationRoute,Schedule,NonVAMedStatus,CPRSOrderSID,StartDateTime," // + "DocumentedDateTime,NonVAMedComments"); s.setLength(0); int nonvamedSID = getNextKey(nonvamed); s.append(nonvamedSID).append(','); s.append(personID).append(','); s.append(nonvamedSID).append(','); if (sta3nValue != null) { s.append(sta3nValue); } s.append(','); s.append(ldrugSID).append(','); if (dosageSID != null) { String fact = dosageForm.getFactById(dosageSID); s.append(fact.substring(fact.indexOf(',') + 1)); } s.append(','); s.append(','); // MedicationRoute s.append(','); // Schedule s.append(orderStatus.getFactById(orderStatusSID)).append(','); s.append(cprsSID).append(','); s.append(iso8601Timestamp(medication.start)).append(','); s.append(iso8601Timestamp(medication.start)).append(','); s.append(clean(code.display)); s.append(NEWLINE); write(s.toString(), nonvamed); } /** * Write a single Immunization to immunizations.csv. * * @param personID ID of the person on whom the immunization was performed. * @param person The person * @param encounterID ID of the encounter where the immunization was performed * @param encounter The encounter itself * @param immunization The immunization itself * @throws IOException if any IO error occurs */ private void immunization(int personID, Person person, int encounterID, Encounter encounter, Immunization immunizationEntry) throws IOException { StringBuilder s = new StringBuilder(); // immunization.write("ImmunizationSID,ImmunizationIEN,Sta3n,PatientSID,ImmunizationNameSID," // + "Series,Reaction,VisitDateTime,ImmunizationDateTime,OrderingStaffSID,ImmunizingStaffSID," // + "VisitSID,ImmunizationComments,ImmunizationRemarks"); int immunizationSid = getNextKey(immunization); s.append(immunizationSid).append(','); s.append(immunizationSid).append(','); // ImmunizationIEN if (encounter.provider != null) { String state = Location.getStateName(encounter.provider.state); String tz = Location.getTimezoneByState(state); s.append(sta3n.addFact(encounter.provider.id, clean(encounter.provider.name) + "," + tz)); } s.append(','); s.append(personID).append(','); Code cvx = immunizationEntry.codes.get(0); int maxInSeries = Immunizations.getMaximumDoses(cvx.code); s.append( immunizationName.addFact( cvx.code, clean(cvx.display) + "," + cvx.code + "," + maxInSeries)); int series = immunizationEntry.series; if (series == maxInSeries) { s.append(",C,"); } else { s.append(",B,"); } s.append(person.randInt(12)).append(','); // Reaction s.append(iso8601Timestamp(immunizationEntry.start)).append(','); s.append(iso8601Timestamp(immunizationEntry.start)).append(','); s.append("-1,-1,"); s.append(encounterID).append(','); // Comment s.append("Dose #" + series + " of " + maxInSeries + " of " + clean(cvx.display) + " vaccine administered.,"); // Remark s.append("Dose #" + series + " of " + maxInSeries + " of " + clean(cvx.display) + " vaccine administered."); s.append(NEWLINE); write(s.toString(), immunization); } /** * Write a single CarePlan to careplans.csv. * * @param personID ID of the person prescribed the careplan. * @param encounterID ID of the encounter where the careplan was prescribed * @param careplan The careplan itself * @throws IOException if any IO error occurs */ private String careplan(int personID, int encounterID, CarePlan careplan) throws IOException { // ID,START,STOP,PATIENT,ENCOUNTER,CODE,DESCRIPTION,REASONCODE,REASONDESCRIPTION StringBuilder s = new StringBuilder(); String careplanID = UUID.randomUUID().toString(); s.append(careplanID).append(','); s.append(dateFromTimestamp(careplan.start)).append(','); if (careplan.stop != 0L) { s.append(dateFromTimestamp(careplan.stop)); } s.append(','); s.append(personID).append(','); s.append(encounterID).append(','); Code coding = careplan.codes.get(0); s.append(coding.code).append(','); s.append(coding.display).append(','); if (careplan.reasons.isEmpty()) { s.append(','); // reason code & desc } else { Code reason = careplan.reasons.get(0); s.append(reason.code).append(','); s.append(clean(reason.display)); } s.append(NEWLINE); //write(s.toString(), careplans); return careplanID; } /** * Write a single ImagingStudy to imaging_studies.csv. * * @param personID ID of the person the ImagingStudy was taken of. * @param encounterID ID of the encounter where the ImagingStudy was performed * @param imagingStudy The ImagingStudy itself * @throws IOException if any IO error occurs */ private String imagingStudy(int personID, int encounterID, ImagingStudy imagingStudy) throws IOException { // ID,DATE,PATIENT,ENCOUNTER,BODYSITE_CODE,BODYSITE_DESCRIPTION, // MODALITY_CODE,MODALITY_DESCRIPTION,SOP_CODE,SOP_DESCRIPTION StringBuilder s = new StringBuilder(); String studyID = UUID.randomUUID().toString(); s.append(studyID).append(','); s.append(dateFromTimestamp(imagingStudy.start)).append(','); s.append(personID).append(','); s.append(encounterID).append(','); ImagingStudy.Series series1 = imagingStudy.series.get(0); ImagingStudy.Instance instance1 = series1.instances.get(0); Code bodySite = series1.bodySite; Code modality = series1.modality; Code sopClass = instance1.sopClass; s.append(bodySite.code).append(','); s.append(bodySite.display).append(','); s.append(modality.code).append(','); s.append(modality.display).append(','); s.append(sopClass.code).append(','); s.append(sopClass.display); s.append(NEWLINE); //write(s.toString(), imagingStudies); return studyID; } private int getNextKey(FileWriter table) { synchronized (sids) { return sids.computeIfAbsent(table, k -> new AtomicInteger(1)).getAndIncrement(); } } /** * Replaces commas and line breaks in the source string with a single space. * Null is replaced with the empty string. */ private static String clean(String src) { if (src == null) { return ""; } else { return src.replaceAll("\\r\\n|\\r|\\n|,", " ").trim(); } } /** * Helper method to write a line to a File. * Extracted to a separate method here to make it a little easier to replace implementations. * * @param line The line to write * @param writer The place to write it * @throws IOException if an I/O error occurs */ private static void write(String line, FileWriter writer) throws IOException { synchronized (writer) { writer.write(line); writer.flush(); } } }
package io.spine.server.type; import com.google.common.collect.ImmutableSet; import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath.ClassInfo; import com.google.protobuf.Message; import io.spine.base.RejectionMessage; import io.spine.base.ThrowableMessage; import io.spine.core.Event; import io.spine.type.MessageClass; import java.io.IOException; import java.util.Arrays; import java.util.Optional; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.spine.core.Events.ensureMessage; import static io.spine.util.Exceptions.illegalStateWithCauseOf; import static io.spine.util.Exceptions.newIllegalArgumentException; /** * A value object holding a class of a business rejection. */ public final class RejectionClass extends MessageClass<RejectionMessage> { private static final long serialVersionUID = 0L; private RejectionClass(Class<? extends RejectionMessage> value) { super(value); } /** * Creates a new instance of the rejection class. * * @param value * a value to hold * @return new instance */ public static RejectionClass of(Class<? extends RejectionMessage> value) { return new RejectionClass(checkNotNull(value)); } /** * Creates a new instance of the rejection class by passed rejection instance. * * <p>If an instance of {@link Event} which implements {@code Message} is * passed to this method, enclosing rejection message will be un-wrapped to determine * the class of the rejection. * * @param rejectionOrMessage * a rejection instance * @return new instance */ public static RejectionClass of(Message rejectionOrMessage) { RejectionMessage message = (RejectionMessage) ensureMessage(rejectionOrMessage); RejectionClass result = of(message.getClass()); return result; } /** * Creates a new instance from the given {@code ThrowableMessage}. */ public static RejectionClass of(ThrowableMessage rejection) { RejectionMessage rejectionMessage = rejection.messageThrown(); return of(rejectionMessage); } public static RejectionClass from(Class<? extends ThrowableMessage> cls) { Locator locator = new Locator(cls); RejectionClass result = locator.find() .map(RejectionClass::of) .orElseThrow( () -> newIllegalArgumentException( "Unable to find a rejection class matching the class `%s`", cls.getName()) ); return result; } private static final class Locator { /** * The conventional suffix for outer classes containing rejection message classes. */ private static final String REJECTION_OUTER_CLASS_SUFFIX = "Rejections"; private final Class<? extends ThrowableMessage> throwableClass; private final ClassPath classPath; private Locator(Class<? extends ThrowableMessage> cls) { this.throwableClass = cls; this.classPath = classPath(); } Optional<Class<? extends RejectionMessage>> find() { Package classPackage = throwableClass.getPackage(); String packageName = classPackage.getName(); ImmutableSet<ClassInfo> rejectionOuterClasses = rejectionOuterClasses(packageName); @SuppressWarnings("unchecked") /* The cast is ensures by the fact that generated rejection messages are placed inside the outer class which name ends with "Rejections". We also check that for the simple name equality, which is also a part of the convention. */ Optional<Class<? extends RejectionMessage>> result = rejectionOuterClasses .stream() .map(ClassInfo::load) .flatMap(outerClass -> Arrays.stream(outerClass.getClasses())) .filter(innerClass -> innerClass.getSimpleName() .equals(throwableClass.getSimpleName())) .findFirst() .map(c -> (Class<? extends RejectionMessage>) c); return result; } private ImmutableSet<ClassInfo> rejectionOuterClasses(String packageName) { ImmutableSet<ClassInfo> topLevelClasses = classPath.getTopLevelClasses(packageName); return topLevelClasses.stream() .filter(c -> c.getName() .endsWith(REJECTION_OUTER_CLASS_SUFFIX)) .collect(toImmutableSet()); } private ClassPath classPath() { try { return ClassPath.from(throwableClass.getClassLoader()); } catch (IOException e) { throw illegalStateWithCauseOf(e); } } } }
package org.myrobotlab.framework; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.logging.LoggerFactory; import org.slf4j.Logger; import com.google.gson.internal.LinkedTreeMap; /** * * @author GroG * * A method cache whos purpose is to build a cache of methods to be * accessed when needed for invoking. This cache is typically used for * services and populated during Runtime.create({name},{Type}). It's a * static resource and contains a single definition per {Type}. * * It has a single map of "all" MethodEntries per type, and several * indexes to that map. The other utility indexes are supposed to be * useful and relevant for service specific access of methods. * * The definition of "declared methods" is slightly different for Mrl * services. "Declared methods" are service methods which are expected * to be commonly used. The difference occurs often with abstract * classes such as AbstractSpeechSynthesis. Polly's * class.getDeclaredMethods() would NOT include all the useful methods * commonly defined in AbstractSpeechSynthesis. * * FIXME - keys should be explicitly typed full signature with execution * format e.g. method( * * * The cache is built when new services are created. Method signatures * are used as keys. The keys are string based. All parameters in key * creation are "boxed", this leads to the ability to write actual * functions with primitives e.g. doIt(int x, float y, ...) and invoking * does not need to fail for it to be called directly. * * Ancestor classes are all indexed, so there is no "special" handling * to call abstract class methods. * * Special indexes are created when a new service gets created that are * explicitly applicable for remote procedure calls e.g. methods which * contain interfaces in the parameters are not part of this index, if * your creating a highly accessable method that you expect to be used * remotely, you would make it with a String {name} reference as a * parameter. * */ public class MethodCache { // FIXME - mostly interested in // NOT Object // RARELY Service // OFTEN ANYTHING DEFINED LOWER THAN THAT // WHICH MEANS - filter out Object // CREATE a "Service" Index // -> ALL OTHER METHODS ARE OF INTEREST class MethodIndex { // index for typeless resolution and invoking Map<String, List<MethodEntry>> methodOrdinalIndex = new TreeMap<>(); // super index of all method entries Map<String, MethodEntry> methodsIndex = new TreeMap<>(); // index based on typeless resolution and invoking without interfaces Map<String, List<MethodEntry>> remoteOrdinalIndex = new TreeMap<>(); // Map<String, List<MethodEntry>> declaredMethodOrdinalIndex = new // TreeMap<>(); } private static MethodCache instance; public final static Logger log = LoggerFactory.getLogger(MethodCache.class); final public static Class<?> boxPrimitive(Class<?> clazz) { if (clazz == boolean.class) { return Boolean.class; } else if (clazz == char.class) { return Character.class; } else if (clazz == byte.class) { return Byte.class; } else if (clazz == short.class) { return Short.class; } else if (clazz == int.class) { return Integer.class; } else if (clazz == long.class) { return Long.class; } else if (clazz == float.class) { return Float.class; } else if (clazz == double.class) { return Double.class; } else if (clazz == void.class) { return Void.class; } else { log.error("unexpected type class conversion for class {}", clazz.getTypeName()); } return null; } public static MethodCache getInstance() { if (instance != null) { return instance; } synchronized (MethodCache.class) { if (instance == null) { instance = new MethodCache(); instance.excludeMethods.add("main"); } } return instance; } /* * public static void main(String[] args) { try { * * // LoggingFactory.init(Level.INFO); * * MethodCache cache = MethodCache.getInstance(); // * cache.cacheMethodEntries(Runtime.class); * cache.cacheMethodEntries(Clock.class); * * * } catch(Exception e) { log.error("main threw", e); } } */ Set<String> excludeMethods = new TreeSet<>(); Map<String, MethodIndex> objectCache = new TreeMap<>(); protected MethodCache() { } public void cacheMethodEntries(Class<?> object) { Set<Class<?>> exclude = new HashSet<>(); exclude.add(Service.class); exclude.add(Object.class); cacheMethodEntries(object, exclude); } // public void cacheMethodEntries(Class<?> object, Class<?> maxSuperType, // Set<String> excludeMethods) { public void cacheMethodEntries(Class<?> object, Set<Class<?>> excludeFromDeclared) { if (objectCache.containsKey(object.getTypeName())) { log.info("already cached {} methods", object.getSimpleName()); return; } long start = System.currentTimeMillis(); MethodIndex mi = new MethodIndex(); Method[] methods = object.getMethods(); Method[] declaredMethods = object.getDeclaredMethods(); log.info("caching {}'s {} methods and {} declared methods", object.getSimpleName(), methods.length, declaredMethods.length); for (Method m : methods) { // log.debug("processing {}", m.getName()); // extremely useful for debugging cache // if (m.getName().equals("processResults") && // m.getParameterTypes().length == 1) { // log.info("here"); String key = getMethodKey(object, m); String ordinalKey = getMethodOrdinalKey(object, m); boolean hasInterfaceInParamList = hasInterface(m); // FIXME - we are "building" an index, not at the moment - "using" the // index - so it should be "complete" // FIXME - other sub-indexes are "trimmed" for appropriate uses // should this use key ?? vs name ? or different class-less signature e.g. // main(String[]) // if (excludeMethods.contains(m.getName())) { // continue; // search for interfaces in parameters - if there are any the method is // not applicable for remote invoking ! MethodEntry me = new MethodEntry(m); mi.methodsIndex.put(key, me); addMethodEntry(mi.methodOrdinalIndex, ordinalKey, me); if (!hasInterfaceInParamList) { addMethodEntry(mi.remoteOrdinalIndex, ordinalKey, me); } log.debug("processed {}", me); } // log.debug("cached {}'s {} methods and {} declared methods", // object.getSimpleName(), methods.length, // mi.remoteMethods.keySet().size()); objectCache.put(object.getTypeName(), mi); log.info("cached {} {} methods with {} ordinal signatures in {} ms", object.getSimpleName(), mi.methodsIndex.size(), mi.methodOrdinalIndex.size(), System.currentTimeMillis() - start); } private void addMethodEntry(Map<String, List<MethodEntry>> index, String ordinalKey, MethodEntry me) { if (!index.containsKey(ordinalKey)) { List<MethodEntry> mel = new ArrayList<>(); mel.add(me); index.put(ordinalKey, mel); } else { List<MethodEntry> mel = index.get(ordinalKey); mel.add(me); // FIXME - output more info on collisions // log.warn("{} method ordinal parameters collision ", ordinalKey); } } private boolean hasInterface(Method m) { Class<?>[] paramTypes = m.getParameterTypes(); boolean hasInterfaceInParamList = false; // exclude interfaces from this index - the preference in design would // be to have a // string {name} reference to refer to the service instance, however, // within in-process // python binding, using a reference to an interface is preferred for (Class<?> paramType : paramTypes) { if (paramType.isInterface() && !paramType.getName().equals(List.class.getCanonicalName()) && !paramType.getName().equals(Map.class.getCanonicalName())) { // skipping not applicable for remote invoking hasInterfaceInParamList = true; break; } } return hasInterfaceInParamList; } /** * clears all cache */ public void clear() { objectCache.clear(); } public int getObjectSize() { return objectCache.size(); } public int getMethodSize() { int size = 0; for (MethodIndex mi : objectCache.values()) { size += mi.methodsIndex.size(); } return size; } public Method getMethod(Class<?> object, String methodName, Class<?>... paramTypes) throws ClassNotFoundException { String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; ++i) { if (paramTypes[i] == null) { paramTypeNames[i] = null; } else { paramTypeNames[i] = paramTypes[i].getTypeName(); } } return getMethod(object.getTypeName(), methodName, paramTypeNames); } /** * Use case for in-process non-serialized messages with actual data parameters * * @param objectType * - the object to invoke against * @param methodName * - method name * @param params * - actual parameter * @return - the method to invoke * @throws ClassNotFoundException */ public Method getMethod(Class<?> objectType, String methodName, Object... params) throws ClassNotFoundException { Class<?>[] paramTypes = getParamTypes(params); return getMethod(objectType, methodName, paramTypes); } public Class<?>[] getParamTypes(Object... params) { Class<?>[] paramTypes = null; if (params != null) { paramTypes = new Class<?>[params.length]; for (int i = 0; i < params.length; ++i) { if (params[i] == null) { paramTypes[i] = null; } else { paramTypes[i] = params[i].getClass(); } } } else { paramTypes = new Class<?>[0]; } return paramTypes; } /** * A full string interface to get a method - although this is potentially a * easy method to use, the most common use case would be used by the framework * which will automatically supply fully qualified type names. * * @param fullType * @param methodName * @param paramTypeNames * @return * @throws ClassNotFoundException */ public Method getMethod(String fullType, String methodName, String[] paramTypeNames) throws ClassNotFoundException { if (!objectCache.containsKey(fullType)) { // attempt to load it cacheMethodEntries(Class.forName(fullType)); } MethodIndex mi = objectCache.get(fullType); // make a key String key = makeKey(fullType, methodName, paramTypeNames); // get the method - (from the super-map of all methods) if (!mi.methodsIndex.containsKey(key)) { // a key for the method might not exist because when a key is generated by // code // utilizing the MethodCache - super-types or interfaces might be used in // the parameter list // if this is the case we will look based on methods and ordinals String ordinalKey = getMethodOrdinalKey(fullType, methodName, paramTypeNames.length); List<MethodEntry> possibleMatches = mi.methodOrdinalIndex.get(ordinalKey); if (possibleMatches == null) { // log.error("there were no possible matches for ordinal key {} - does // the method exist?", ordinalKey); // log.error("{}.{}.{}", fullType, methodName, paramTypeNames); return null; } if (possibleMatches.size() == 1) { // woohoo ! we're done - if there is a single match it makes the choice // easy ;) return possibleMatches.get(0).method; } else { // now it gets more complex with overloading // spin through the possibilites - see if all parameters can be coerced // into working for (MethodEntry me : possibleMatches) { boolean foundMatch = true; Class<?>[] definedTypes = me.method.getParameterTypes(); for (int i = 0; i < paramTypeNames.length; ++i) { Class<?> paramClass = null; try { paramClass = Class.forName(paramTypeNames[i]); } catch (ClassNotFoundException e) { log.error("while attempting to parameter match {} was not found", paramTypeNames[i], e); } if (!definedTypes[i].isAssignableFrom(paramClass)) { // parameter coercion fails - check other possiblities foundMatch = false; continue; } } if (!foundMatch) { // one of the parameters could not be coerced // look at other methods continue; } // We made it through matching all parameters ! // send back the winner - but lets cache the entry first // we will fill the cache here with a new explicit key key = makeKey(fullType, methodName, paramTypeNames); mi.methodsIndex.put(key, me); return me.method; } } log.error("method {} with key signature {} not found in methodsIndex", methodName, key); return null; } // easy - exact key match return method return mi.methodsIndex.get(key).method; } public Map<String, Map<String, MethodEntry>> getRemoteMethods() { Map<String, Map<String, MethodEntry>> ret = new TreeMap<>(); for (String name : objectCache.keySet()) { ret.put(name, objectCache.get(name).methodsIndex); } return ret; } public Map<String, MethodEntry> getRemoteMethods(String type) { if (!type.contains(".")) { type = "org.myrobotlab.service." + type; } if (objectCache.containsKey(type)) { return objectCache.get(type).methodsIndex; } return null; } final public Object invokeOn(Object obj, String methodName, Object... params) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { if (obj == null) { log.error("invokeOn object is null"); return null; } Object retobj = null; MethodCache cache = MethodCache.getInstance(); Method method = cache.getMethod(obj.getClass(), methodName, params); retobj = method.invoke(obj, params); out(methodName, retobj); // <-- FIXME clean this up !!! return retobj; } private String getMethodKey(Class<?> object, Method method) { // make sure all parameters are boxed - and use those signature keys // msgs coming in will "always" be boxed so they will match this signature // keys Class<?>[] params = method.getParameterTypes(); String[] paramTypes = new String[method.getParameterTypes().length]; for (int i = 0; i < params.length; ++i) { Class<?> param = params[i]; if (param.isPrimitive()) { paramTypes[i] = boxPrimitive(param).getTypeName(); } else { paramTypes[i] = params[i].getTypeName(); } } return makeKey(object.getTypeName(), method.getName(), paramTypes); } public String makeKey(Class<?> object, String methodName, Class<?>... paramTypes) { String[] paramTypeNames = new String[paramTypes.length]; for (int i = 0; i < paramTypes.length; ++i) { paramTypeNames[i] = paramTypes[i].getTypeName(); } return makeKey(object.getTypeName(), methodName, paramTypeNames); } public String makeKey(String fullType, String methodName, String[] paramTypes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < paramTypes.length; ++i) { sb.append(paramTypes[i]); if (i < paramTypes.length - 1) { sb.append(","); } } return String.format("%s.%s(%s)", fullType, methodName, sb); } private String getMethodOrdinalKey(Class<?> object, Method method) { return getMethodOrdinalKey(object.getTypeName(), method.getName(), method.getParameterTypes().length); } private String getMethodOrdinalKey(String fullType, String methodName, int parameterSize) { String key = String.format("%s.%s-%s", fullType, methodName, parameterSize); return key; } public void out(String method, Object o) { } public List<MethodEntry> getOrdinalMethods(Class<?> object, String methodName, int parameterSize) { if (object == null) { log.error("getOrdinalMethods on a null object "); } String objectKey = object.getTypeName(); String ordinalKey = getMethodOrdinalKey(objectKey, methodName, parameterSize); MethodIndex methodIndex = objectCache.get(objectKey); if (methodIndex == null) { log.error("cannot find index of {} !", objectKey); return null; } return methodIndex.methodOrdinalIndex.get(ordinalKey); } public List<MethodEntry> getRemoteOrdinalMethods(Class<?> object, String methodName, int parameterSize) { if (object == null) { log.error("getRemoteOrdinalMethods object is null"); return null; } String objectKey = object.getTypeName(); String ordinalKey = getMethodOrdinalKey(objectKey, methodName, parameterSize); MethodIndex methodIndex = objectCache.get(objectKey); if (methodIndex == null) { log.error("cannot find index of {} !", objectKey); return null; } return methodIndex.remoteOrdinalIndex.get(ordinalKey); } public Object[] getDecodedJsonParameters(Class<?> clazz, String methodName, Object[] encodedParams) { if (encodedParams == null) { encodedParams = new Object[0]; } if (clazz == null) { log.error("cannot query method cache for null class"); } // get templates // List<MethodEntry> possible = getOrdinalMethods(clazz, methodName, // encodedParams.length); List<MethodEntry> possible = getRemoteOrdinalMethods(clazz, methodName, encodedParams.length); if (possible == null) { log.error("getOrdinalMethods -> {}.{} with ordinal {} does not exist", clazz.getSimpleName(), methodName, encodedParams.length); return null; } Object[] params = new Object[encodedParams.length]; // iterate through templates - attempt to decode for (int p = 0; p < possible.size(); ++p) { Class<?>[] paramTypes = possible.get(p).getParameterTypes(); try { for (int i = 0; i < encodedParams.length; ++i) { if (encodedParams[i].getClass() == LinkedTreeMap.class) { // specific gson implementation // rather than double encode everything - i have chosen // to re-encode objects back to string since gson will decode them // all ot linked tree maps - if the json decoder changes from gson // this will probably need to change too encodedParams[i] = CodecUtils.toJson(encodedParams[i]); } params[i] = CodecUtils.fromJson((String) encodedParams[i], paramTypes[i]); } // successfully decoded params return params; } catch (Exception e) { log.info("getDecodedParameters threw clazz {} method {} params {} ", clazz, methodName, encodedParams.length, e.getMessage()); } } // if successful return new msg log.error("requested getDecodedJsonParameters({}, {},{}) could not decode", clazz.getSimpleName(), methodName, encodedParams); return null; } public static String formatParams(Object[] params) { StringBuilder sb = new StringBuilder(); if (params != null) { for (int i = 0; i < params.length; ++i) { sb.append(params[i].getClass().getSimpleName()); if (i < params.length - 1) { sb.append(", "); } } } return sb.toString(); } public List<MethodEntry> query(String fullClassName, String methodName) { MethodIndex methodIndex = objectCache.get(fullClassName); String keyPart = String.format("%s.%s(", fullClassName, methodName); List<MethodEntry> ret = new ArrayList<>(); for (String key : methodIndex.methodsIndex.keySet()) { if (key.startsWith(keyPart)) { ret.add(methodIndex.methodsIndex.get(key)); } } return ret; } }
package massim.scenario.city; import massim.protocol.scenario.city.data.JobData; import massim.util.Log; import massim.util.RNG; import massim.protocol.messagecontent.Action; import massim.scenario.city.data.*; import massim.scenario.city.data.facilities.*; import java.util.*; import java.util.stream.Collectors; import static massim.protocol.scenario.city.Actions.*; /** * How else to execute agent actions. */ public class ActionExecutor { // scenario-specific failure-codes public final static String SUCCESSFUL = "successful"; private final static String FAILED_COUNTERPART = "failed_counterpart"; private final static String FAILED_LOCATION = "failed_location"; public final static String FAILED_NO_ROUTE = "failed_no_route"; private final static String FAILED_UNKNOWN_ITEM = "failed_unknown_item"; private final static String FAILED_UNKNOWN_AGENT = "failed_unknown_agent"; private final static String FAILED_ITEM_AMOUNT = "failed_item_amount"; private final static String FAILED_CAPACITY = "failed_capacity"; private final static String FAILED_UNKNOWN_FACILITY = "failed_unknown_facility"; private final static String FAILED_WRONG_FACILITY = "failed_wrong_facility"; private final static String FAILED_TOOLS = "failed_tools"; private final static String FAILED_ITEM_TYPE = "failed_item_type"; private final static String FAILED_UNKNOWN_JOB = "failed_unknown_job"; private final static String FAILED_JOB_STATUS = "failed_job_status"; private final static String FAILED_JOB_TYPE = "failed_job_type"; private final static String PARTIAL_SUCCESS = "successful_partial"; private final static String FAILED_WRONG_PARAM = "failed_wrong_param"; private final static String FAILED_RESOURCES = "failed_resources"; private final static String FAILED = "failed"; private final static String USELESS = "useless"; private final static String FAILED_FACILITY_STATE = "failed_facility_state"; private WorldState world; /** * Contains all agents that actually received items this turn. */ private Set<Entity> receivers; /** * Contains all agents that want to assemble an item this turn. */ private Set<Entity> assemblers; /** * Keys: assemblers, Values: sets of assistants */ private Map<Entity, Set<Entity>> assistants; ActionExecutor(WorldState world) { this.world = world; } /** * Prepares everything for the new step. * So, should be called before each step. */ void preProcess(){ receivers = new HashSet<>(); assemblers = new HashSet<>(); assistants = new HashMap<>(); } /** * Execute an action for a given agent. * @param agent the name of the agent * @param actions the actions of all agents * @param stepNo the current step */ void execute(String agent, Map<String, Action> actions, int stepNo) { Entity entity = world.getEntity(agent); Action action = actions.get(agent); if(action == null){ Log.log(Log.Level.CRITICAL, "Step " + stepNo + ": No action for agent " + agent + " provided."); action = Action.STD_NO_ACTION; } entity.setLastAction(action); List<String> params = action.getParameters(); switch (action.getActionType()){ case Action.RANDOM_FAIL: entity.setLastActionResult(FAILED); break; case Action.NO_ACTION: entity.setLastActionResult(SUCCESSFUL); break; case GO_TO: if(params.size() == 0){ // no params => follow existing route if(entity.getRoute() == null){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } } Location destination; if(params.size() == 1){ // param must be facility name Facility facility = world.getFacility(params.get(0)); if(facility == null || facility instanceof ResourceNode){ entity.setLastActionResult(FAILED_UNKNOWN_FACILITY); break; } destination = facility.getLocation(); } else if(params.size() == 2){ // params must be (lat,lon) destination = Location.parse(params.get(0), params.get(1)); } else{ // too many parameters entity.setLastActionResult(FAILED_WRONG_PARAM); break; } if (destination != null) entity.setRoute( world.getMap().findRoute(entity.getLocation(), destination, entity.getRole().getPermissions())); else{ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } entity.setLastActionResult(entity.advanceRoute(world.getGotoCost())? SUCCESSFUL : FAILED_NO_ROUTE); break; case BUILD: if(params.size() > 1){ entity.setLastActionResult(FAILED_WRONG_PARAM); return; } if(params.size() == 1) { // param must be well type name Facility facility = world.getFacilityByLocation(entity.getLocation()); if(facility != null) { // current location is not free entity.setLastActionResult(FAILED_LOCATION); return; } WellType wellType = world.getWellType(params.get(0)); if(wellType == null) { entity.setLastActionResult(FAILED_UNKNOWN_FACILITY); return; } TeamState team = world.getTeam(world.getTeamForAgent(agent)); if(team.getMassium() < wellType.getCost()){ entity.setLastActionResult(FAILED_RESOURCES); return; } world.addWell(wellType, agent); team.subMassium(wellType.getCost()); entity.setLastActionResult(SUCCESSFUL); return; } else { // build up existing well Facility facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null) { entity.setLastActionResult(FAILED_LOCATION); return; } if(!(facility instanceof Well)) { entity.setLastActionResult(FAILED_WRONG_FACILITY); return; } Well well = (Well) facility; well.build(entity.getSkill()); } break; case DISMANTLE: if(params.size() > 0){ entity.setLastActionResult(FAILED_WRONG_PARAM); return; } Facility fac = world.getFacilityByLocation(entity.getLocation()); if(fac == null || !(fac instanceof Well)) { entity.setLastActionResult(FAILED_LOCATION); return; } Well well = (Well) fac; entity.setLastActionResult(SUCCESSFUL); if(well.dismantle(entity.getSkill())){ world.removeWell(well); int refund = (int) (RNG.nextDouble() * .5 * well.getCost()); // refund up to 50% of a well's cost TeamState team = world.getTeam(world.getTeamForAgent(agent)); team.addMassium(refund); } break; case GIVE: // 3 params (agent, item, amount) if(params.size() != 3){ entity.setLastActionResult(FAILED_WRONG_PARAM); } else { String receiver = params.get(0); Item item = world.getItemByName(params.get(1)); Entity receiverEntity = world.getEntity(receiver); int amount = -1; try { amount = Integer.parseInt(params.get(2)); } catch (NumberFormatException ignored) {} if(receiverEntity == null || amount < 0){ entity.setLastActionResult(FAILED_WRONG_PARAM); } else if (item == null) { entity.setLastActionResult(FAILED_UNKNOWN_ITEM); } else if (!actions.get(receiver).getActionType().equals(RECEIVE)) { entity.setLastActionResult(FAILED_COUNTERPART); } else if (!receiverEntity.getLocation().inRange(entity.getLocation())) { entity.setLastActionResult(FAILED_LOCATION); } else if (amount > entity.getItemCount(item)) { entity.setLastActionResult(FAILED_ITEM_AMOUNT); } else if (receiverEntity.getFreeSpace() < amount * item.getVolume()) { entity.setLastActionResult(FAILED_CAPACITY); } else { entity.transferItems(receiverEntity, item, amount); entity.setLastActionResult(SUCCESSFUL); receivers.add(receiverEntity); } } break; case RECEIVE: break; // action is processed in give-action, result in postProcess() case STORE: // 2 params (item, amount) if(params.size() != 2){ entity.setLastActionResult(FAILED_WRONG_PARAM); return; } Facility facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null){ entity.setLastActionResult(FAILED_LOCATION); return; } else if(!(facility instanceof Storage)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); return; } Storage storage = (Storage)facility; Item item = world.getItemByName(params.get(0)); if(item == null){ entity.setLastActionResult(FAILED_UNKNOWN_ITEM); return; } int amount = -1; try{ amount = Integer.parseInt(params.get(1)); } catch(NumberFormatException ignored){} if(amount < 1 || amount > entity.getItemCount(item)){ entity.setLastActionResult(FAILED_ITEM_AMOUNT); return; } if(storage.getFreeSpace() < amount * item.getVolume()){ entity.setLastActionResult(FAILED_CAPACITY); return; } if(storage.store(item, amount, world.getTeamForAgent(agent))){ entity.setLastActionResult(SUCCESSFUL); entity.removeItem(item, amount); } else{ entity.setLastActionResult(FAILED); } break; case RETRIEVE: // 2 params (item, amount) case RETRIEVE_DELIVERED: // 2 params (item, amount) if(params.size() != 2){ entity.setLastActionResult(FAILED_WRONG_PARAM); return; } facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null){ entity.setLastActionResult(FAILED_LOCATION); return; } else if(!(facility instanceof Storage)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); return; } storage = (Storage)facility; item = world.getItemByName(params.get(0)); if(item == null){ entity.setLastActionResult(FAILED_UNKNOWN_ITEM); return; } amount = -1; try{ amount = Integer.parseInt(params.get(1)); } catch(NumberFormatException ignored){} int retrievable = action.getActionType().equals(RETRIEVE)? storage.getStored(item, world.getTeamForAgent(agent)) : storage.getDelivered(item, world.getTeamForAgent(agent)); if (amount < 1 || amount > retrievable){ entity.setLastActionResult(FAILED_ITEM_AMOUNT); return; } if(amount * item.getVolume() > entity.getFreeSpace()){ entity.setLastActionResult(FAILED_CAPACITY); return; } if(action.getActionType().equals(RETRIEVE)) storage.removeStored(item, amount, world.getTeamForAgent(agent)); else storage.removeDelivered(item, amount, world.getTeamForAgent(agent)); entity.addItem(item, amount); entity.setLastActionResult(SUCCESSFUL); break; case ASSEMBLE: // 1 param (item) if(params.size() != 1){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null){ entity.setLastActionResult(FAILED_LOCATION); break; } else if(!(facility instanceof Workshop)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); break; } assemblers.add(entity); assistants.putIfAbsent(entity, new HashSet<>()); break; case ASSIST_ASSEMBLE: // 1 param (agent) if(params.size() != 1){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } Entity assembler = world.getEntity(params.get(0)); if (assembler == null){ entity.setLastActionResult(FAILED_UNKNOWN_AGENT); break; } Action counterPartAction = actions.get(params.get(0)); if(counterPartAction != null && !counterPartAction.getActionType().equals(ASSEMBLE)){ entity.setLastActionResult(FAILED_COUNTERPART); break; } else if(!entity.getLocation().inRange(assembler.getLocation())){ entity.setLastActionResult(FAILED_LOCATION); break; } assistants.putIfAbsent(assembler, new HashSet<>()); assistants.get(assembler).add(entity); break; case DELIVER_JOB: // 1 param (job) if(params.size() != 1){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } Job job = world.getJob(params.get(0)); if(job == null){ entity.setLastActionResult(FAILED_UNKNOWN_JOB); break; } if(!job.isActive()){ entity.setLastActionResult(FAILED_JOB_STATUS); break; } if (!entity.getLocation().inRange(job.getStorage().getLocation())){ entity.setLastActionResult(FAILED_LOCATION); break; } if (job instanceof AuctionJob) { AuctionJob auctionJob = (AuctionJob) job; if (!auctionJob.isAssigned() || !auctionJob.getAuctionWinner().equals(world.getTeamForAgent(agent))){ entity.setLastActionResult(FAILED_JOB_STATUS); break; } } final int[] itemsUsed = {0}; job.getRequiredItems().forEach((it, qty) -> { int used = job.deliver(it, entity.getItemCount(it), world.getTeamForAgent(agent)); entity.removeItem(it, used); itemsUsed[0] += used; }); if (itemsUsed[0] > 0){ String teamName = world.getTeamForAgent(agent); if (job.checkCompletion(teamName)) { // add reward to completing team int reward = job instanceof AuctionJob? ((AuctionJob)job).getLowestBid() : job.getReward(); world.getTeam(teamName).addMassium(reward); // if job posted by another team, subtract payment if (!job.getPoster().equals(JobData.POSTER_SYSTEM)) world.getTeam(job.getPoster()).subMassium(reward); entity.setLastActionResult(SUCCESSFUL); break; } else { entity.setLastActionResult(PARTIAL_SUCCESS); break; } } else { entity.setLastActionResult(USELESS); break; } case BID_FOR_JOB: // 2 params (job, price) if(params.size() != 2){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } job = world.getJob(params.get(0)); if(job == null){ entity.setLastActionResult(FAILED_UNKNOWN_JOB); break; } int price = -1; try{ price = Integer.parseInt(params.get(1)); } catch(NumberFormatException ignored){} if(price < 0){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } if(!(job instanceof AuctionJob)){ entity.setLastActionResult(FAILED_JOB_TYPE); break; } AuctionJob auction = (AuctionJob) job; if(!(job.getStatus() == Job.JobStatus.AUCTION)){ entity.setLastActionResult(FAILED_JOB_STATUS); break; } auction.bid(world.getTeam(world.getTeamForAgent(agent)), price); entity.setLastActionResult(SUCCESSFUL); break; case DUMP: // 2 params (item, amount) if(params.size() != 2){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } facility = world.getFacilityByLocation(entity.getLocation()); if (facility == null){ entity.setLastActionResult(FAILED_LOCATION); break; } if (!(facility instanceof Dump)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); break; } item = world.getItemByName(params.get(0)); if (item == null){ entity.setLastActionResult(FAILED_UNKNOWN_ITEM); break; } amount = -1; try{ amount = Integer.parseInt(params.get(1)); } catch(NumberFormatException ignored){} if(amount < 1 || amount > entity.getItemCount(item)){ entity.setLastActionResult(FAILED_ITEM_AMOUNT); break; } entity.removeItem(item, amount); entity.setLastActionResult(SUCCESSFUL); break; case TRADE: // 2 params (item, amount) if(params.size() != 2) { entity.setLastActionResult(FAILED_WRONG_PARAM); break; } item = world.getItemByName(params.get(0)); if(item == null) { entity.setLastActionResult(FAILED_UNKNOWN_ITEM); return; } if(!item.needsAssembly()) { entity.setLastActionResult(FAILED_ITEM_TYPE); return; } amount = -1; try{ amount = Integer.parseInt(params.get(1)); } catch(NumberFormatException ignored){} if (amount < 1 || amount > entity.getItemCount(item)) { entity.setLastActionResult(FAILED_ITEM_AMOUNT); return; } fac = world.getFacilityByLocation(entity.getLocation()); if (fac == null || !(fac instanceof Shop)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); return; } Shop shop = (Shop) fac; entity.removeItem(item, amount); world.getTeam(world.getTeamForAgent(agent)).addMassium(item.getValue() * shop.getTradeModifier()); entity.setLastActionResult(SUCCESSFUL); return; case CHARGE: // no params if(params.size() != 0){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null){ entity.setLastActionResult(FAILED_LOCATION); break; } if(!(facility instanceof ChargingStation)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); break; } entity.charge(((ChargingStation)facility).getRate()); entity.setLastActionResult(SUCCESSFUL); break; case RECHARGE: // no params if(params.size() != 0){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } entity.charge(world.getRechargeRate() + RNG.nextInt(world.getRechargeRate() + 1)); entity.setLastActionResult(SUCCESSFUL); break; case CONTINUE: if (entity.getRoute() != null) entity.setLastActionResult(entity.advanceRoute(world.getGotoCost())? SUCCESSFUL : FAILED_NO_ROUTE); else // nothing happens successfully entity.setLastActionResult(SUCCESSFUL); break; case ABORT: entity.clearRoute(); entity.setLastActionResult(SUCCESSFUL); break; case GATHER: // no params if(params.size() != 0){ entity.setLastActionResult(FAILED_WRONG_PARAM); break; } facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null){ entity.setLastActionResult(FAILED_LOCATION); break; } if(!(facility instanceof ResourceNode)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); break; } ResourceNode node = (ResourceNode) facility; int resources = node.gather(entity.getSkill()); if(resources > 0){ int actual = Math.min(resources, entity.getFreeSpace() / node.getResource().getVolume()); if(actual == 0) { entity.setLastActionResult(FAILED_CAPACITY); break; } entity.addItem(node.getResource(), actual); entity.setLastActionResult(SUCCESSFUL); break; } else { entity.setLastActionResult(PARTIAL_SUCCESS); break; } case UPGRADE: if(params.size() != 1) { entity.setLastActionResult(FAILED_WRONG_PARAM); return; } facility = world.getFacilityByLocation(entity.getLocation()); if(facility == null){ entity.setLastActionResult(FAILED_LOCATION); break; } if(!(facility instanceof Shop)){ entity.setLastActionResult(FAILED_WRONG_FACILITY); break; } String upgradeName = params.get(0); Upgrade upgrade = world.getUpgrade(upgradeName); if(upgrade == null) { entity.setLastActionResult(FAILED_WRONG_PARAM); return; } TeamState teamState = world.getTeam(world.getTeamForAgent(agent)); if(teamState.getMassium() < upgrade.getCost()) { entity.setLastActionResult(FAILED_RESOURCES); return; } entity.upgrade(upgrade); teamState.subMassium(upgrade.getCost()); entity.setLastActionResult(SUCCESSFUL); return; default: entity.setLastAction(Action.STD_UNKNOWN_ACTION); entity.setLastActionResult(FAILED); } } /** * Sets things that can only be done after all actions have been processed. */ void postProcess(){ // set last action result for receiver agents world.getEntities().stream() .filter(r -> r.getLastAction().getActionType().equals(RECEIVE)) .forEach(r -> r.setLastActionResult(receivers.contains(r)? SUCCESSFUL : FAILED_COUNTERPART)); // handle assembly // assemblers and assistants are performing correct actions in the correct facility // agents are in the same workshop assemblers.forEach(assembler -> { Item item = world.getItemByName(assembler.getLastAction().getParameters().get(0)); if(item == null){ assembler.setLastActionResult(FAILED_UNKNOWN_ITEM); assistants.get(assembler).forEach(a -> a.setLastActionResult(FAILED_COUNTERPART)); } else if(!item.needsAssembly()){ assembler.setLastActionResult(FAILED_ITEM_TYPE); assistants.get(assembler).forEach(a -> a.setLastActionResult(FAILED_COUNTERPART)); } else{ // item exists and can be assembled Set<Entity> assembleTeam = new HashSet<>(assistants.get(assembler)); assembleTeam.add(assembler); Set<Role> presentRoles = assembleTeam.stream().map(Entity::getRole).collect(Collectors.toSet()); Set<Role> missingRoles = new HashSet<>(item.getRequiredRoles()); missingRoles.removeAll(presentRoles); if(missingRoles.size() > 0){ assembler.setLastActionResult(FAILED_TOOLS); assistants.get(assembler).forEach(a -> a.setLastActionResult(FAILED_TOOLS)); } else{ // all "tools" available, check items now // sort assembly helpers by name List<Entity> assemblyAssistants = new ArrayList<>(assistants.get(assembler)); assemblyAssistants.sort((e1, e2) -> { String ag1 = world.getAgentForEntity(e1); String ag2 = world.getAgentForEntity(e2); return ag1.length() == ag2.length()? ag1.compareTo(ag2) : ag1.length() - ag2.length(); }); String assemblyResult = canBeAssembled(item, assembler, assemblyAssistants, true); if(assemblyResult.equals(SUCCESSFUL)){ assembler.setLastActionResult(SUCCESSFUL); assistants.get(assembler).forEach(a -> a.setLastActionResult(SUCCESSFUL)); } else{ assembler.setLastActionResult(assemblyResult); assistants.get(assembler).forEach(a -> a.setLastActionResult(FAILED_COUNTERPART)); } } } }); } /** * Checks if a team of entities has all necessary items (except tools) to assemble an item. * If called to apply changes, checks first whether changes can be applied in total * (so it does not need to be called to check that from the outside before) * @param item the item type to assemble * @param assembler the head assembler * @param assistants the assistant assemblers (<b>sorted by connected agent's name</b>) * @param applyChanges whether to apply the changes (i.e. remove parts and add product to head assembler) * @return the result of the assemble action, i.e. one of {@link #SUCCESSFUL}, {@link #FAILED_ITEM_TYPE}, * {@link #FAILED_ITEM_AMOUNT}, {@link #FAILED_CAPACITY} */ private String canBeAssembled(Item item, Entity assembler, List<Entity> assistants, boolean applyChanges){ if(!item.needsAssembly()) return FAILED_ITEM_TYPE; if(applyChanges){ String dryRunResult = canBeAssembled(item, assembler, assistants, false); if(!dryRunResult.equals(SUCCESSFUL)) return dryRunResult; } int freedVolume = 0; for(Item part: item.getRequiredItems()){ int needed = 1; int take = Math.min(needed, assembler.getItemCount(part)); if(applyChanges) assembler.removeItem(part, take); needed -= take; freedVolume += take * item.getVolume(); if(needed > 0){ for (Entity assistant : assistants) { take = Math.min(needed, assistant.getItemCount(part)); if(applyChanges) assistant.removeItem(part, take); needed -= take; if (needed == 0) break; } } if (needed > 0) return FAILED_ITEM_AMOUNT; } if(item.getVolume() > assembler.getFreeSpace() + freedVolume) return FAILED_CAPACITY; // new item would not fit into head assembler if(applyChanges) assembler.addItem(item, 1); return SUCCESSFUL; } }
package scalac.ast; import scalac.Global; import scalac.ast.Tree.*; import scalac.atree.AConstant; import scalac.symtab.*; import scalac.util.*; /** * This class provides method to build attributed trees. * * @author Martin Odersky, Christine Roeckl * @version 1.0 */ public class TreeGen implements Kinds, Modifiers, TypeTags { // // Private Fields /** The global environment */ private final Global global; /** The global definitions */ private final Definitions definitions; /** The tree factory */ private final TreeFactory make; /** Initializes this instance. */ public TreeGen(Global global) { this(global, global.make); } /** Initializes this instance. */ public TreeGen(Global global, TreeFactory make) { this.global = global; this.definitions = global.definitions; this.make = make; } // // Public Methods - Building types /** Builds type references corresponding to given symbols. */ public Tree[] mkTypeRefs(int pos, Symbol[] syms) { if (syms.length == 0) return Tree.EMPTY_ARRAY; Tree[] trees = new Tree[syms.length]; for (int i = 0; i < trees.length; i++) trees[i] = mkTypeRef(pos, syms[i]); return trees; } /** Builds a type reference corresponding to given symbol. */ public Tree mkTypeRef(int pos, Symbol sym) { assert sym.kind == TYPE: Debug.show(sym); sym.flags |= ACCESSED; return mkType(pos, sym.nextType()); } /** Builds trees corresponding to given types. */ public Tree[] mkTypes(int pos, Type[] types) { if (types.length == 0) return Tree.EMPTY_ARRAY; Tree[] trees = new Tree[types.length]; for (int i = 0; i < trees.length; i++) trees[i] = mkType(pos, types[i]); return trees; } /** Builds a tree corresponding to given type. */ public Tree mkType(int pos, Type type) { return TypeTerm(pos, type); } /** Builds a TypeTerm node corresponding to given type. */ public TypeTerm TypeTerm(int pos, Type type) { TypeTerm tree = make.TypeTerm(pos); tree.setType(type); return tree; } // // Public Methods - Building constants /** Builds a unit literal. */ public Tree mkUnitLit(int pos) { return Literal(pos, AConstant.UNIT); } /** Builds a boolean literal. */ public Tree mkBooleanLit(int pos, boolean value) { return Literal(pos, AConstant.BOOLEAN(value)); } /** Builds a byte literal. */ public Tree mkByteLit(int pos, byte value) { return Literal(pos, AConstant.BYTE(value)); } /** Builds a short literal. */ public Tree mkShortLit(int pos, short value) { return Literal(pos, AConstant.SHORT(value)); } /** Builds a character literal. */ public Tree mkCharLit(int pos, char value) { return Literal(pos, AConstant.CHAR(value)); } /** Builds an integer literal */ public Tree mkIntLit(int pos, int value) { return Literal(pos, AConstant.INT(value)); } /** Builds a long literal. */ public Tree mkLongLit(int pos, long value) { return Literal(pos, AConstant.LONG(value)); } /** Builds a float literal. */ public Tree mkFloatLit(int pos, float value) { return Literal(pos, AConstant.FLOAT(value)); } /** Builds a double literal. */ public Tree mkDoubleLit(int pos, double value) { return Literal(pos, AConstant.DOUBLE(value)); } /** Builds a string literal. */ public Tree mkStringLit(int pos, String value) { return Literal(pos, AConstant.STRING(value)); } /** Builds a null literal. */ public Tree mkNullLit(int pos) { return Literal(pos, AConstant.NULL); } /** Builds a zero literal. */ public Tree mkZeroLit(int pos) { return Literal(pos, AConstant.ZERO); } /** Builds a default zero value according to given type tag. */ public Tree mkDefaultValue(int pos, int tag) { switch (tag) { case UNIT : return mkUnitLit(pos); case BOOLEAN: return mkBooleanLit(pos, false); case BYTE : return mkByteLit(pos, (byte)0); case SHORT : return mkShortLit(pos, (short)0); case CHAR : return mkCharLit(pos, '\0'); case INT : return mkIntLit(pos, 0); case LONG : return mkLongLit(pos, 0l); case FLOAT : return mkFloatLit(pos, 0f); case DOUBLE : return mkDoubleLit(pos, 0d); default : throw Debug.abort("unknown type tag: " + tag); } } /** Builds a default zero value according to given type. */ public Tree mkDefaultValue(int pos, Type type) { if (definitions.ALLREF_TYPE().isSubType(type)) return mkNullLit(pos); switch (type.unbox()) { case UnboxedType(int tag): return mkDefaultValue(pos, tag); } return mkZeroLit(pos); } /** Builds a Literal node of given value. */ public Literal Literal(int pos, AConstant value) { Literal tree = make.Literal(pos, value); global.nextPhase(); tree.setType(definitions.atyper.type(value)); global.prevPhase(); return tree; } // // Public Methods - Building references /** * Builds a reference to primary constructor of given class with * given qualifier. */ public Tree mkPrimaryConstructorRef(int pos, Tree qualifier, Symbol clasz){ return mkRef(pos, qualifier, primaryConstructorOf(clasz)); } public Tree mkPrimaryConstructorRef(Tree qualifier, Symbol clasz) { return mkPrimaryConstructorRef(qualifier.pos, qualifier, clasz); } /** * Builds a reference to primary constructor of given class with * given stable prefix. */ public Tree mkPrimaryConstructorRef(int pos, Type stable, Symbol clasz) { return mkRef(pos, stable, primaryConstructorOf(clasz)); } /** * Builds a local reference to primary constructor of given class. */ public Tree mkPrimaryConstructorLocalRef(int pos, Symbol clasz) { return mkLocalRef(pos, primaryConstructorOf(clasz)); } /** * Builds a global reference to primary constructor of given * class. */ public Tree mkPrimaryConstructorGlobalRef(int pos, Symbol clasz) { return mkGlobalRef(pos, primaryConstructorOf(clasz)); } /** Builds local references to given symbols. */ public Tree[] mkLocalRefs(int pos, Symbol[] symbols) { if (symbols.length == 0) return Tree.EMPTY_ARRAY; Tree[] trees = new Tree[symbols.length]; for (int i = 0; i < trees.length; i++) trees[i] = mkLocalRef(pos, symbols[i]); return trees; } /** Builds global references to given symbols. */ public Tree[] mkGlobalRefs(int pos, Symbol[] symbols) { if (symbols.length == 0) return Tree.EMPTY_ARRAY; Tree[] trees = new Tree[symbols.length]; for (int i = 0; i < trees.length; i++) trees[i] = mkGlobalRef(pos, symbols[i]); return trees; } /** Builds a reference to given symbol with given qualifier. */ public Tree mkRef(int pos, Tree qualifier, Symbol symbol) { return Select(pos, qualifier, symbol); } public Tree mkRef(Tree qualifier, Symbol symbol) { return mkRef(qualifier.pos, qualifier, symbol); } /** * Builds a reference to given symbol with given stable prefix. */ public Tree mkRef(int pos, Type stable, Symbol symbol) { switch (stable) { case NoPrefix: return Ident(pos, symbol); case ThisType(Symbol clasz): if (clasz.isRoot()) return Ident(pos, symbol); // !!! remove ? if (clasz.isPackage()) return mkRef(pos, mkGlobalRef(pos, clasz.module()), symbol); return mkRef(pos, This(pos, clasz), symbol); case SingleType(Type prefix, Symbol member): Tree tree = mkRef(pos, prefix, member); switch (tree.type()) { case MethodType(Symbol[] params, _): assert params.length == 0: tree.type(); tree = Apply(pos, tree); } return mkRef(pos, tree, symbol); default: throw Debug.abort("illegal case", stable); } } /** Builds a local reference to given symbol. */ public Tree mkLocalRef(int pos, Symbol symbol) { assert symbol.isTerm(): Debug.show(symbol); return mkRef(pos, symbol.owner().thisType(), symbol); } /** Builds a global reference to given symbol. */ public Tree mkGlobalRef(int pos, Symbol symbol) { assert symbol.isTerm(): Debug.show(symbol); Symbol owner = symbol.owner(); if (owner.isRoot()) return Ident(pos, symbol); assert owner.isModuleClass(): Debug.show(symbol); return mkRef(pos, mkGlobalRef(pos, owner.module()), symbol); } /** Builds a This node corresponding to given class. */ public This This(int pos, Symbol clazz) { assert clazz.isClassType(): Debug.show(clazz); This tree = make.This(pos, clazz); global.nextPhase(); tree.setType(clazz.thisType()); global.prevPhase(); return tree; } /** Builds a Super node corresponding to given class. */ public Super Super(int pos, Symbol clazz) { assert clazz.isClass(): Debug.show(clazz); Super tree = make.Super(pos, clazz, TypeNames.EMPTY); global.nextPhase(); tree.setType(clazz.thisType()); global.prevPhase(); return tree; } /** Builds an Ident node corresponding to given symbol. */ public Ident Ident(int pos, Symbol sym) { assert sym.isTerm(): Debug.show(sym); sym.flags |= ACCESSED; Ident tree = make.Ident(pos, sym); global.nextPhase(); Type type; if (sym.isInitializer()) { type = sym.type(); Symbol[] tparams = sym.owner().typeParams(); if (tparams.length != 0) type = Type.PolyType(tparams, type); } else { type = sym.owner().thisType().memberStabilizedType(sym); } tree.setType(type); global.prevPhase(); return tree; } /** * Builds a Select node corresponding to given symbol selected * from given qualifier. */ public Select Select(int pos, Tree qualifier, Symbol sym) { assert sym.isTerm(): Debug.show(sym); sym.flags |= ACCESSED | SELECTOR; Select tree = make.Select(pos, sym, qualifier); global.nextPhase(); tree.setType(qualifier.type.memberStabilizedType(sym)); global.prevPhase(); return tree; } public Select Select(Tree qualifier, Symbol sym) { return Select(qualifier.pos, qualifier, sym); } // // Public Methods - Building applications /** * Builds an application with given function, type arguments and * value arguments. */ public Tree mkApplyTV(int pos, Tree fn, Type[] targs, Tree[] vargs) { if (targs.length != 0) fn = TypeApply(pos, fn, mkTypes(pos, targs)); return Apply(pos, fn, vargs); } public Tree mkApplyTV(Tree fn, Type[] targs, Tree[] vargs) { return mkApplyTV(fn.pos, fn, targs, vargs); } public Tree mkApplyTV(int pos, Tree fn, Tree[] targs, Tree[] vargs) { if (targs.length != 0) fn = TypeApply(pos, fn, targs); return Apply(pos, fn, vargs); } public Tree mkApplyTV(Tree fn, Tree[] targs, Tree[] vargs) { return mkApplyTV(fn.pos, fn, targs, vargs); } /** * Builds an application with given function and type arguments * and with no value arguments. */ public Tree mkApplyT_(int pos, Tree fn, Type[] targs) { return mkApplyTV(pos, fn, targs, Tree.EMPTY_ARRAY); } public Tree mkApplyT_(Tree fn, Type[] targs) { return mkApplyT_(fn.pos, fn, targs); } public Tree mkApplyT_(int pos, Tree fn, Tree[] targs) { return mkApplyTV(pos, fn, targs, Tree.EMPTY_ARRAY); } public Tree mkApplyT_(Tree fn, Tree[] targs) { return mkApplyT_(fn.pos, fn, targs); } /** * Builds an application with given function, no type arguments * and given value arguments. */ public Tree mkApply_V(int pos, Tree fn, Tree[] vargs) { return mkApplyTV(pos, fn, Tree.EMPTY_ARRAY, vargs); } public Tree mkApply_V(Tree fn, Tree[] vargs) { return mkApply_V(fn.pos, fn, vargs); } /** * Builds an application with given function and no type arguments * and no value arguments. */ public Tree mkApply__(int pos, Tree fn) { return mkApplyTV(pos, fn, Tree.EMPTY_ARRAY, Tree.EMPTY_ARRAY); } public Tree mkApply__(Tree fn) { return mkApply__(fn.pos, fn); } /** Builds a TypeApply node with given function and arguments. */ public TypeApply TypeApply(int pos, Tree fn, Type[] targs) { return TypeApply(pos, fn, mkTypes(pos, targs)); } public TypeApply TypeApply(Tree fn, Type[] targs) { return TypeApply(fn.pos, fn, targs); } public TypeApply TypeApply(int pos, Tree fn, Tree[] targs) { switch (fn.type()) { case Type.OverloadedType(_, _): // TreeGen only builds trees, names must already be resolved throw Debug.abort("unresolved name", fn + " - " + fn.type); case Type.PolyType(Symbol[] tparams, Type restpe): global.nextPhase(); restpe = restpe.subst(tparams, Tree.typeOf(targs)); global.prevPhase(); return (TypeApply)make.TypeApply(pos, fn, targs).setType(restpe); default: throw Debug.abort("illegal case", fn + " - " + fn.type()); } } public TypeApply TypeApply(Tree fn, Tree[] targs) { return TypeApply(fn.pos, fn, targs); } /** Builds an Apply node with given function and arguments. */ public Apply Apply(int pos, Tree fn, Tree[] vargs) { switch (fn.type()) { case Type.OverloadedType(_, _): // TreeGen only builds trees, names must already be resolved throw Debug.abort("unresolved name", fn + " - " + fn.type()); case Type.MethodType(Symbol[] vparams, Type restpe): return (Apply)make.Apply(pos, fn, vargs).setType(restpe); default: throw Debug.abort("illegal case", fn + " - " + fn.type()); } } public Apply Apply(Tree fn, Tree[] vargs) { return Apply(fn.pos, fn, vargs); } /** Builds an Apply node with given function and no arguments. */ public Apply Apply(int pos, Tree fn) { return Apply(pos, fn, Tree.EMPTY_ARRAY); } public Apply Apply(Tree fn) { return Apply(fn.pos, fn); } // // Public Methods - Building expressions - Simple nodes /** Flattens the given tree array by inlining Block nodes. */ public Tree[] flatten_(Tree[] trees) { boolean copy = false; int length = 0; for (int i = 0; i < trees.length; i++) { switch (trees[i]) { case Empty: copy = true; length -= 1; continue; case Block(Tree[] stats, Tree value): copy = true; length += stats.length + 1; continue; } length += 1; } if (!copy) return trees; Tree[] clone = new Tree[length]; for (int i = 0, o = 0; i < trees.length; i++) { switch (trees[i]) { case Empty: continue; case Block(Tree[] stats, Tree value): for (int j = 0; j < stats.length; j++) clone[o++] = stats[j]; clone[o++] = value; continue; } clone[o++] = trees[i]; } return clone; } /** Builds an import of all names of given qualifier. */ public Import mkImportAll(int pos, Tree qualifier) { return Import(pos, qualifier, new Name[]{Names.IMPORT_WILDCARD}); } public Import mkImportAll(Tree qualifier) { return mkImportAll(qualifier.pos, qualifier); } public Import mkImportAll(int pos, Symbol qualifier) { return mkImportAll(pos, mkGlobalRef(pos, qualifier)); } /** Builds an instance test with given value and type. */ public Tree mkIsInstanceOf(int pos, Tree value, Type type) { Type[] targs = new Type[]{type}; return mkApplyT_(pos, Select(value, definitions.ANY_IS), targs); } public Tree mkIsInstanceOf(Tree value, Type type) { return mkIsInstanceOf(value.pos, value, type); } /** Builds a cast with given value and type. */ public Tree mkAsInstanceOf(int pos, Tree value, Type type) { Type[] targs = new Type[]{type}; return mkApplyT_(pos, Select(value, definitions.ANY_AS), targs); } public Tree mkAsInstanceOf(Tree value, Type type) { return mkAsInstanceOf(value.pos, value, type); } /** Builds an expression of type Unit with given statements. */ public Tree mkUnitBlock(int pos, Tree[] stats) { return mkBlock(pos, stats, mkUnitLit(pos)); } /** Builds an expression of type Unit with given statement. */ public Tree mkUnitBlock(int pos, Tree stat) { return mkUnitBlock(pos, new Tree[]{stat}); } public Tree mkUnitBlock(Tree stat) { return mkUnitBlock(stat.pos, stat); } /** Builds an expression with given statements and value. */ public Tree mkBlock(int pos, Tree[] stats, Tree value) { if (stats.length == 0) return value; return Block(pos, stats, value); // !!! add flatten? } public Tree mkBlock(Tree[] stats, Tree value) { return mkBlock((stats.length!=0 ? stats[0] : value).pos, stats, value); } /** Builds an expression with given statement and value. */ public Tree mkBlock(int pos, Tree stat, Tree value) { switch (stat) { case Empty: return value; case Block(Tree[] block_stats, Tree block_value): Tree[] stats = Tree.cloneArray(block_stats, 1); stats[block_stats.length] = block_value; return Block(stat.pos, stats, value); default: return Block(pos, new Tree[]{stat}, value); } } public Tree mkBlock(Tree stat, Tree value) { return mkBlock(stat.pos, stat, value); } /** Builds an Import node with given qualifier and names. */ public Import Import(int pos, Tree qualifier, Name[] names) { Import tree = make.Import(pos, qualifier.symbol(), qualifier, names); tree.setType(Type.NoType); return tree; } public Import Import(Tree qualifier, Name[] names) { return Import(qualifier.pos, qualifier, names); } public Import Import(int pos, Symbol qualifier, Name[] names) { return Import(pos, mkGlobalRef(pos, qualifier), names); } /** Builds a Template node with given symbol, parents and body. */ public Template Template(int pos, Symbol local, Tree[]parents, Tree[]body){ Template tree = make.Template(pos, local, parents, body); tree.setType(Type.NoType); return tree; } /** Builds a Block node with given statements and value. */ public Block Block(int pos, Tree[] stats, Tree value) { inline: switch (value) { case Block(Tree[] value_stats, Tree value_value): int count = 0; for (int i = 0; i < value_stats.length; i++) { if (value_stats[i].definesSymbol()) break inline; if (value_stats[i] != Tree.Empty) count++; } Tree[] array = Tree.cloneArray(stats, count); for (int i = 0, j = stats.length; i < value_stats.length; i++) { if (value_stats[i] != Tree.Empty) array[j++] = value_stats[i]; } stats = array; value = value_value; } Block tree = make.Block(pos, stats, value); tree.setType(value.type()); return tree; } public Block Block(Tree[] stats, Tree value) { return Block((stats.length != 0 ? stats[0] : value).pos, stats, value); } /** Builds an Assign node corresponding to "<lhs> = <rhs>". */ public Assign Assign(int pos, Tree lhs, Tree rhs) { Assign tree = make.Assign(pos, lhs, rhs); global.nextPhase(); tree.setType(definitions.UNIT_TYPE()); global.prevPhase(); return tree; } public Assign Assign(Tree lhs, Tree rhs) { return Assign(lhs.pos, lhs, rhs); } /** Builds an If node with given components and type. */ public If If(int pos, Tree cond, Tree thenpart, Tree elsepart, Type type) { assert assertTreeSubTypeOf(thenpart, type); assert assertTreeSubTypeOf(elsepart, type); If tree = make.If(pos, cond, thenpart, elsepart); tree.setType(type); return tree; } public If If(Tree cond, Tree thenpart, Tree elsepart, Type type) { return If(cond.pos, cond, thenpart, elsepart, type); } /** Builds an If node with given condition and branches. */ public If If(int pos, Tree cond, Tree thenpart, Tree elsepart) { global.nextPhase(); Type type = thenpart.getType().isSameAs(elsepart.getType()) ? thenpart.type : Type.lub(new Type[] {thenpart.getType(), elsepart.getType()}); global.prevPhase(); return If(pos, cond, thenpart, elsepart, type); } public If If(Tree cond, Tree thenpart, Tree elsepart) { return If(cond.pos, cond, thenpart, elsepart); } /** Builds a Switch node with given components and type. * @param tags a <b>sorted</b> array of tags */ public Switch Switch(int pos, Tree test, int[] tags, Tree[] bodies, Tree otherwise, Type type) { for (int i = 0; i < bodies.length; i++) { assert assertTreeSubTypeOf(bodies[i], type); assert (i==0) || ( tags[i-1] < tags[i] ) : "expecting sorted tags"; } assert assertTreeSubTypeOf(otherwise, type); Switch tree = make.Switch(pos, test, tags, bodies, otherwise); tree.setType(type); return tree; } public Switch Switch(Tree test, int[] tags, Tree[] bodies, Tree otherwise, Type type) { return Switch(test.pos, test, tags, bodies, otherwise, type); } /** Builds a Switch node with given components. */ public Switch Switch(int pos, Tree test, int[] tags, Tree[] bodies, Tree otherwise) { Type[] types = new Type[bodies.length + 1]; for (int i = 0; i < bodies.length; i++) types[i] = bodies[i].getType(); types[bodies.length] = otherwise.getType(); global.nextPhase(); Type type = Type.lub(types); global.prevPhase(); return Switch(pos, test, tags, bodies, otherwise, type); } public Switch Switch(Tree test, int[] tags, Tree[] bodies, Tree otherwise){ return Switch(test.pos, test, tags, bodies, otherwise); } /** Builds a Return node of given method with given value. */ public Return Return(int pos, Symbol method, Tree value) { Return tree = make.Return(pos, method, value); tree.setType(definitions.ALL_TYPE()); return tree; } public Return Return(Symbol method, Tree value) { return Return(value.pos, method, value); } /** Builds a New node corresponding to "new <constr>". */ public Tree New(int pos, Tree constr) { Tree[] constrs = { constr }; Template templ = Template(pos, Symbol.NONE, constrs, Tree.EMPTY_ARRAY); New tree = make.New(pos, templ); tree.setType(constr.type); // after AddConstructor use type of symbol switch (constr) { case Apply(TypeApply(Tree fun, Tree[] targs), _): Symbol sym = fun.symbol(); if (sym == null || sym.isConstructor()) break; Type[] args = Tree.typeOf(targs); tree.setType(Type.appliedType(sym.owner().nextType(), args)); break; case Apply(Tree fun, _): Symbol sym = fun.symbol(); if (sym == null || sym.isConstructor()) break; tree.setType(sym.owner().nextType()); break; } return tree; } public Tree New(Tree constr) { return New(constr.pos, constr); } /** Builds a Typed nodes with given value and type. */ public Typed Typed(int pos, Tree value, Tree type) { Typed tree = make.Typed(pos, value, type); tree.setType(type.type()); return tree; } public Typed Typed(Tree value, Tree type) { return Typed(value.pos, value, type); } public Typed Typed(int pos, Tree value, Type type) { return Typed(pos, value, mkType(pos, type)); } public Typed Typed(Tree value, Type type) { return Typed(value.pos, value, type); } // // Public Methods - Building expressions - Lists /** Builds an empty list. */ public Tree mkNil(int pos) { return mkGlobalRef(pos, definitions.NIL); } /** Builds a list with given element type, head and tail. */ public Tree mkNewCons(int pos, Type element, Tree head, Tree tail) { // !!! these checks can be removed once they are done in Apply global.nextPhase(); assert head.type().isSubType(element): element + " -- " + head + " : " + head.type; assert tail.type().isSubType(definitions.LIST_TYPE(element)): element + " -- " + tail + " : " + tail.type; global.prevPhase(); return New( mkApplyTV( mkPrimaryConstructorGlobalRef(pos, definitions.CONS_CLASS), new Type[]{element}, new Tree[]{head, tail})); } public Tree mkNewCons(Type element, Tree head, Tree tail) { return mkNewCons(head.pos, element, head, tail); } /** Builds a list with given element type and values. */ public Tree mkNewList(int pos, Type element, Tree[] values) { Tree list = mkNil(pos); for (int i = values.length - 1; 0 <= i; i list = mkNewCons(pos, element, values[i], list); return list; } // // Public Methods - Building expressions - Arrays /** Builds a new array tree with given element type and length. */ public Tree mkNewArray(int pos, Type element, Tree length) { return New( mkApplyTV( mkPrimaryConstructorGlobalRef(pos, definitions.ARRAY_CLASS), new Type[]{element}, new Tree[]{length})); } public Tree mkNewArray(Type element, Tree length) { return mkNewArray(length.pos, element, length); } public Tree mkNewArray(int pos, Type element, int length) { return mkNewArray(pos, element, mkIntLit(pos, length)); } /** * Builds a new array tree with given element type and values. The * owner must be the owner of the created code. It is needed to * create a local variable. */ public Tree mkNewArray(int pos, Type element, Tree[] values, Symbol owner){ if (values.length == 0) return mkNewArray(pos, element, 0); Tree[] trees = new Tree[1 + values.length]; Symbol array = newLocal(pos, Names.array, owner, definitions.ARRAY_TYPE(element)); trees[0] = ValDef(array, mkNewArray(pos, element, values.length)); for (int i = 0; i < values.length; i++) trees[1 + i] = mkArraySet(Ident(pos, array), i, values[i]); return Block(pos, trees, Ident(pos, array)); } /** Builds an array length operation. */ public Tree mkArrayLength(int pos, Tree array) { Tree function = Select(pos, array, definitions.ARRAY_LENGTH()); return Apply(pos, function); } public Tree mkArrayLength(Tree array) { return mkArrayLength(array.pos, array); } /** Builds an array get operation. */ public Tree mkArrayGet(int pos, Tree array, Tree index) { Tree function = Select(pos, array, definitions.ARRAY_GET()); return Apply(pos, function, new Tree[] {index}); } public Tree mkArrayGet(Tree array, Tree index) { return mkArrayGet(array.pos, array, index); } public Tree mkArrayGet(int pos, Tree array, int index) { return mkArrayGet(pos, array, mkIntLit(pos, index)); } public Tree mkArrayGet(Tree array, int index) { return mkArrayGet(array.pos, array, index); } /** Builds an array set operation. */ public Tree mkArraySet(int pos, Tree array, Tree index, Tree value) { Tree function = Select(pos, array, definitions.ARRAY_SET()); return Apply(pos, function, new Tree[] {index, value}); } public Tree mkArraySet(Tree array, Tree index, Tree value) { return mkArraySet(array.pos, array, index, value); } public Tree mkArraySet(int pos, Tree array, int index, Tree value) { return mkArraySet(pos, array, mkIntLit(pos, index), value); } public Tree mkArraySet(Tree array, int index, Tree value) { return mkArraySet(array.pos, array, index, value); } // // Public Methods - Building definitions /** Builds the type parameter section of given symbol. */ public AbsTypeDef[] mkTypeParamsOf(Symbol sym) { Symbol[] tparams = sym.nextTypeParams(); AbsTypeDef[] trees = new AbsTypeDef[tparams.length]; for (int i = 0; i < tparams.length; i++) trees[i] = mkTypeParam(tparams[i]); return trees; } /** Builds the value parameter section of given symbol. */ public ValDef[][] mkParamsOf(Symbol sym) { global.nextPhase(); if (sym.isClass()) sym = sym.primaryConstructor(); Type type = sym.type(); global.prevPhase(); ValDef[][] treess = Tree.ValDef_EMPTY_ARRAY_ARRAY; while (true) { switch (type) { case PolyType(_, Type result): type = result; continue; case MethodType(Symbol[] vparams, Type result): ValDef[] trees = new ValDef[vparams.length]; for (int i = 0; i < vparams.length; i++) trees[i] = mkParam(vparams[i]); ValDef[][] array = new ValDef[treess.length + 1][]; for (int i = 0; i < treess.length; i++) array[i] = treess[i]; array[treess.length] = trees; treess = array; type = result; continue; default: return treess; } } } /** Builds the type parameter corresponding to given symbol. */ public AbsTypeDef mkTypeParam(Symbol sym) { return AbsTypeDef(sym); } /** Builds the value parameter corresponding to given symbol. */ public ValDef mkParam(Symbol sym) { return ValDef(sym, Tree.Empty); } /** Builds a PackageDef with given package and template. */ public PackageDef PackageDef(Tree peckage, Template template) { PackageDef tree = make.PackageDef(peckage.pos, peckage, template); tree.setType(Type.NoType); return tree; } public PackageDef PackageDef(Symbol peckage, Template template) { return PackageDef(mkGlobalRef(peckage.pos, peckage), template); } /** Builds a PackageDef with given package and body. */ public PackageDef PackageDef(Tree peckage, Tree[] body) { return PackageDef( peckage, Template(peckage.pos, Symbol.NONE, Tree.EMPTY_ARRAY, body)); } public PackageDef PackageDef(Symbol peckage, Tree[] body) { return PackageDef(mkGlobalRef(peckage.pos, peckage), body); } /** Builds a ClassDef node for given class with given template. */ public ClassDef ClassDef(Symbol clazz, Template template) { Tree type = Tree.Empty; if (clazz.thisSym() != clazz) { global.nextPhase(); type = mkType(clazz.pos, clazz.typeOfThis()); global.prevPhase(); } ClassDef tree = make.ClassDef( clazz.pos, clazz, mkTypeParamsOf(clazz), mkParamsOf(clazz), type, template); tree.setType(Type.NoType); return tree; } /** * Builds a ClassDef node for given class with given parent * constructors, local symbol and body. */ public ClassDef ClassDef(Symbol clazz, Tree[] constrs, Symbol local, Tree[] body) { return ClassDef(clazz, Template(clazz.pos, local, constrs, body)); } /** Builds a ClassDef node for given class with given body. */ public Tree ClassDef(Symbol clazz, Tree[] body) { for (int i = 0; i < body.length; i++) { assert body[i] == Tree.Empty || body[i].definesSymbol() && body[i].symbol().owner() ==clazz: "\nclass : " + Debug.show(clazz) + "\nmember: " + Debug.show(body[i].symbol()) + "\nmember: " + body[i]; } Global.instance.nextPhase(); Type[] parents = clazz.parents(); Global.instance.prevPhase(); Tree[] constrs = new Tree[parents.length]; for (int i = 0; i < constrs.length; i++) { switch (parents[i]) { case TypeRef(Type prefix, Symbol parent, Type[] targs): constrs[i] = mkApplyT_( mkPrimaryConstructorRef(clazz.pos, prefix, parent), targs); continue; default: throw Debug.abort("invalid type", parents[i]); } } return ClassDef(clazz, constrs, Symbol.NONE, body); } /** Builds a ValDef node for given symbol and with given rhs. */ public ValDef ValDef(Symbol sym, Tree rhs) { ValDef tree = make.ValDef( sym.pos, sym, TypeTerm(sym.pos, sym.nextType()), rhs); tree.setType(Type.NoType); return tree; } /** Builds a DefDef node for given symbol with given body. */ public DefDef DefDef(Symbol sym, Tree body) { DefDef tree = make.DefDef( sym.pos, sym, mkTypeParamsOf(sym), mkParamsOf(sym), TypeTerm(sym.pos, sym.nextType().resultType()), body); tree.setType(Type.NoType); return tree; } /** Builds an AbsTypeDef node for given symbol. */ public AbsTypeDef AbsTypeDef(Symbol sym) { AbsTypeDef tree = make.AbsTypeDef( sym.pos, sym, TypeTerm(sym.pos, sym.nextInfo()), TypeTerm(sym.pos, sym.loBound())); tree.setType(Type.NoType); return tree; } /** Builds an AliasTypeDef node for given symbol. */ public AliasTypeDef AliasTypeDef(Symbol sym) { AliasTypeDef tree = make.AliasTypeDef( sym.pos, sym, mkTypeParamsOf(sym), TypeTerm(sym.pos, sym.nextInfo())); tree.setType(Type.NoType); return tree; } /** Builds an CaseDef node with given pattern, guard and body. */ public CaseDef CaseDef(Tree pattern, Tree guard, Tree body) { CaseDef tree = make.CaseDef(pattern.pos, pattern, guard, body); tree.setType(body.getType()); return tree; } /** Builds an CaseDef node with given pattern and body. */ public CaseDef CaseDef(Tree pattern, Tree body) { return CaseDef(pattern, Tree.Empty, body); } /** * Builds a LabelDef node for given label with given parameters * and body. */ public LabelDef LabelDef(Symbol label, Ident[] params, Tree body) { LabelDef tree = make.LabelDef(label.pos, label, params, body); tree.setType(label.nextType().resultType()); return tree; } public LabelDef LabelDef(Symbol label, Symbol[] params, Tree body) { Ident[] idents = new Ident[params.length]; for (int i = 0; i < params.length; i++) idents[i] = Ident(params[i].pos, params[i]); return LabelDef(label, idents, body); } // // Private Methods /** Asserts type of given tree is a subtype of given type. */ private boolean assertTreeSubTypeOf(Tree tree, Type expected) { global.nextPhase(); assert tree.getType().isSubType(expected): "\ntree : " + tree + "\ntype : " + tree.getType() + "\nexpected: " + expected; global.prevPhase(); return true; } /** Creates a local variable with given prefix, owner and type. */ private Symbol newLocal(int pos, Name prefix, Symbol owner, Type type) { Name name = global.freshNameCreator.newName(prefix); Symbol local = new TermSymbol(pos, name, owner, Modifiers.SYNTHETIC); global.nextPhase(); local.setType(type); global.prevPhase(); return local; } /** Returns the primary constructor of given class. */ private Symbol primaryConstructorOf(Symbol clasz) { global.nextPhase(); Symbol constr = clasz.primaryConstructor(); global.prevPhase(); return constr; } // // // // // !!! not yet reviewed /** Build the expansion of (() => expr) */ public Tree mkUnitFunction(Tree expr, Type type, Symbol owner) { return mkFunction(expr.pos, Tree.ValDef_EMPTY_ARRAY, expr, type, owner); } /** Build the expansion of ((vparams_1, ..., vparams_n) => body) * with result type `restype', where `owner' is the previous owner * of `body'. * This is: * { class $anon() extends scala.Object with * scala.Function_N[T_1, ..., T_n, restype] { * def apply(vparams_1, ..., vparams_n) = body1 * } * new $anon() * } * where * vparams_i: T_i * `body1' results from `body' by changing owner of all defined * symbols in `body' from `owner' to the apply method. */ public Tree mkFunction(int pos, ValDef[] vparams, Tree body, Type restype, Symbol owner) { int n = vparams.length; Symbol[] params = new Symbol[n]; Type[] argtypes = new Type[n]; for (int i = 0; i < n; i++) { params[i] = vparams[i].symbol(); argtypes[i] = params[i].type(); } Type[] parentTypes = { definitions.ANYREF_TYPE(), definitions.FUNCTION_TYPE(argtypes, restype) }; ClassSymbol clazz = new ClassSymbol( pos, Names.ANON_CLASS_NAME.toTypeName(), owner, 0); clazz.setInfo(Type.compoundType(parentTypes, new Scope(), clazz)); clazz.allConstructors().setInfo( Type.MethodType(Symbol.EMPTY_ARRAY, clazz.typeConstructor())); Symbol applyMeth = new TermSymbol(pos, Names.apply, clazz, FINAL) .setInfo(Type.MethodType(params, restype)); clazz.info().members().enter(applyMeth); for (int i = 0; i < params.length; i++) { params[i].setOwner(applyMeth); } changeOwner(body, owner, applyMeth); Tree[] memberTrees = { DefDef(applyMeth, body) }; Tree classDef = ClassDef(clazz, memberTrees); Tree alloc = New(mkApply__(mkPrimaryConstructorLocalRef(pos, clazz))) .setType(parentTypes[1]); return mkBlock(classDef, alloc); } public Tree mkPartialFunction(int pos, Tree applyVisitor, Tree isDefinedAtVisitor, Type pattype, Type restype, Symbol owner) { ClassSymbol clazz = new ClassSymbol( pos, Names.ANON_CLASS_NAME.toTypeName(), owner, 0); Type[] parentTypes = { definitions.ANYREF_TYPE(), definitions.PARTIALFUNCTION_TYPE(pattype, restype)}; clazz.setInfo(Type.compoundType(parentTypes, new Scope(), clazz)); clazz.allConstructors().setInfo( Type.MethodType(Symbol.EMPTY_ARRAY, clazz.typeConstructor())); Tree[] memberTrees = { makeVisitorMethod(pos, Names.apply, applyVisitor, pattype, restype, clazz, owner), makeVisitorMethod(pos, Names.isDefinedAt, isDefinedAtVisitor, pattype, definitions.BOOLEAN_TYPE(), clazz, owner)}; Tree classDef = ClassDef(clazz, memberTrees); Tree alloc = New(mkApply__(mkPrimaryConstructorLocalRef(pos, clazz))) .setType(parentTypes[1]); return mkBlock(classDef, alloc); } //where private Tree makeVisitorMethod(int pos, Name name, Tree visitor, Type pattype, Type restype, Symbol clazz, Symbol prevOwner) { Symbol meth = new TermSymbol(pos, name, clazz, FINAL); Symbol param = new TermSymbol(pos, Name.fromString("x$"), meth, PARAM) .setInfo(pattype); meth.setInfo(Type.MethodType(new Symbol[]{param}, restype)); clazz.info().members().enter(meth); changeOwner(visitor, prevOwner, meth); Tree body = mkApplyTV( Select(Ident(pos, param), definitions.ANY_MATCH), new Tree[]{mkType(pos, pattype), mkType(pos, restype)}, new Tree[]{visitor}); return DefDef(meth, body); } /** Change owner of all defined symbols from `prevOwner' to `newOwner' */ public void changeOwner(Tree tree, final Symbol prevOwner, final Symbol newOwner) { Traverser lifter = new Traverser() { public void traverse(Tree tree) { if (tree.definesSymbol()) { Symbol sym = tree.symbol(); if (sym != null && sym.owner() == prevOwner) { sym.setOwner(newOwner); } } super.traverse(tree); } }; lifter.traverse(tree); } /** Build a postfix function application */ public Tree postfixApply(Tree obj, Tree fn, Symbol owner) { if (TreeInfo.isPureExpr(obj) || TreeInfo.isPureExpr(fn)) { return Apply(Select(fn, definitions.FUNCTION_APPLY(1)), new Tree[]{obj}); } else { Name tmpname = global.freshNameCreator.newName("tmp", '$'); Symbol tmp = new TermSymbol( obj.pos, tmpname, owner, SYNTHETIC | FINAL) .setInfo(obj.type); Tree tmpdef = ValDef(tmp, obj); Tree expr = postfixApply(Ident(obj.pos, tmp), fn, owner); return mkBlock(tmpdef, expr); } } // for insert debug printing code public Tree Console_print(int pos, String str) { return Console_print( pos, mkStringLit( pos, str )); } public Tree Console_print(int pos, Tree arg) { Symbol sym = global.definitions.getModule( Names.scala_Console ); return Apply( Select( pos, mkGlobalRef( pos, sym), global.definitions.CONSOLE_PRINT()), new Tree[] { arg }); } }
package org.neo4j.rdf.store; import java.util.Iterator; import java.util.LinkedList; import org.neo4j.api.core.Direction; import org.neo4j.api.core.NeoService; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.api.core.StopEvaluator; import org.neo4j.api.core.Transaction; import org.neo4j.api.core.Traverser.Order; import org.neo4j.neometa.structure.MetaStructure; import org.neo4j.rdf.model.CompleteStatement; import org.neo4j.rdf.model.Context; import org.neo4j.rdf.model.Literal; import org.neo4j.rdf.model.Resource; import org.neo4j.rdf.model.Statement; import org.neo4j.rdf.model.Uri; import org.neo4j.rdf.model.Value; import org.neo4j.rdf.model.WildcardStatement; import org.neo4j.rdf.store.representation.AbstractNode; import org.neo4j.rdf.store.representation.standard.AbstractUriBasedExecutor; import org.neo4j.rdf.store.representation.standard.VerboseQuadExecutor; import org.neo4j.rdf.store.representation.standard.VerboseQuadStrategy; import org.neo4j.util.FilteringIterable; import org.neo4j.util.FilteringIterator; import org.neo4j.util.IterableWrapper; import org.neo4j.util.OneOfRelTypesReturnableEvaluator; import org.neo4j.util.PrefetchingIterator; import org.neo4j.util.RelationshipToNodeIterable; import org.neo4j.util.index.IndexService; public class VerboseQuadStore extends RdfStoreImpl { private final MetaStructure meta; public VerboseQuadStore( NeoService neo, IndexService indexer ) { this( neo, indexer, null ); } public VerboseQuadStore( NeoService neo, IndexService indexer, MetaStructure meta ) { super( neo, new VerboseQuadStrategy( new VerboseQuadExecutor( neo, indexer, meta ), meta ) ); this.meta = meta; debug( "I'm initialized!" ); } protected MetaStructure meta() { return this.meta; } @Override protected VerboseQuadStrategy getRepresentationStrategy() { return ( VerboseQuadStrategy ) super.getRepresentationStrategy(); } @Override public Iterable<CompleteStatement> getStatements( WildcardStatement statement, boolean includeInferredStatements ) { debug( "getStatements( " + statement + " )" ); Transaction tx = neo().beginTx(); try { if ( includeInferredStatements ) { throw new UnsupportedOperationException( "We currently not " + "support getStatements() with reasoning enabled" ); } Iterable<CompleteStatement> result = null; if ( wildcardPattern( statement, false, false, true ) ) { result = handleSubjectPredicateWildcard( statement ); } else if ( wildcardPattern( statement, false, true, true ) ) { result = handleSubjectWildcardWildcard( statement ); } else if ( wildcardPattern( statement, false, true, false ) ) { result = handleSubjectWildcardObject( statement ); } else if ( wildcardPattern( statement, true, true, false ) ) { result = handleWildcardWildcardObject( statement ); } else if ( wildcardPattern( statement, true, false, false ) ) { result = handleWildcardPredicateObject( statement ); } else if ( wildcardPattern( statement, false, false, false ) ) { result = handleSubjectPredicateObject( statement ); } else if ( wildcardPattern( statement, true, false, true ) ) { result = handleWildcardPredicateWildcard( statement ); } else if ( wildcardPattern( statement, true, true, true ) ) { result = handleWildcardWildcardWildcard( statement ); } else { result = super.getStatements( statement, includeInferredStatements ); } if ( result == null ) { result = new LinkedList<CompleteStatement>(); } tx.success(); return result; } finally { tx.finish(); } } private void debug( String message ) { } private Node lookupNode( Value uri ) { return getRepresentationStrategy().getExecutor(). lookupNode( new AbstractNode( uri ) ); } private String getNodeUriOrNull( Node node ) { return ( String ) node.getProperty( AbstractUriBasedExecutor.URI_PROPERTY_KEY, null ); } private Value getValueForObjectNode( String predicate, Node objectNode ) { String uri = ( String ) objectNode.getProperty( AbstractUriBasedExecutor.URI_PROPERTY_KEY, null ); if ( uri != null ) { return new Uri( uri ); } else { Object value = objectNode.getProperty( predicate ); String datatype = ( String ) objectNode.getProperty( VerboseQuadExecutor.LITERAL_DATATYPE_KEY, null ); String language = ( String ) objectNode.getProperty( VerboseQuadExecutor.LITERAL_LANGUAGE_KEY, null ); return new Literal( value, datatype == null ? null : new Uri( datatype ), language ); } } private RelationshipType relType( final String name ) { return new RelationshipType() { public String name() { return name; } }; } private RelationshipType relType( Value value ) { return relType( ( ( Uri ) value ).getUriAsString() ); } private RelationshipType relType( Statement statement ) { return relType( statement.getPredicate() ); } private Iterable<Node> getMiddleNodesFromLiterals( Statement statement ) { Literal literal = ( Literal ) statement.getObject(); Iterable<Node> literalNodes = getRepresentationStrategy(). getExecutor().findLiteralNodes( literal.getValue() ); return new LiteralToMiddleNodeIterable( literalNodes ); } private Iterable<Node> getMiddleNodesFromAllContexts() { return getRepresentationStrategy().getExecutor(). getContextsReferenceNode().traverse( Order.DEPTH_FIRST, StopEvaluator.END_OF_NETWORK, new OneOfRelTypesReturnableEvaluator( VerboseQuadStrategy.RelTypes.IN_CONTEXT ), VerboseQuadExecutor.RelTypes.IS_A_CONTEXT, Direction.OUTGOING, VerboseQuadStrategy.RelTypes.IN_CONTEXT, Direction.INCOMING ); } private Iterable<CompleteStatement> handleSubjectPredicateWildcard( Statement statement ) { Node subjectNode = lookupNode( statement.getSubject() ); if ( subjectNode == null ) { return null; } Iterable<Node> middleNodes = new RelationshipToNodeIterable( subjectNode, subjectNode.getRelationships( relType( statement ), Direction.OUTGOING ) ); return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleSubjectWildcardWildcard( Statement statement ) { Node subjectNode = lookupNode( statement.getSubject() ); if ( subjectNode == null ) { return null; } Iterable<Node> middleNodes = new RelationshipToNodeIterable( subjectNode, subjectNode.getRelationships( Direction.OUTGOING ) ); return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleSubjectWildcardObject( final Statement statement ) { // TODO Optimization: maybe check which has least rels (S or O) // and start there. Node subjectNode = lookupNode( statement.getSubject() ); if ( subjectNode == null ) { return null; } Iterable<Relationship> relationships = subjectNode.getRelationships( Direction.OUTGOING ); relationships = new ObjectFilteredRelationships( statement, relationships ); Iterable<Node> middleNodes = new RelationshipToNodeIterable( subjectNode, relationships ); return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleSubjectPredicateObject( Statement statement ) { Node subjectNode = lookupNode( statement.getSubject() ); if ( subjectNode == null ) { return null; } Iterable<Relationship> relationships = subjectNode.getRelationships( relType( statement ), Direction.OUTGOING ); relationships = new ObjectFilteredRelationships( statement, relationships ); Iterable<Node> middleNodes = new RelationshipToNodeIterable( subjectNode, relationships ); return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleWildcardWildcardObject( Statement statement ) { Iterable<Node> middleNodes = null; if ( statement.getObject() instanceof Literal ) { middleNodes = getMiddleNodesFromLiterals( statement ); } else { Node objectNode = lookupNode( statement.getObject() ); if ( objectNode == null ) { return null; } middleNodes = new RelationshipToNodeIterable( objectNode, objectNode.getRelationships( Direction.INCOMING ) ); } return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleWildcardPredicateWildcard( Statement statement ) { Iterable<Node> middleNodes = null; if ( statement.getContext().isWildcard() ) { // TODO Slow middleNodes = getMiddleNodesFromAllContexts(); } else { Node contextNode = lookupNode( statement.getContext() ); if ( contextNode == null ) { return null; } middleNodes = new RelationshipToNodeIterable( contextNode, contextNode.getRelationships( VerboseQuadStrategy.RelTypes.IN_CONTEXT, Direction.INCOMING ) ); } middleNodes = new PredicateFilteredNodes( statement, middleNodes ); return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleWildcardPredicateObject( Statement statement ) { Iterable<Node> middleNodes = null; if ( statement.getObject() instanceof Literal ) { middleNodes = new PredicateFilteredNodes( statement, getMiddleNodesFromLiterals( statement ) ); } else { Node objectNode = lookupNode( statement.getObject() ); if ( objectNode == null ) { return null; } middleNodes = new RelationshipToNodeIterable( objectNode, objectNode.getRelationships( relType( statement ), Direction.INCOMING ) ); } return new MiddleNodeToStatementIterable( statement, middleNodes ); } private Iterable<CompleteStatement> handleWildcardWildcardWildcard( Statement statement ) { Iterable<Node> middleNodes = null; if ( statement.getContext().isWildcard() ) { // TODO Slow middleNodes = getMiddleNodesFromAllContexts(); } else { Node contextNode = lookupNode( statement.getContext() ); if ( contextNode == null ) { return null; } middleNodes = new RelationshipToNodeIterable( contextNode, contextNode.getRelationships( VerboseQuadStrategy.RelTypes.IN_CONTEXT, Direction.INCOMING ) ); } return new MiddleNodeToStatementIterable( statement, middleNodes ); } private class MiddleNodeToStatementIterable implements Iterable<CompleteStatement> { private Statement statement; private Iterable<Node> middleNodes; MiddleNodeToStatementIterable( Statement statement, Iterable<Node> middleNodes ) { this.statement = statement; this.middleNodes = middleNodes; } public Iterator<CompleteStatement> iterator() { return new MiddleNodeToStatementIterator( statement, middleNodes.iterator() ); } } private class MiddleNodeToStatementIterator extends PrefetchingIterator<CompleteStatement> { private Statement statement; private Iterator<Node> middleNodes; // They are both null or both non-null synced. private Node currentMiddleNode; private Iterator<Node> currentMiddleNodeContexts; MiddleNodeToStatementIterator( Statement statement, Iterator<Node> middleNodes ) { this.statement = statement; this.middleNodes = middleNodes; } @Override protected CompleteStatement fetchNextOrNull() { if ( currentMiddleNodeContexts == null || !currentMiddleNodeContexts.hasNext() ) { while ( middleNodes.hasNext() ) { currentMiddleNode = middleNodes.next(); currentMiddleNodeContexts = newContextIterator( currentMiddleNode ); if ( currentMiddleNodeContexts.hasNext() ) { break; } } } if ( currentMiddleNodeContexts != null && currentMiddleNodeContexts.hasNext() ) { return newStatement(); } return null; } private Iterator<Node> newContextIterator( Node middleNode ) { // TODO With the traverser it's... somewhat like // 1000 times slower, why Johan why? // currentMiddleNodeContexts = currentMiddleNode.traverse( // Order.BREADTH_FIRST, StopEvaluator.END_OF_NETWORK, // contextMatcher, VerboseQuadStrategy.RelTypes.IN_CONTEXT, // Direction.OUTGOING ).iterator(); Iterator<Node> iterator = new RelationshipToNodeIterable( middleNode, middleNode.getRelationships( VerboseQuadStrategy.RelTypes.IN_CONTEXT, Direction.OUTGOING ) ).iterator(); if ( !statement.getContext().isWildcard() ) { iterator = new FilteringIterator<Node>( iterator ) { @Override protected boolean passes( Node contextNode ) { String contextUri = getNodeUriOrNull( contextNode ); return new Context( contextUri ).equals( statement.getContext() ); } }; } return iterator; } private CompleteStatement newStatement() { Node middleNode = currentMiddleNode; Relationship subjectRelationship = middleNode.getRelationships( Direction.INCOMING ).iterator().next(); Node subjectNode = subjectRelationship.getOtherNode( middleNode ); Uri subject = new Uri( getNodeUriOrNull( subjectNode ) ); Uri predicate = new Uri( subjectRelationship.getType().name() ); Node objectNode = middleNode.getSingleRelationship( subjectRelationship.getType(), Direction.OUTGOING ).getEndNode(); Value object = getValueForObjectNode( predicate.getUriAsString(), objectNode ); Node contextNode = currentMiddleNodeContexts.next(); Context context = new Context( getNodeUriOrNull( contextNode ) ); return object instanceof Literal ? new CompleteStatement( subject, predicate, ( Literal ) object, context ) : new CompleteStatement( subject, predicate, ( Resource ) object, context ); } } private class PredicateFilteredNodes extends FilteringIterable<Node> { private Statement statement; PredicateFilteredNodes( Statement statment, Iterable<Node> source ) { super( source ); this.statement = statment; } @Override protected boolean passes( Node middleNode ) { Relationship relationship = middleNode.getRelationships( Direction.INCOMING ).iterator().next(); return relationship.getType().name().equals( ( ( Uri ) statement.getPredicate() ).getUriAsString() ); } } private class ObjectFilteredRelationships extends FilteringIterable<Relationship> { private Statement statement; ObjectFilteredRelationships( Statement statement, Iterable<Relationship> source ) { super( source ); this.statement = statement; } @Override protected boolean passes( Relationship subjectToMiddleRel ) { Node middleNode = subjectToMiddleRel.getEndNode(); Node objectNode = middleNode.getSingleRelationship( subjectToMiddleRel.getType(), Direction.OUTGOING ).getEndNode(); Value objectValue = getValueForObjectNode( subjectToMiddleRel.getType().name(), objectNode ); return objectValue.equals( statement.getObject() ); } } private class LiteralToMiddleNodeIterable extends IterableWrapper<Node, Node> { LiteralToMiddleNodeIterable( Iterable<Node> literalNodes ) { super( literalNodes ); } @Override protected Node underlyingObjectToObject( Node literalNode ) { return literalNode.getRelationships( Direction.INCOMING ).iterator().next().getStartNode(); } } }
package scalac.ast; import java.io.*; import java.util.*; import scalac.*; import scalac.symtab.*; import scalac.typechecker.Infer; import scalac.util.*; import Tree.*; /** A helper class for building trees * * @author Martin Odersky, Christine Roeckl * @version 1.0 */ public class TreeGen implements Kinds, Modifiers { /** VARIABLES **/ /** the global environment */ protected Global global; /** the global definitions */ protected Definitions definitions; /** the tree factory */ public TreeFactory make; /** the type inferencer */ Infer infer; /** CONSTRUCTORS **/ public TreeGen(Global global, TreeFactory make) { this.global = global; this.definitions = global.definitions; this.make = make; this.infer = new Infer(global, this, make); } public TreeGen(Global global) { this(global, global.make); } /** METHODS **/ public Type deref(Type tp) { switch (tp) { case PolyType(Symbol[] tparams, Type restp): if (tparams.length == 0) return restp; } return tp; } /** Create a dummy symbol to be used for templates. */ public Symbol localDummy(int pos, Symbol owner) { return new TermSymbol(pos, Names.EMPTY, owner, 0) .setInfo(Type.NoType); } public Tree mkStable(Tree tree) { Symbol sym = tree.symbol(); if (sym.isStable()) { switch (tree) { case Ident(_): tree.setType(Type.singleType(sym.owner().thisType(), sym)); break; case Select(Tree qual, _): if (qual.type.isStable()) tree.setType(Type.singleType(qual.type, sym)); } } return tree; } public Tree mkRef(int pos, Type pre, Symbol sym) { if (pre.isSameAs(Type.localThisType) || pre.symbol().isRoot()) return Ident(pos, sym); else return Select(pos, mkStableId(pos, pre), sym); } public Tree mkRef(int pos, Symbol sym) { return mkRef(pos, sym.owner().thisType(), sym); } /** Build and attribute stable identifier tree corresponding to given prefix. */ public Tree mkStableId(int pos, Type pre) { switch (pre.expandModuleThis()) { case ThisType(Symbol sym): return make.This(pos, Ident(pos, sym)).setType(pre); case SingleType(Type pre1, Symbol sym): return mkStable(mkRef(pos, pre1, sym)); default: throw new ApplicationError(); } } /** Build and attribute tree corresponding to given type. */ public Tree mkType(int pos, Type type) { return TypeTerm(pos, type); } /** Build and attribute tree array corresponding to given type array. */ public Tree[] mkTypes(int pos, Type[] types) { Tree[] res = new Tree[types.length]; for (int i = 0; i < types.length; i++) { res[i] = mkType(pos, types[i]); } return res; } /** Build and attribute tree corresponding to given type. */ public Tree TypeTerm(int pos, Type type) { return make.TypeTerm(pos).setType(type); } /** Build and attribute tree corresponding to symbol's declaration. */ public Tree mkDef(int pos, Symbol sym) { switch (sym.kind) { case ERROR: return make.Bad(pos).setSymbol(Symbol.ERROR).setType(Type.ErrorType); case TYPE: case ALIAS: return TypeDef(pos, sym); case VAL: if (sym.isMethod()) return DefDef(pos, sym, Tree.Empty); else return Param(pos, sym); default: throw new ApplicationError(); } } /** Build and attribute tree array corresponding to given symbol's declarations. */ public Tree[] mkDefs(int pos, Symbol[] syms) { Tree[] res = new Tree[syms.length]; for (int i = 0; i < syms.length; i++) { res[i] = mkDef(pos, syms[i]); } return res; } /** Build a boolean constant tree. */ public Tree mkBooleanLit(int pos, boolean bool) { return make.Literal(pos, bool ? Boolean.TRUE : Boolean.FALSE). setType(definitions.BOOLEAN_TYPE); } /** Build a string literal */ public Tree mkStringLit(int pos, String str) { return make.Literal(pos, str).setType(definitions.JAVA_STRING_TYPE); } /** Build an integer literal */ public Tree mkIntLit(int pos, int value) { return make.Literal(pos, new Integer(value)).setType(definitions.INT_TYPE); } /** Build a tree to be used as a base class constructor for a template. */ public Tree mkParentConstr(int pos, Type parentType, Tree[] parentArgs) { switch (parentType) { case TypeRef(Type pre, Symbol sym, Type[] args): Tree ref = mkRef(pos, pre, sym.constructor()); Tree constr = (args.length == 0) ? ref : TypeApply(ref, mkTypes(sym.pos, args)); return Apply(constr, parentArgs); default: throw global.fail("invalid parent type", parentType); } } public Tree mkParentConstr(int pos, Type parentType) { return mkParentConstr(pos, parentType, Tree.EMPTY_ARRAY); } /** Build an array of trees to be used as base classes for a template. */ public Tree[] mkParentConstrs(int pos, Type[] parents, Tree[][] parentArgs) { Tree[] constrs = new Tree[parents.length]; for (int i = 0; i < parents.length; ++i) constrs[i] = (parentArgs == null ? mkParentConstr(pos, parents[i]) : mkParentConstr(pos, parents[i], parentArgs[i])); return constrs; } public Tree[] mkParentConstrs(int pos, Type[] parents) { return mkParentConstrs(pos, parents, null); } /** Build parameter sections corresponding to type. */ public ValDef[][] mkParams(int pos, Type type) { switch (type) { case PolyType(Symbol[] tparams, Type restype): return mkParams(pos, restype); case MethodType(Symbol[] vparams, Type restype): ValDef[] params1 = mkParams(pos, vparams); ValDef[][] paramss = mkParams(pos, restype); if (paramss.length == 0) { return new ValDef[][]{params1}; } else { ValDef[][] paramss1 = new ValDef[paramss.length + 1][]; paramss1[0] = params1; System.arraycopy(paramss, 0, paramss1, 1, paramss.length); return paramss1; } default: return new ValDef[][]{}; } } /** Build parameter section corresponding to given array of symbols . */ public ValDef[] mkParams(int pos, Symbol[] symbols) { ValDef[] res = new ValDef[symbols.length]; for (int i = 0; i < symbols.length; i++) { res[i] = Param(pos, symbols[i]); } return res; } /** Build type parameter section corresponding to given array of symbols . */ public TypeDef[] mkTypeParams(int pos, Symbol[] symbols) { TypeDef[] res = new TypeDef[symbols.length]; for (int i = 0; i < symbols.length; i++) { res[i] = (TypeDef)TypeDef(pos, symbols[i]); } return res; } /** Build type definition corresponding to given symbol . */ public TypeDef TypeDef(int pos, Symbol sym) { Global.instance.nextPhase(); Type symtype = sym.info(); Global.instance.prevPhase(); return (TypeDef) make.TypeDef( pos, sym.flags & SOURCEFLAGS, sym.name, TypeTerm(pos, symtype), TypeTerm(pos, sym.loBound())) .setSymbol(sym).setType(definitions.UNIT_TYPE); } public TypeDef TypeDef(Symbol sym) { return TypeDef(sym.pos, sym); } /** Build parameter */ public ValDef Param(int pos, Symbol sym) { global.log("use of obsolete Param method in TreeGen"); return (ValDef)ValDef(pos, sym, Tree.Empty); } public ValDef Param(Symbol sym) { global.log("use of obsolete Param method in TreeGen"); return Param(sym.pos, sym); } public ValDef ValDef(int pos, Symbol sym) { return (ValDef)ValDef(pos, sym, Tree.Empty); } public ValDef ValDef(Symbol sym) { return Param(sym.pos, sym); } /** Build and attribute block with given statements, starting * at given position. The type is the type of the last * statement in the block. */ public Tree Block(int pos, Tree[] stats) { Type tp = (stats.length == 0) ? definitions.UNIT_TYPE : stats[stats.length - 1].type; return make.Block(pos, stats).setType(tp); } /** Build and attribute non-empty block with given statements. */ public Tree Block(Tree[] stats) { return Block(stats[0].pos, stats); } public Tree Typed(Tree tree, Type tp) { return make.Typed(tree.pos, tree, TypeTerm(tree.pos, tp)).setType(tp); } /** Build and attribute the assignment lhs = rhs */ public Tree Assign(int pos, Tree lhs, Tree rhs) { return make.Assign(pos, lhs, rhs).setType(definitions.UNIT_TYPE); } public Tree Assign(Tree lhs, Tree rhs) { return Assign(lhs.pos, lhs, rhs); } /** Build and attribute new B, given constructor expression B. */ public Tree New(int pos, Tree constr) { Template templ = make.Template( pos, new Tree[]{constr}, Tree.EMPTY_ARRAY); templ.setType(constr.type); templ.setSymbol(localDummy(pos, Symbol.NONE)); return make.New(pos, templ).setType(constr.type); } public Tree New(Tree constr) { return New(constr.pos, constr); } /** Build an allocation new P.C[TARGS](ARGS) * given a (singleton) type P, class C, type arguments TARGS and arguments ARGS */ public Tree New(int pos, Type pre, Symbol clazz, Type[] targs, Tree[] args) { Tree constr = mkRef(pos, pre, clazz.constructor()); if (targs.length != 0) constr = TypeApply(constr, mkTypes(pos, targs)); Tree base = Apply(constr, args); return New(base); } /** Build a monomorphic allocation new P.C(ARGS) * given a prefix P, class C and arguments ARGS */ public Tree New(int pos, Type pre, Symbol clazz, Tree[] args) { return New(pos, pre, clazz, Type.EMPTY_ARRAY, args); } /** Build and attribute application node with given function * and argument trees. */ public Tree Apply(int pos, Tree fn, Tree[] args) { try { switch (fn.type) { case Type.OverloadedType(Symbol[] alts, Type[] alttypes): infer.methodAlternative(fn, alts, alttypes, Tree.typeOf(args), Type.AnyType); } switch (fn.type) { case Type.MethodType(Symbol[] vparams, Type restpe): return make.Apply(pos, fn, args).setType(restpe); } } catch (Type.Error ex) { } throw new ApplicationError("method type required", fn.type); } public Tree Apply(Tree fn, Tree[] args) { return Apply(fn.pos, fn, args); } /** Build and attribute type application node with given function * and argument trees. */ public Tree TypeApply(int pos, Tree fn, Tree[] args) { try { switch (fn.type) { case Type.OverloadedType(Symbol[] alts, Type[] alttypes): infer.polyAlternative(fn, alts, alttypes, args.length); } switch (fn.type) { case Type.PolyType(Symbol[] tparams, Type restpe): return make.TypeApply(pos, fn, args) .setType(restpe.subst(tparams, Tree.typeOf(args))); } } catch (Type.Error ex) { } throw new ApplicationError("poly type required", fn.type); } public Tree TypeApply(Tree fn, Tree[] args) { return TypeApply(fn.pos, fn, args); } public Tree If(int pos, Tree cond, Tree thenpart, Tree elsepart) { return make.If(pos, cond, thenpart, elsepart).setType(thenpart.type); } public Tree If(Tree cond, Tree thenpart, Tree elsepart) { return If(cond.pos, cond, thenpart, elsepart); } /** Build and applied type node with given function * and argument trees. public Tree AppliedType(int pos, Tree fn, Tree[] args) { return make.AppliedType(pos, fn, args) .setType(Type.appliedType(fn.type, Tree.typeOf(args))); } public Tree AppliedType(Tree fn, Tree[] args) { return AppliedType(fn.pos, fn, args); } */ /** Build and attribute select node of given symbol. * It is assumed that the prefix is not empty. */ public Tree Select(int pos, Tree qual, Symbol sym) { assert sym.kind != NONE; Global.instance.nextPhase(); Type symtype = qual.type.memberType(sym); Global.instance.prevPhase(); return make.Select(pos, qual, sym.name) .setSymbol(sym).setType(deref(symtype)); } public Tree Select(Tree qual, Symbol sym) { return Select(qual.pos, qual, sym); } public Tree Select(Tree qual, Name name) { Symbol sym = qual.type.lookup(name); assert (sym.kind != NONE && sym != Symbol.ERROR) : name + " from " + qual.type; return Select(qual, sym); } /** Build and attribute ident node with given symbol. */ public Tree Ident(int pos, Symbol sym) { Global.instance.nextPhase(); Type symtype = sym.type(); Global.instance.prevPhase(); return make.Ident(pos, sym.name) .setSymbol(sym).setType(deref(symtype)); } public Tree Ident(Symbol sym) { return Ident(sym.pos, sym); } /** Build and attribute this node with given symbol. */ public Tree This(int pos, Symbol sym) { Type type = sym.thisType(); return make.This(pos, TypeTerm(pos, type)).setType(type); } /** Build and attribute super node with given type. */ public Tree Super(int pos, Type type) { return make.Super(pos, TypeTerm(pos, type)).setType(type); } /** Build and attribute value/variable/let definition node whose signature * corresponds to given symbol and which has given rhs. */ public Tree ValDef(int pos, Symbol sym, Tree rhs) { Global.instance.nextPhase(); Type symtype = sym.type(); Global.instance.prevPhase(); return make.ValDef(pos, sym.flags & SOURCEFLAGS, sym.name, TypeTerm(pos, symtype), rhs) .setSymbol(sym).setType(definitions.UNIT_TYPE); } public Tree ValDef(Symbol sym, Tree rhs) { return ValDef(sym.pos, sym, rhs); } /** Build and attribute value/variable/let definition node whose signature * corresponds to given symbol and which has given body. */ public Tree DefDef(int pos, Symbol sym, Tree body) { Global.instance.nextPhase(); Type symtype = sym.type(); Global.instance.prevPhase(); return make.DefDef(pos, sym.flags & SOURCEFLAGS, sym.name, mkTypeParams(pos, symtype.typeParams()), mkParams(pos, symtype), TypeTerm(pos, symtype.resultType()), body) .setSymbol(sym).setType(definitions.UNIT_TYPE); } public Tree DefDef(Symbol sym, Tree rhs) { return DefDef(sym.pos, sym, rhs); } /** Generate class definition from class symbol, and template. */ public Tree ClassDef(int pos, Symbol clazz, Template template) { Global.instance.nextPhase(); Type constrtype = clazz.constructor().info(); Global.instance.prevPhase(); return make.ClassDef( pos, clazz.flags & SOURCEFLAGS, clazz.name, mkTypeParams(pos, constrtype.typeParams()), mkParams(pos, constrtype), Tree.Empty, template) .setSymbol(clazz).setType(definitions.UNIT_TYPE); } public Tree ClassDef(Symbol clazz, Template template) { return ClassDef(clazz.pos, clazz, template); } /** Generate class definition from class symbol, parent constructors, and body. */ public Tree ClassDef(int pos, Symbol clazz, Tree[] constrs, Symbol local, Tree[] body) { Global.instance.nextPhase(); Type clazzinfo = clazz.info(); Global.instance.prevPhase(); switch (clazzinfo) { case CompoundType(Type[] parents, Scope members): Template templ = make.Template(pos, constrs, body); templ.setType(clazzinfo); templ.setSymbol(local); return ClassDef(pos, clazz, templ); default: throw new ApplicationError(); } } public Tree ClassDef(int pos, Symbol clazz, Tree[] constrs, Tree[] body) { return ClassDef(pos, clazz, constrs, localDummy(pos, clazz), body); } public Tree ClassDef(Symbol clazz, Tree[] constrs, Symbol local, Tree[] body) { return ClassDef(clazz.pos, clazz, constrs, local, body); } public Tree ClassDef(Symbol clazz, Tree[] constrs, Tree[] body) { return ClassDef(clazz.pos, clazz, constrs, body); } /** Generate class definition from class symbol and body. * All parents must by parameterless, or take unit parameters. */ public Tree ClassDef(int pos, Symbol clazz, Symbol local, Tree[] body) { Global.instance.nextPhase(); Type clazzinfo = clazz.info(); Global.instance.prevPhase(); return ClassDef(pos, clazz, mkParentConstrs(pos, clazzinfo.parents()), local, body); } public Tree ClassDef(int pos, Symbol clazz, Tree[] body) { return ClassDef(pos, clazz, localDummy(pos, clazz), body); } public Tree ClassDef(Symbol clazz, Symbol local, Tree[] body) { return ClassDef(clazz.pos, clazz, local, body); } public Tree ClassDef(Symbol clazz, Tree[] body) { return ClassDef(clazz.pos, clazz, body); } /** Build the expansion of (() => expr) */ public Tree mkUnitFunction(Tree expr, Type tp, Symbol owner) { return mkFunction(expr.pos, Tree.ValDef_EMPTY_ARRAY, expr, tp, owner); } /** Build the expansion of ((vparams_1, ..., vparams_n) => body) * with result type `restype', where `owner' is the previous owner * of `body'. * This is: * { class $anon() extends scala.Object with * scala.Function_N[T_1, ..., T_n, restype] { * def apply(vparams_1, ..., vparams_n) = body1 * } * new $anon() * } * where * vparams_i: T_i * `body1' results from `body' by changing owner of all defined * symbols in `body' from `owner' to the apply method. */ public Tree mkFunction(int pos, ValDef[] vparams, Tree body, Type restype, Symbol owner) { int n = vparams.length; Symbol[] params = new Symbol[n]; Type[] argtypes = new Type[n]; for (int i = 0; i < n; i++) { params[i] = vparams[i].symbol(); argtypes[i] = params[i].type(); } Type ft = definitions.functionType(argtypes, restype); ClassSymbol clazz = new ClassSymbol( pos, Names.ANON_CLASS_NAME.toTypeName(), owner, 0); clazz.setInfo(Type.compoundType(new Type[]{definitions.OBJECT_TYPE, ft}, new Scope(), clazz)); clazz.constructor().setInfo( Type.MethodType(Symbol.EMPTY_ARRAY, clazz.typeConstructor())); Symbol applyMeth = new TermSymbol(pos, Names.apply, clazz, FINAL) .setInfo(Type.MethodType(params, restype)); clazz.info().members().enter(applyMeth); for (int i = 0; i < params.length; i++) { params[i].setOwner(applyMeth); } changeOwner(body, owner, applyMeth); Tree applyDef = DefDef(applyMeth, body); Tree classDef = ClassDef(clazz, new Tree[]{applyDef}); Tree alloc = New(pos, Type.localThisType, clazz, Tree.EMPTY_ARRAY); return Block(new Tree[]{classDef, alloc}).setType(ft); } public Tree mkPartialFunction(int pos, Tree applyVisitor, Tree isDefinedAtVisitor, Type pattype, Type restype, Symbol owner) { Type pft = definitions.partialFunctionType(pattype, restype); ClassSymbol clazz = new ClassSymbol( pos, Names.ANON_CLASS_NAME.toTypeName(), owner, 0); clazz.setInfo(Type.compoundType(new Type[]{definitions.OBJECT_TYPE, pft}, new Scope(), clazz)); clazz.constructor().setInfo( Type.MethodType(Symbol.EMPTY_ARRAY, clazz.typeConstructor())); Tree classDef = ClassDef(clazz, new Tree[]{ makeVisitorMethod(pos, Names.apply, applyVisitor, pattype, restype, clazz, owner), makeVisitorMethod(pos, Names.isDefinedAt, isDefinedAtVisitor, pattype, definitions.BOOLEAN_TYPE, clazz, owner)}); Tree alloc = New(pos, Type.localThisType, clazz, Tree.EMPTY_ARRAY); return Block(new Tree[]{classDef, alloc}).setType(pft); } //where private Tree makeVisitorMethod(int pos, Name name, Tree visitor, Type pattype, Type restype, Symbol clazz, Symbol prevOwner) { Symbol meth = new TermSymbol(pos, name, clazz, FINAL); Symbol param = new TermSymbol(pos, Name.fromString("x$"), meth, PARAM) .setInfo(pattype); meth.setInfo(Type.MethodType(new Symbol[]{param}, restype)); clazz.info().members().enter(meth); changeOwner(visitor, prevOwner, meth); Tree body = Apply( Select(Ident(param), definitions.MATCH), new Tree[]{visitor}) .setType(restype); return DefDef(meth, body); } /** Change owner of all defined symbols from `prevOwner' to `newOwner' */ public void changeOwner(Tree tree, final Symbol prevOwner, final Symbol newOwner) { Traverser lifter = new Traverser() { public void traverse(Tree tree) { if (TreeInfo.isDefinition(tree)) { Symbol sym = tree.symbol(); if (sym != null && sym.owner() == prevOwner) { sym.setOwner(newOwner); } } super.traverse(tree); } }; lifter.traverse(tree); } }
package org.jboss.as.server; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.Serializable; import java.util.List; import java.util.Map; import java.util.Properties; import org.jboss.as.deployment.chain.JarDeploymentActivator; import org.jboss.as.deployment.module.ClassifyingModuleLoaderInjector; import org.jboss.as.deployment.module.ClassifyingModuleLoaderService; import org.jboss.as.deployment.module.DeploymentModuleLoaderImpl; import org.jboss.as.deployment.module.DeploymentModuleLoaderService; import org.jboss.as.model.AbstractServerModelUpdate; import org.jboss.as.model.ServerModel; import org.jboss.as.model.UpdateContext; import org.jboss.as.model.UpdateFailedException; import org.jboss.as.server.mgmt.ServerConfigurationPersisterImpl; import org.jboss.as.server.mgmt.ShutdownHandlerImpl; import org.jboss.as.server.mgmt.deployment.ServerDeploymentManagerImpl; import org.jboss.as.server.mgmt.deployment.ServerDeploymentRepositoryImpl; import org.jboss.as.services.net.SocketBindingManager; import org.jboss.as.services.net.SocketBindingManagerService; import org.jboss.logging.Logger; import org.jboss.msc.service.BatchBuilder; import org.jboss.msc.service.BatchServiceBuilder; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceActivator; import org.jboss.msc.service.ServiceActivatorContext; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.ServiceRegistryException; import org.jboss.msc.service.StartException; /** * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ServerStartTask implements ServerTask, Serializable, ObjectInputValidation { private static final long serialVersionUID = -8505496119636153918L; private final String serverName; private final int portOffset; private final Runnable logConfigurator; private final List<ServiceActivator> startServices; private final List<AbstractServerModelUpdate<?>> updates; private static final Logger log = Logger.getLogger("org.jboss.as.server"); public ServerStartTask(final String serverName, final int portOffset, final Runnable logConfigurator, final List<ServiceActivator> startServices, final List<AbstractServerModelUpdate<?>> updates) { this.serverName = serverName; this.portOffset = portOffset; this.logConfigurator = logConfigurator; this.startServices = startServices; this.updates = updates; } public void run(final List<ServiceActivator> startServices) { if (logConfigurator != null) logConfigurator.run(); log.infof("Starting server \"%s\"", serverName); final ServiceContainer container = ServiceContainer.Factory.create(); final ServerStartupListener serverStartupListener = new ServerStartupListener(createListenerCallback()); // First-stage (boot) services final BatchBuilder bootBatchBuilder = container.batchBuilder(); bootBatchBuilder.addListener(serverStartupListener); final ServiceActivatorContext serviceActivatorContext = new ServiceActivatorContext() { public BatchBuilder getBatchBuilder() { return bootBatchBuilder; } }; // Root service final BatchServiceBuilder<Void> builder = bootBatchBuilder.addService(ServiceName.JBOSS.append("as", "server"), Service.NULL); builder.setInitialMode(ServiceController.Mode.IMMEDIATE); // Services specified by the creator of this object for (ServiceActivator service : this.startServices) { service.activate(serviceActivatorContext); } // Services specified to this method for (ServiceActivator service : startServices) { service.activate(serviceActivatorContext); } // Install the boot services try { bootBatchBuilder.install(); } catch (ServiceRegistryException e) { throw new IllegalStateException("Failed to install boot services", e); } // Next-stage services final BatchBuilder batchBuilder = container.batchBuilder(); batchBuilder.addListener(serverStartupListener); // Initial model final ServerModel serverModel = new ServerModel(serverName, portOffset); final Properties systemProperties = System.getProperties(); final ServerEnvironment environment = new ServerEnvironment(systemProperties, serverName, false); log.info("Activating core services"); // Server env ServerEnvironmentService.addService(environment, batchBuilder); // Deployment repository ServerDeploymentRepositoryImpl.addService(batchBuilder); // Graceful shutdown ShutdownHandlerImpl.addService(batchBuilder); // Server model service - TODO: replace with ServerController ServerModelService.addService(serverModel, batchBuilder); // Server deployment manager - TODO: move into startServices, only start in standalone mode ServerDeploymentManagerImpl.addService(serverModel, container, batchBuilder); // Server configuration persister - TODO: move into startServices, only start in standalone mode ServerConfigurationPersisterImpl.addService(serverModel, batchBuilder); batchBuilder.addService(SocketBindingManager.SOCKET_BINDING_MANAGER, new SocketBindingManagerService(portOffset)).setInitialMode(ServiceController.Mode.ON_DEMAND); // Activate deployment module loader batchBuilder.addService(ClassifyingModuleLoaderService.SERVICE_NAME, new ClassifyingModuleLoaderService()); final DeploymentModuleLoaderService deploymentModuleLoaderService = new DeploymentModuleLoaderService(new DeploymentModuleLoaderImpl()); batchBuilder.addService(DeploymentModuleLoaderService.SERVICE_NAME, deploymentModuleLoaderService) .addDependency(ClassifyingModuleLoaderService.SERVICE_NAME, ClassifyingModuleLoaderService.class, new ClassifyingModuleLoaderInjector("deployment", deploymentModuleLoaderService)); // todo move elsewhere... new JarDeploymentActivator().activate(new ServiceActivatorContext() { public BatchBuilder getBatchBuilder() { return batchBuilder; } }); for (AbstractServerModelUpdate<?> update : updates) { try { serverModel.update(update); } catch (UpdateFailedException e) { throw new IllegalStateException("Failed to start server", e); } } try { batchBuilder.install(); } catch (ServiceRegistryException e) { throw new IllegalStateException("Failed to start server", e); } final BatchBuilder updatesBatchBuilder = container.batchBuilder(); updatesBatchBuilder.addListener(serverStartupListener); final UpdateContext context = new UpdateContext() { public BatchBuilder getBatchBuilder() { return updatesBatchBuilder; } public ServiceContainer getServiceContainer() { return container; } }; for (AbstractServerModelUpdate<?> update : updates) { update.applyUpdateBootAction(context); } try { serverStartupListener.finish(); updatesBatchBuilder.install(); } catch (ServiceRegistryException e) { throw new IllegalStateException("Failed to install boot services", e); } } ServerStartupListener.Callback createListenerCallback() { return new ServerStartupListener.Callback() { public void run(Map<ServiceName, StartException> serviceFailures, long elapsedTime, int totalServices, int onDemandServices, int startedServices) { if(serviceFailures.isEmpty()) { log.infof("JBoss AS started in %dms. - Services [Total: %d, On-demand: %d. Started: %d]", elapsedTime, totalServices, onDemandServices, startedServices); } else { final StringBuilder buff = new StringBuilder(String.format("JBoss AS server start failed. Attempted to start %d services in %dms", totalServices, elapsedTime)); buff.append("\nThe following services failed to start:\n"); for(Map.Entry<ServiceName, StartException> entry : serviceFailures.entrySet()) { buff.append(String.format("\t%s => %s\n", entry.getKey(), entry.getValue().getMessage())); } log.error(buff.toString()); } } }; } public void validateObject() throws InvalidObjectException { if (serverName == null) { throw new InvalidObjectException("serverName is null"); } if (portOffset < 0) { throw new InvalidObjectException("portOffset is out of range"); } if (updates == null) { throw new InvalidObjectException("updates is null"); } if (logConfigurator == null) { throw new InvalidObjectException("logConfigurator is null"); } if (startServices == null) { throw new InvalidObjectException("startServices is null"); } } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); ois.registerValidation(this, 100); } }
//todo: T {} == T package scalac.symtab; import ch.epfl.lamp.util.Position; import scalac.ApplicationError; import scalac.util.*; import scalac.Global; public class Type implements Modifiers, Kinds, TypeTags, EntryTags { public static boolean explainSwitch = false; private static int indent = 0; public case ErrorType; // not used after analysis public case AnyType; // not used after analysis public case NoType; /** C.this.type */ public case ThisType(Symbol sym); /** pre.sym.type * sym represents a valueS */ public case SingleType(Type pre, Symbol sym) { assert this instanceof ExtSingleType; } /** pre.sym[args] * sym represents a type * for example: scala.List[java.lang.String] is coded as * * TypeRef( * SingleType(ThisType(definitions.ROOT_CLASS), definitions.SCALA), * <List>, * new Type[]{ * TypeRef( * SingleType( * SingleType(ThisType(definitions.ROOT_CLASS), definitions.JAVA), * definitions.LANG), * definitions.STRING, * new Type[]{})}). * */ public case TypeRef(Type pre, Symbol sym, Type[] args) { assert pre.isLegalPrefix() || pre == ErrorType : pre + "#" + sym; assert sym.kind == ERROR || sym.isType() : pre + " # " + sym; } /** parts_1 with ... with parts_n { members } */ public case CompoundType(Type[] parts, Scope members) { assert this instanceof ExtCompoundType; } /** synthetic type of a method def ...(vparams): result = ... */ public case MethodType(Symbol[] vparams, Type result); /** synthetic type of a method def ...[tparams]result * For instance, given def f[a](x: a): a * f has type PolyType(new Symbol[]{<a>}, * MethodType(new Symbol[]{<x>}, <a>.type())) * * if tparams is empty, this is the type of a parameterless method * def ... = * For instance, given def f = 1 * f has type PolyType(new Symbol[]{}, <scala.Int>.type()) */ public case PolyType(Symbol[] tparams, Type result); /** synthetic type of an overloaded value whose alternatives are * alts_1, ..., alts_n, with respective types alttypes_1, ..., alttypes_n * * For instance, if there are two definitions of `f' * def f: int * def f: String * then there are three symbols: * ``f1'' corresponding to def f: int * ``f2'' corresponding to def f: String * ``f3'' corresponding to both * f3 has type * OverloadedType( * new Symbol[]{<f1>, <f2>}, * new Type[]{PolyType(new Symbol[]{}, <int>), * PolyType(new Symbol[]{}, <String>), * */ public case OverloadedType(Symbol[] alts, Type[] alttypes); /** Hidden case to implement delayed evaluation of types. * No need to pattern match on this type; it will never come up. */ public case LazyType(); /** Hidden case to implement local type inference. * Later phases do not need to match on this type. */ public case TypeVar(Type origin, Constraint constr); /** Hidden cases to implement type erasure. * Earlier phases do not need to match on these types. */ public case UnboxedType(int tag); public case UnboxedArrayType(Type elemtp); /** Force evaluation of a lazy type. No cycle * check is needed; since this is done in Symbol. * @see Symbol.info(). */ public void complete(Symbol p) {} /** An owner-less ThisType */ public static Type localThisType = ThisType(Symbol.NONE); /** An empty Type array */ public static final Type[] EMPTY_ARRAY = new Type[0]; public static SingleType singleType(Type pre, Symbol sym) { if (pre.isStable() || pre == ErrorType) { return new ExtSingleType(pre, sym); } else { throw new Type.Error( "malformed type: " + pre + "#" + sym.nameString() + ".type"); } } public static TypeRef appliedType(Type tycon, Type[] args) { switch (tycon) { case TypeRef(Type pre, Symbol sym, Type[] args1): if (args == args1) return (TypeRef)tycon; else return TypeRef(pre, sym, args); default: throw new ApplicationError(); } } public static CompoundType compoundType(Type[] parts, Scope members, Symbol clazz) { ExtCompoundType res = new ExtCompoundType(parts, members); res.tsym = clazz; return res; } public static CompoundType compoundType(Type[] parts, Scope members) { ExtCompoundType res = new ExtCompoundType(parts, members); res.tsym = new ClassSymbol( Position.FIRSTPOS, Names.COMPOUND_NAME.toTypeName(), Symbol.NONE, SYNTHETIC | ABSTRACTCLASS); res.tsym.setInfo(res); res.tsym.primaryConstructor().setInfo( Type.MethodType(Symbol.EMPTY_ARRAY, Type.NoType)); return res; } public static Type typeRef(Type pre, Symbol sym, Type[] args) { if (pre.isLegalPrefix() || pre == ErrorType) return TypeRef(pre, sym, args); else if (sym.kind == ALIAS) return pre.memberInfo(sym); else // todo: handle Java-style inner classes throw new Type.Error( "malformed type: " + pre + "#" + sym.nameString()); } static class ExtSingleType extends SingleType { Type tp = null; int definedId = -1; ExtSingleType(Type pre, Symbol sym) { super(pre, sym); } public Type singleDeref() { if (definedId != Global.instance.currentPhase.id) { definedId = Global.instance.currentPhase.id; tp = pre.memberType(sym).resultType(); } return tp; } } static class ExtCompoundType extends CompoundType { Symbol tsym; ExtCompoundType(Type[] parts, Scope members) { super(parts, members); } public Symbol symbol() { return tsym; } void validate() {//debug for (Scope.SymbolIterator it = members.iterator(true); it.hasNext(); ) assert it.next().owner() == tsym; } } void validate() {//debug } /** If this is a thistype, named type, applied type, singleton type, or compound type, * its symbol, otherwise Symbol.NONE. */ public Symbol symbol() { switch (this) { case ErrorType: return Symbol.ERROR; case ThisType(Symbol sym): return sym; case TypeRef(_, Symbol sym, _): return sym; case SingleType(_, Symbol sym): return sym; case TypeVar(Type origin, _): return origin.symbol(); case CompoundType(_, _): // overridden in ExtCompoundType throw new ApplicationError(); default: return Symbol.NONE; } } public static Symbol[] symbol(Type[] tps) { Symbol[] syms = new Symbol[tps.length]; for (int i = 0; i < syms.length; i++) syms[i] = tps[i].symbol(); return syms; } /** The upper bound of this type. Returns always a TypeRef whose * symbol is a class. */ public Type bound() { switch (this) { case TypeRef(Type pre, Symbol sym, _): if (sym.kind == ALIAS) return unalias().bound(); if (sym.kind == TYPE) return pre.memberInfo(sym).bound(); assert sym.isClass() : Debug.show(sym) + " -- " + this; return this; case ThisType(_): case SingleType(_, _): return singleDeref().bound(); case TypeVar(_, _): return unalias().bound(); default: throw Debug.abort("illegal case", this); } } /** If this type is a thistype or singleton type, its type, * otherwise the type itself. */ public Type singleDeref() { switch (this) { case ThisType(Symbol sym): return sym.typeOfThis(); case SingleType(Type pre, Symbol sym): // overridden in ExtSingleType throw new ApplicationError(); case TypeVar(Type origin, Constraint constr): if (constr.inst != NoType) return constr.inst.singleDeref(); else return this; default: return this; } } /** If this type is a thistype or singleton type, its underlying object type, * otherwise the type itself. */ public Type widen() { Type tp = singleDeref(); switch (tp) { case ThisType(_): case SingleType(_, _): return tp.widen(); default: return tp; } } private static Map widenMap = new Map() { public Type apply(Type t) { return t.widen(); } }; public static Type[] widen(Type[] tps) { return widenMap.map(tps); } /** The thistype or singleton type corresponding to values of this type. */ public Type narrow() { switch (this) { case TypeRef(Type pre, Symbol sym, Type[] args): if (sym.kind == ALIAS) return pre.memberInfo(sym).narrow(); else if (sym.kind == CLASS) return sym.thisType(); else return ThisType(sym); case CompoundType(_, _): return symbol().thisType(); default: return this; } } /** The lower approximation of this type (which must be a typeref) */ public Type loBound() { switch (unalias()) { case TypeRef(Type pre, Symbol sym, Type[] args): Type lb = Global.instance.definitions.ALL_TYPE; if (sym.kind == TYPE) { lb = pre.memberLoBound(sym); } if (lb.symbol() == Global.instance.definitions.ALL_CLASS && this.symbol() != Global.instance.definitions.ALL_CLASS && this.isSubType(Global.instance.definitions.ANYREF_TYPE)) { lb = Global.instance.definitions.ALLREF_TYPE; } return lb; default: throw new ApplicationError(); } } /** If this is a this-type, named-type, applied type or single-type, its prefix, * otherwise NoType. */ public Type prefix() { switch (this) { case ThisType(Symbol sym): return sym.owner().thisType(); case TypeRef(Type pre, _, _): return pre; case SingleType(Type pre, _): return pre; case TypeVar(Type origin, Constraint constr): if (constr.inst != NoType) return constr.inst.prefix(); else return NoType; default: return NoType; } } /** Get all type arguments of this type. */ public Type[] typeArgs() { switch (unalias()) { case TypeRef(_, _, Type[] args): return args; default: return Type.EMPTY_ARRAY; } } /** Get type of `this' symbol corresponding to this type, extend * homomorphically to function types and poly types. */ public Type instanceType() { switch (unalias()) { case TypeRef(Type pre, Symbol sym, Type[] args): if (sym != sym.thisSym()) return sym.typeOfThis() .asSeenFrom(pre, sym.owner()) .subst(sym.typeParams(), args); break; case MethodType(Symbol[] params, Type restp): Type restp1 = restp.instanceType(); if (restp1 != restp) return MethodType(params, restp1); break; case PolyType(Symbol[] tparams, Type restp): Type restp1 = restp.instanceType(); if (restp1 != restp) return PolyType(tparams, restp1); break; } return this; } /** Remove all aliases */ public Type unalias() { Type result = unalias(0);//debug //if (this != result) System.out.println(this + " ==> " + result);//DEBUG return result; } private Type unalias(int n) { if (n == 100) throw new Type.Error("alias chain too long (recursive type alias?): " + this); switch (this) { case TypeRef(Type pre, Symbol sym, Type[] args): if (sym.kind == ALIAS) return pre.memberInfo(sym).unalias(n + 1); break; case TypeVar(Type origin, Constraint constr): if (constr.inst != NoType) return constr.inst.unalias(n + 1); else return this; } return this; } /** The (prefix/argument-adapted) parents of this type. */ public Type[] parents() { switch (unalias()) { case ThisType(_): case SingleType(_, _): return singleDeref().parents(); case TypeRef(Type pre, Symbol sym, Type[] args): if (sym.kind == ALIAS) return unalias().parents(); else if (sym.kind == CLASS) { assert sym.typeParams().length == args.length : sym + " " + ArrayApply.toString(args) + " " + sym.primaryConstructor().info();//debug return subst(asSeenFrom(sym.info().parents(), pre, sym.owner()), sym.typeParams(), args); } else return new Type[]{sym.info().asSeenFrom(pre, sym.owner())}; case CompoundType(Type[] parts, _): return parts; default: return Type.EMPTY_ARRAY; } } /** Get type parameters of method type (a PolyType or MethodType) * or EMPTY_ARRAY if method type is not polymorphic. */ public Symbol[] typeParams() { switch (this) { case PolyType(Symbol[] tparams, _): return tparams; case MethodType(Symbol[] vparams, _): return Symbol.EMPTY_ARRAY; case TypeRef(_, Symbol sym, Type[] args): if (args.length == 0) return sym.typeParams(); else return Symbol.EMPTY_ARRAY; default: return Symbol.EMPTY_ARRAY; } } /** Get value parameters of method type (a PolyType or MethodType) * or EMPTY_ARRAY if method type has no value parameter section. */ public Symbol[] valueParams() { return valueParams(false); } private Symbol[] valueParams(boolean ok) { switch (this) { case PolyType(_, Type result): return result.valueParams(true); case MethodType(Symbol[] vparams, _): return vparams; default: if (ok) return Symbol.EMPTY_ARRAY; throw Debug.abort("illegal case", this); } } /** If this type is a (possibly polymorphic) method type, its result type * after applying all method argument sections, * otherwise the type itself. */ public Type resultType() { switch (this) { case PolyType(_, Type tpe): return tpe.resultType(); case MethodType(_, Type tpe): return tpe.resultType(); default: return this; } } /** The number of value parameter sections of this type. */ public int paramSectionCount() { switch (this) { case PolyType(_, Type restpe): return restpe.paramSectionCount(); case MethodType(_, Type restpe): return restpe.paramSectionCount() + 1; default: return 0; } } /** The first parameter section of this type. */ public Symbol[] firstParams() { switch (this) { case PolyType(_, Type restpe): return restpe.firstParams(); case MethodType(Symbol[] params, _): return params; default: return Symbol.EMPTY_ARRAY; } } /** If this type is overloaded, its alternative types, * otherwise an array consisting of this type itself. */ public Type[] alternativeTypes() { switch (this) { case OverloadedType(_, Type[] alttypes): return alttypes; default: return new Type[]{this}; } } /** If this type is overloaded, its alternative symbols, * otherwise an empty array. */ public Symbol[] alternativeSymbols() { switch (this) { case OverloadedType(Symbol[] alts, _): return alts; default: return Symbol.EMPTY_ARRAY; } } /** If type is a this type of a module class, transform to singletype of * module. */ public Type expandModuleThis() { switch (this) { case ThisType(Symbol sym): if ((sym.flags & MODUL) != 0 && sym.module() != Symbol.NONE) { return singleType( sym.owner().thisType().expandModuleThis(), sym.module()); } } return this; } /** Is this type a this type or singleton type? */ public boolean isStable() { switch (unalias()) { case ThisType(_): case SingleType(_, _): return true; default: return false; } } public boolean isLegalPrefix() { switch (unalias()) { case ThisType(_): case SingleType(_, _): return true; case TypeRef(_, Symbol sym, _): return sym.kind == CLASS && ((sym.flags & JAVA) != 0 || (sym.flags & (TRAIT | ABSTRACTCLASS)) == 0); default: return false; } } /** Is this type a reference to an object type? * todo: replace by this.isSubType(global.definitions.ANY_TYPE)? */ public boolean isObjectType() { switch (unalias()) { case ThisType(_): case SingleType(_, _): case CompoundType(_, _): return true; case TypeRef(Type pre, Symbol sym, _): return sym.kind != ALIAS || unalias().isObjectType(); default: return false; } } /** Is this type of the form scala.FunctionN[T_1, ..., T_n, +T] or * scala.Object with scala.FunctionN[T_1, ..., T_n, +T]? */ public boolean isFunctionType() { switch (this) { case TypeRef(Type pre, Symbol sym, Type[] args): return sym.fullName().startsWith(Names.scala_Function) && args.length > 0; case CompoundType(Type[] parents, Scope members): return members.isEmpty() && parents.length == 2 && parents[0].symbol().fullName() == Names.scala_Object && parents[1].isFunctionType(); } return false; } /** Is this a polymorphic method type? */ public boolean isPolymorphic() { return typeParams().length > 0; } /** Is this a parameterized or polymorphic method type? */ public boolean isParameterized() { switch (this) { case MethodType(_, _): return true; default: return isPolymorphic(); } } /** Get the scope containing the local members of this type. * Symbols in this scope are not prefix-adapted! */ public Scope members() { switch (this) { case ErrorType: return new Scope(); case TypeRef(_, Symbol sym, _): return sym.info().members(); case SingleType(_, Symbol sym): return singleDeref().members(); case CompoundType(Type[] basetypes, Scope members): return members; default: return Scope.EMPTY; } } /** Lookup symbol with given name among all local and inherited members * of this type; return Symbol.NONE if not found. */ public Symbol lookup(Name name) { switch (this) { case ErrorType: return Symbol.ERROR; case ThisType(_): case SingleType(_, _): return singleDeref().lookup(name); case TypeRef(_, Symbol sym, _): return sym.info().lookup(name); case CompoundType(Type[] parts, Scope members): Symbol sym = members.lookup(name); if (sym.kind != NONE) return sym; else return lookupNonPrivate(name); default: return Symbol.NONE; } } /** Lookup non-private symbol with given name among all local and * inherited members of this type; return Symbol.NONE if not found. */ public Symbol lookupNonPrivate(Name name) { return lookupNonPrivate(name, 0); } /** Same as before, but with additional parameter `start'. * If start == 0, lookup in all basetypes of a compound type. * If start == 1, lookup only in mixin classes. */ private Symbol lookupNonPrivate(Name name, int start) { switch (this) { case ErrorType: return Symbol.ERROR; case ThisType(_): case SingleType(_, _): return singleDeref().lookupNonPrivate(name); case TypeRef(_, Symbol sym, _): return sym.info().lookupNonPrivate(name, start); case CompoundType(Type[] parts, Scope members): Symbol sym = members.lookup(name); if (sym.kind != NONE && (sym.flags & PRIVATE) == 0) return sym; // search base types in reverse; non-abstract members // take precedence over abstract ones. int i = parts.length; sym = Symbol.NONE; while (i > start && (sym.kind == NONE || (sym.flags & DEFERRED) != 0)) { i Symbol sym1 = parts[i].lookupNonPrivate(name, i == 0 ? 0 : 1); if (sym1.kind != NONE && (sym1.flags & PRIVATE) == 0 && (sym.kind == NONE || (sym1.flags & DEFERRED) == 0)) sym = sym1; } return sym; default: return Symbol.NONE; } } /** The type of type-to-type functions. */ public abstract static class Map { public abstract Type apply(Type t); /** * This method assumes that all symbols in MethodTypes and * PolyTypes have already been cloned. */ public Type applyParams(Type type) { switch (type) { case MethodType(Symbol[] vparams, Type result): map(vparams, true); Type result1 = applyParams(result); return result == result1 ? type : MethodType(vparams, result1); case PolyType(Symbol[] tparams, Type result): map(tparams, true); Type result1 = applyParams(result); return result == result1 ? type : PolyType(tparams, result1); default: return apply(type); } } /** Apply map to all top-level components of this type. */ public Type map(Type tp) { switch (tp) { case ErrorType: case AnyType: case NoType: case UnboxedType(_): case TypeVar(_, _): case ThisType(_): return tp; case TypeRef(Type pre, Symbol sym, Type[] args): Type pre1 = apply(pre); Type[] args1 = map(args); if (pre1 == pre && args1 == args) return tp; else return typeRef(pre1, sym, args1); case SingleType(Type pre, Symbol sym): Type pre1 = apply(pre); if (pre1 == pre) return tp; else return singleType(pre1, sym); case CompoundType(Type[] parts, Scope members): Type[] parts1 = map(parts); Scope members1 = map(members); if (parts1 == parts && members1 == members) { return tp; } else if (members1 == members && !tp.symbol().isCompoundSym()) { return compoundType(parts1, members, tp.symbol()); } else { Scope members2 = new Scope(); //Type tp1 = compoundType(parts1, members2); Type tp1 = (tp.symbol().isCompoundSym()) ? compoundType(parts1, members2) : compoundType(parts1, members2, tp.symbol()); Symbol[] syms1 = members1.elements(); Symbol[] syms2 = new Symbol[syms1.length]; for (int i = 0; i < syms2.length; i++) { syms2[i] = syms1[i].cloneSymbol(tp1.symbol()); } for (int i = 0; i < syms2.length; i++) { syms2[i].setInfo(syms1[i].info().subst(syms1, syms2)); if (syms2[i].kind == TYPE) syms2[i].setLoBound(syms1[i].loBound().subst(syms1, syms2)); } for (int i = 0; i < syms2.length; i++) { members2.enter(syms2[i]); } return tp1; } case MethodType(Symbol[] vparams, Type result): Symbol[] vparams1 = map(vparams); Type result1 = apply(result); if (vparams1 == vparams && result1 == result) return tp; else return MethodType(vparams1, result1); case PolyType(Symbol[] tparams, Type result): Symbol[] tparams1 = map(tparams); Type result1 = apply(result); if (tparams1 != tparams) result1 = result1.subst(tparams, tparams1); if (tparams1 == tparams && result1 == result) return tp; else return PolyType(tparams1, result1); case OverloadedType(Symbol[] alts, Type[] alttypes): Type[] alttypes1 = map(alttypes); if (alttypes1 == alttypes) return tp; else return OverloadedType(alts, alttypes1); case UnboxedArrayType(Type elemtp): Type elemtp1 = apply(elemtp); if (elemtp1 == elemtp) return tp; else return UnboxedArrayType(elemtp1); default: throw new ApplicationError(tp + " " + tp.symbol()); } } public final Symbol map(Symbol sym) { return map(sym, false); } public Symbol map(Symbol sym, boolean dontClone) { Type tp = sym.info(); Type tp1 = apply(tp); if (tp != tp1) { if (!dontClone) sym = sym.cloneSymbol(); sym.setInfo(tp1); dontClone = true; } if (sym.kind == TYPE) { Type lb = sym.loBound(); Type lb1 = apply(lb); if (lb != lb1) { if (!dontClone) sym = sym.cloneSymbol(); sym.setLoBound(lb1); } } return sym; } public Type[] map(Type[] tps) { Type[] tps1 = tps; for (int i = 0; i < tps.length; i++) { Type tp = tps[i]; Type tp1 = apply(tp); if (tp1 != tp && tps1 == tps) { tps1 = new Type[tps.length]; System.arraycopy(tps, 0, tps1, 0, i); } tps1[i] = tp1; } return tps1; } /** Apply map to all elements of this array of symbols, * preserving recursive references to symbols in the array. */ public final Symbol[] map(Symbol[] syms) { return map(syms, false); } public Symbol[] map(Symbol[] syms, boolean dontClone) { Symbol[] syms1 = syms; for (int i = 0; i < syms.length; i++) { Symbol sym = syms[i]; Symbol sym1 = map(sym, dontClone); if (sym != sym1 && syms1 == syms) { syms1 = new Symbol[syms.length]; System.arraycopy(syms, 0, syms1, 0, i); } syms1[i] = sym1; } if (syms1 != syms) { for (int i = 0; i < syms1.length; i++) { if (syms1[i] == syms[i]) syms1[i] = syms[i].cloneSymbol(); } new SubstSymMap(syms, syms1).map(syms1, true); } return syms1; } /** Apply map to all elements of this array of this scope. */ public Scope map(Scope s) { Symbol[] members = s.elements(); Symbol[] members1 = map(members); if (members == members1) return s; else return new Scope(members1); } } public abstract static class MapOnlyTypes extends Map { public Symbol map(Symbol sym, boolean dontClone) { return sym; } public Symbol[] map(Symbol[] syms, boolean dontClone) { return syms; } public Scope map(Scope s) { return s; } } public static final Map IdMap = new Map() { public Type apply(Type tp) { return tp; } public Type applyParams(Type tp) { return tp; } public Type map(Type tp) { return tp; } public Symbol map(Symbol sym, boolean dontClone) { return sym; } public Type[] map(Type[] tps) { return tps; } public Symbol[] map(Symbol[] syms, boolean dontClone) { return syms; } public Scope map(Scope scope) { return scope; } }; /** Return the base type of this type whose symbol is `clazz', or NoType, if * such a type does not exist. */ public Type baseType(Symbol clazz) { //System.out.println(this + ".baseType(" + clazz + ")");//DEBUG switch (this) { case ErrorType: return ErrorType; case ThisType(_): case SingleType(_, _): return singleDeref().baseType(clazz); case TypeRef(Type pre, Symbol sym, Type[] args): if (sym == clazz) return this; else if (sym.kind == TYPE || sym.kind == ALIAS) return pre.memberInfo(sym).baseType(clazz); else if (clazz.isCompoundSym()) return NoType; else { return sym.baseType(clazz) .asSeenFrom(pre, clazz.owner()) .subst(sym.typeParams(), args); } case CompoundType(Type[] parts, _): for (int i = parts.length - 1; i >= 0; i Type result = parts[i].baseType(clazz); if (result != NoType) return result; } break; case UnboxedArrayType(_): if (clazz == Global.instance.definitions.ANY_CLASS || clazz == Global.instance.definitions.ANYREF_CLASS) return clazz.type(); } return NoType; } /** Return overriding instance of `sym' in this type, * or `sym' itself if none exists. */ public Symbol rebind(Symbol sym) { Symbol sym1 = lookupNonPrivate(sym.name); if (sym1.kind != NONE) { //System.out.println("rebinding " + sym + " to " + sym1);//DEBUG return sym1; } else return sym; } /** A map to implement `asSeenFrom'. */ static class AsSeenFromMap extends Map { private Type pre; private Symbol clazz; AsSeenFromMap(Type pre, Symbol clazz) { this.pre = pre; this.clazz = clazz; } public Type apply(Type t) { if (pre == NoType || clazz.kind != CLASS) return t; switch (t) { case ThisType(Symbol sym): return t.toPrefix(sym, pre, clazz); case TypeRef(Type prefix, Symbol sym, Type[] args): if (sym.kind == ALIAS) { return apply(t.unalias()); } else if (sym.owner().isPrimaryConstructor()) { assert sym.kind == TYPE; Type t1 = t.toInstance(sym, pre, clazz); //System.out.println(t + ".toInstance(" + pre + "," + clazz + ") = " + t1);//DEBUG return t1; } else { Type prefix1 = apply(prefix); Symbol sym1 = (prefix1 == prefix || (sym.flags & MODUL) != 0) ? sym : prefix1.rebind(sym); Type[] args1 = map(args); if (prefix1 == prefix && args1 == args) return t; else return typeRef(prefix1, sym1, args1); } case SingleType(Type prefix, Symbol sym): try { Type prefix1 = apply(prefix); if (prefix1 == prefix) return t; else return singleType(prefix1, prefix1.rebind(sym)); } catch (Type.Error ex) {} return apply(t.singleDeref()); default: return map(t); } } } //where Type toInstance(Symbol sym, Type pre, Symbol clazz) { if (pre == NoType || clazz.kind != CLASS) return this; Symbol ownclass = sym.owner().constructorClass(); if (ownclass == clazz && pre.widen().symbol().isSubClass(ownclass)) { switch (pre.baseType(ownclass)) { case TypeRef(_, Symbol basesym, Type[] baseargs): Symbol[] baseparams = basesym.typeParams(); for (int i = 0; i < baseparams.length; i++) { if (sym == baseparams[i]) return baseargs[i]; } System.out.println(sym + " " + basesym + " " + ArrayApply.toString(baseparams));//debug break; case ErrorType: return ErrorType; } throw new ApplicationError( this + " in " + ownclass + " cannot be instantiated from " + pre.widen() ); } else { return toInstance(sym, pre.baseType(clazz).prefix(), clazz.owner()); } } Type toPrefix(Symbol sym, Type pre, Symbol clazz) { if (pre == NoType || clazz.kind != CLASS) return this; else if (sym.isSubClass(clazz) && pre.widen().symbol().isSubClass(sym)) return pre; else return toPrefix(sym, pre.baseType(clazz).prefix(), clazz.owner()); } /** This type as seen from prefix `pre' and class `clazz'. This means: * Replace all thistypes of `clazz' or one of its superclasses by `pre' * and instantiate all parameters by arguments of `pre'. * Proceed analogously for thistypes referring to outer classes. */ public Type asSeenFrom(Type pre, Symbol clazz) { //System.out.println("computing asseenfrom of " + this + " with " + pre + "," + clazz);//DEBUG return new AsSeenFromMap(pre, clazz).apply(this); } /** Types `these' as seen from prefix `pre' and class `clazz'. */ public static Type[] asSeenFrom(Type[] these, Type pre, Symbol clazz) { return new AsSeenFromMap(pre, clazz).map(these); } /** The info of `sym', seen as a member of this type. */ public Type memberInfo(Symbol sym) { return sym.info().asSeenFrom(this, sym.owner()); } /** The type of `sym', seen as a member of this type. */ public Type memberType(Symbol sym) { return sym.type().asSeenFrom(this, sym.owner()); } /** The low bound of `sym', seen as a member of this type. */ public Type memberLoBound(Symbol sym) { return sym.loBound().asSeenFrom(this, sym.owner()); } /** A common map superclass for symbol/symbol and type/symbol substitutions. */ public static abstract class SubstMap extends Map { private Symbol[] from; SubstMap(Symbol[] from) { this.from = from; } public boolean matches(Symbol sym1, Symbol sym2) { return sym1 == sym2; } /** Produce replacement type * @param i The index in `from' of the symbol to be replaced. * @param fromtp The type referring to this symbol. */ protected abstract Type replacement(int i, Type fromtp); /** Produce new substitution where some symbols are excluded. * @param newfrom The new array of from symbols (without excluded syms) * @param excluded The array of excluded sysmbols */ protected abstract SubstMap exclude(Symbol[] newfrom, Symbol[] excluded); public Type apply(Type t) { switch (t) { case TypeRef(ThisType(_), Symbol sym, Type[] args): for (int i = 0; i < from.length; i++) { if (matches(sym, from[i])) return replacement(i, t); } break; case SingleType(ThisType(_), Symbol sym): for (int i = 0; i < from.length; i++) { if (matches(sym, from[i])) return replacement(i, t); } break; case PolyType(Symbol[] tparams, Type result): Symbol[] from1 = excludeSyms(from, tparams, from); if (from1 != from) { SubstMap f = exclude(from1, tparams); Symbol[] tparams1 = f.map(tparams); Type result1 = f.apply(result); if (tparams1 != tparams) result1 = result1.subst(tparams, tparams1); if (tparams1 == tparams && result1 == result) return t; else return PolyType(tparams1, result1); } } return map(t); } //where private boolean contains1(Symbol[] syms, Symbol sym) { int i = 0; while (i < syms.length && syms[i] != sym) i++; return i < syms.length; } private int nCommon(Symbol[] from, Symbol[] tparams) { int cnt = 0; for (int i = 0; i < from.length; i++) { if (contains1(tparams, from[i])) cnt++; } return cnt; } private Symbol[] excludeSyms(Symbol[] from, Symbol[] tparams, Symbol[] syms) { int n = nCommon(from, tparams); if (n == 0) { return syms; } else { Symbol[] syms1 = new Symbol[syms.length - n]; int j = 0; for (int i = 0; i < from.length; i++) { if (!contains1(tparams, from[i])) syms1[j++] = syms[i]; } return syms1; } } private Type[] excludeTypes(Symbol[] from, Symbol[] tparams, Type[] types) { int n = nCommon(from, tparams); if (n == 0) { return types; } else { Type[] types1 = new Type[types.length - n]; int j = 0; for (int i = 0; i < from.length; i++) { if (!contains1(tparams, from[i])) types1[j++] = types[i]; } return types1; } } } /** A map for symbol/symbol substitutions */ public static class SubstSymMap extends SubstMap { Symbol[] to; protected SubstSymMap(Symbol[] from, Symbol[] to) { super(from); this.to = to; } protected Type replacement(int i, Type fromtp) { switch (fromtp) { case TypeRef(Type pre, Symbol sym, Type[] args): return typeRef(pre, to[i], args); case SingleType(Type pre, Symbol sym): return singleType(pre, to[i]); default: throw new ApplicationError(); } } protected SubstMap exclude(Symbol[] newfrom, Symbol[] excluded) { return new SubstSymMap(newfrom, excludeSyms(from, excluded, to)); } } /** A map for type/symbol substitutions */ public static class SubstTypeMap extends SubstMap { Type[] to; protected SubstTypeMap(Symbol[] from, Type[] to) { super(from); this.to = to; } protected Type replacement(int i, Type fromtp) { return to[i]; } protected SubstMap exclude(Symbol[] newfrom, Symbol[] excluded) { return new SubstTypeMap(newfrom, excludeTypes(from, excluded, to)); } } /** A map for symbol/symbol substitutions which, instead of * cloning parameters, updates their symbol's types. */ public static class UpdateSubstSymMap extends SubstSymMap { protected UpdateSubstSymMap(Symbol[] from, Symbol[] to) { super(from, to); } public Type apply(Type t) { switch (t) { case PolyType(Symbol[] params, Type result): // !!! Also update loBounds? How? loBound can only be set! for (int i = 0; i < params.length; i++) { Type tp = params[i].nextType(); Type tp1 = apply(tp); if (tp != tp1) params[i].updateInfo(tp1); } Type result1 = apply(result); if (result1 == result) return t; else return Type.PolyType(params, result1); case MethodType(Symbol[] params, Type result): for (int i = 0; i < params.length; i++) { Type tp = params[i].nextType(); Type tp1 = apply(tp); if (tp != tp1) params[i].updateInfo(tp1); } Type result1 = apply(result); if (result1 == result) return t; else return Type.MethodType(params, result1); default: return super.apply(t); } } public Symbol map(Symbol sym, boolean dontClone) { return sym; } public Symbol[] map(Symbol[] syms, boolean dontClone) { return syms; } public Scope map(Scope s) { return s; } } /** Returns the given non-updating symbol/symbol substitution. */ public static Map getSubst(Symbol[] from, Symbol[] to) { return getSubst(from, to, false); } /** Returns the given (updating?) symbol/symbol substitution. */ public static Map getSubst(Symbol[] from, Symbol[] to, boolean update) { if (from.length == 0 && to.length == 0) return IdMap; if (update) return new UpdateSubstSymMap(from, to); return new SubstSymMap(from, to); } /** Returns the given non-updating symbol/type substitution. */ public static Map getSubst(Symbol[] from, Type[] to) { if (from.length == 0 && to.length == 0) return IdMap; return new SubstTypeMap(from, to); } /** Substitute symbols `to' for occurrences of symbols `from' in this type. */ public Type subst(Symbol[] from, Symbol[] to) { if (to.length != 0 && from != to) { assert from.length == to.length : this + ": " + from.length + " != " + to.length; return new SubstSymMap(from, to).apply(this); } else return this; } /** Substitute symbols `to' for occurrences of symbols `from' in these types. */ public static Type[] subst(Type[] these, Symbol[] from, Symbol[] to) { if (these.length != 0 && to.length != 0 && from != to) { assert from.length == to.length; return new SubstSymMap(from, to).map(these); } else return these; } /** Substitute types `to' for occurrences of symbols `from' in this type. */ public Type subst(Symbol[] from, Type[] to) { if (to.length != 0) { assert from.length == to.length : this + ": " + Debug.show(from) + " <> " + ArrayApply.toString(to); return new SubstTypeMap(from, to).apply(this); } else return this; } /** Substitute types `to' for occurrences of symbols `from' in these types. */ public static Type[] subst(Type[] these, Symbol[] from, Type[] to) { if (these.length != 0 && to.length != 0) { assert from.length == to.length; return new SubstTypeMap(from, to).map(these); } else return these; } /** A map for substitutions of thistypes. */ public static class SubstThisMap extends Map { Symbol from; Type to; public SubstThisMap(Symbol from, Type to) { this.from = from; this.to = to; } public SubstThisMap(Symbol oldSym, Symbol newSym) { this(oldSym, newSym.thisType()); } public Type apply(Type t) { switch (t) { case ThisType(Symbol sym): if (sym == from) return to; else return t; default: return map(t); } } } public Type substThis(Symbol from, Type to) { return new SubstThisMap(from, to).apply(this); } public static Type[] substThis(Type[] these, Symbol from, Type to) { return new SubstThisMap(from, to).map(these); } static class ContainsMap extends Map { boolean result = false; Symbol sym; ContainsMap(Symbol sym) { this.sym = sym; } public Type apply(Type t) { if (!result) { switch (t) { case TypeRef(Type pre, Symbol sym1, Type[] args): if (sym == sym1) result = true; else { map(pre); map(args); } break; case SingleType(Type pre, Symbol sym1): map(pre); if (sym == sym1) result = true; break; default: map(t); } } return t; } } /** Does this type contain symbol `sym'? */ public boolean contains(Symbol sym) { ContainsMap f = new ContainsMap(sym); f.apply(this); return f.result; } /** Does this type contain any of the symbols `syms'? */ public boolean containsSome(Symbol[] syms) { for (int i = 0; i < syms.length; i++) if (contains(syms[i])) return true; return false; } /** Returns a shallow copy of the given array. */ public static Type[] cloneArray(Type[] array) { return cloneArray(0, array, 0); } /** * Returns a shallow copy of the given array prefixed by "prefix" * null items. */ public static Type[] cloneArray(int prefix, Type[] array) { return cloneArray(prefix, array, 0); } /** * Returns a shallow copy of the given array suffixed by "suffix" * null items. */ public static Type[] cloneArray(Type[] array, int suffix) { return cloneArray(0, array, suffix); } /** * Returns a shallow copy of the given array prefixed by "prefix" * null items and suffixed by "suffix" null items. */ public static Type[] cloneArray(int prefix, Type[] array, int suffix) { assert prefix >= 0 && suffix >= 0: prefix + " - " + suffix; int size = prefix + array.length + suffix; if (size == 0) return EMPTY_ARRAY; Type[] clone = new Type[size]; for (int i = 0; i < array.length; i++) clone[prefix + i] = array[i]; return clone; } /** Returns the concatenation of the two arrays. */ public static Type[] concat(Type[] array1, Type[] array2) { if (array1.length == 0) return array2; if (array2.length == 0) return array1; Type[] clone = cloneArray(array1.length, array2); for (int i = 0; i < array1.length; i++) clone[i] = array1[i]; return clone; } /** * Clones a type i.e. returns a new type where all symbols in * MethodTypes and PolyTypes have been cloned. */ public Type cloneType(Symbol oldOwner, Symbol newOwner) { switch (this) { case MethodType(Symbol[] vparams, Type result): Symbol[] clones = new Symbol[vparams.length]; for (int i = 0; i < clones.length; i++) { assert vparams[i].owner() == oldOwner : Debug.show(vparams[i]); clones[i] = vparams[i].cloneSymbol(newOwner); } result = result.cloneType(oldOwner, newOwner); Type clone = Type.MethodType(clones, result); if (vparams.length != 0) clone = new SubstSymMap(vparams, clones).applyParams(clone); return clone; case PolyType(Symbol[] tparams, Type result): Symbol[] clones = new Symbol[tparams.length]; for (int i = 0; i < clones.length; i++) { assert tparams[i].owner() == oldOwner : Debug.show(tparams[i]); clones[i] = tparams[i].cloneSymbol(newOwner); } result = result.cloneType(oldOwner, newOwner); Type clone = Type.PolyType(clones, result); if (tparams.length != 0) clone = new SubstSymMap(tparams, clones).applyParams(clone); return clone; default: return this; } } /** * Clones a type i.e. returns a new type where all symbols in * MethodTypes and PolyTypes have been cloned. This method * performs no substitution on the type of the cloned symbols. * Typically, the type of those symbols will be fixed later by * applying some Map.applyParams method to the returned type. */ public Type cloneTypeNoSubst(SymbolCloner cloner) { switch (this) { case MethodType(Symbol[] vparams, Type result): Symbol[] clones = cloner.cloneSymbols(vparams); return Type.MethodType(clones, result.cloneTypeNoSubst(cloner)); case PolyType(Symbol[] tparams, Type result): Symbol[] clones = cloner.cloneSymbols(tparams); return Type.PolyType(clones, result.cloneTypeNoSubst(cloner)); default: return this; } } /** Is this type a subtype of that type? */ public boolean isSubType(Type that) { if (explainSwitch) { for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(this + " < " + that + "?"); indent++; } boolean result = isSubType0(that); if (explainSwitch) { indent for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(result); } return result; } public boolean isSubType0(Type that) { if (this == that) return true; switch (this) { case ErrorType: case AnyType: return true; } switch (that) { case ErrorType: case AnyType: return true; case NoType: return false; case ThisType(_): case SingleType(_, _): switch (this) { case ThisType(_): case SingleType(_, _): return this.isSameAs(that); } break; case TypeRef(Type pre1, Symbol sym1, Type[] args1): switch (this) { case TypeRef(Type pre, Symbol sym, Type[] args): if (pre.isSubType(pre1) && (sym == sym1 || sym == pre.rebind(sym1)) && isSubArgs(args, args1, sym.typeParams()) || sym.kind == TYPE && pre.memberInfo(sym).isSubType(that)) return true; break; } if (sym1.kind == CLASS) { Type base = this.baseType(sym1); if (this != base && base.isSubType(that)) return true; } break; case CompoundType(Type[] parts1, Scope members1): int i = 0; while (i < parts1.length && isSubType(parts1[i])) i++; if (i == parts1.length && specializes(members1)) return true; break; case MethodType(Symbol[] ps1, Type res1): switch (this) { case MethodType(Symbol[] ps, Type res): if (ps.length != ps1.length) return false; for (int i = 0; i < ps.length; i++) { Symbol p1 = ps1[i]; Symbol p = ps[i]; if (!p1.type().isSameAs(p.type()) || (p1.flags & (Modifiers.DEF | Modifiers.REPEATED)) != (p.flags & (Modifiers.DEF | Modifiers.REPEATED))) return false; } return res.isSubType(res1); } break; case PolyType(Symbol[] ps1, Type res1): switch (this) { case PolyType(Symbol[] ps, Type res): if (ps.length != ps1.length) return false; for (int i = 0; i < ps.length; i++) if (!ps1[i].info().subst(ps1, ps).isSameAs(ps[i].info()) || !ps[i].loBound().isSameAs(ps1[i].loBound().subst(ps1, ps))) return false; return res.isSubType(res1.subst(ps1, ps)); } break; case OverloadedType(Symbol[] alts1, Type[] alttypes1): for (int i = 0; i < alttypes1.length; i++) { if (!isSubType(alttypes1[i])) return false; } return true; case UnboxedType(int tag1): switch (this) { case UnboxedType(int tag): return tag == tag1 || (tag < tag1 && tag1 <= DOUBLE && tag1 != CHAR); } break; case UnboxedArrayType(UnboxedType(int tag1)): switch (this) { case UnboxedArrayType(UnboxedType(int tag)): return tag1 == tag; } break; case UnboxedArrayType(Type elemtp1): switch (this) { case UnboxedArrayType(Type elemtp): return elemtp.isSubType(elemtp1); } break; case TypeVar(Type origin, Constraint constr): //todo: should we test for equality with origin? if (constr.inst != NoType) { return this.isSubType(constr.inst); } else { constr.lobounds = new List(this, constr.lobounds); return true; } default: throw new ApplicationError(this + " <: " + that); } switch (this) { case NoType: return false; case ThisType(_): case SingleType(_, _): if (this.singleDeref().isSubType(that)) return true; break; case TypeVar(Type origin, Constraint constr): if (constr.inst != NoType) { return constr.inst.isSubType(that); } else { constr.hibounds = new List(that, constr.hibounds); return true; } case TypeRef(_, Symbol sym, _): switch (that) { case TypeRef(Type pre1, Symbol sym1, _): if (sym1.kind == TYPE && this.isSubType(that.loBound())) return true; } if (sym.kind == ALIAS) return this.unalias().isSubType(that); else if (sym == Global.instance.definitions.ALL_CLASS) return that.isSubType(Global.instance.definitions.ANY_TYPE); else if (sym == Global.instance.definitions.ALLREF_CLASS) return that.symbol() == Global.instance.definitions.ANY_CLASS || (that.symbol() != Global.instance.definitions.ALL_CLASS && that.isSubType(Global.instance.definitions.ANYREF_TYPE)); break; case OverloadedType(Symbol[] alts, Type[] alttypes): for (int i = 0; i < alttypes.length; i++) { if (alttypes[i].isSubType(that)) return true; } break; } switch (that) { case TypeRef(_, Symbol sym1, _): if (sym1.kind == ALIAS) return this.isSubType(that.unalias()); break; } return false; } /** Are types `these' subtypes of corresponding types `those'? */ public static boolean isSubType(Type[] these, Type[] those) { if (these.length != those.length) return false; for (int i = 0; i < these.length; i++) { if (!these[i].isSubType(those[i])) return false; } return true; } /** Are types `these' arguments types conforming to corresponding types `those'? */ static boolean isSubArgs(Type[] these, Type[] those, Symbol[] tparams) { if (these.length != those.length) return false; for (int i = 0; i < these.length; i++) { if ((tparams[i].flags & COVARIANT) != 0) { if (!these[i].isSubType(those[i])) return false; } else if ((tparams[i].flags & CONTRAVARIANT) != 0) { //System.out.println("contra: " + these[i] + " " + those[i] + " " + those[i].isSubType(these[i]));//DEBUG if (!those[i].isSubType(these[i])) return false; } else { if (!these[i].isSameAs(those[i])) return false; } } return true; } public static boolean isSubSet(Type[] alts, Type[] alts1) { for (int i = 0; i < alts.length; i++) { int j = 0; while (j < alts1.length && !alts1[j].isSameAs(alts[i])) j++; if (j == alts1.length) return false; } return true; } /** Does this type implement all symbols in scope `s' with same or stronger types? */ public boolean specializes(Scope s) { for (Scope.SymbolIterator it = s.iterator(true); it.hasNext();) { if (!specializes(it.next())) return false; } return true; } /** Does this type implement symbol `sym1' with same or stronger type? */ public boolean specializes(Symbol sym1) { if (explainSwitch) { for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(this + " specializes " + sym1 + "?"); indent++; } boolean result = specializes0(sym1); if (explainSwitch) { indent for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(result); } return result; } private boolean specializes0(Symbol sym1) { Type self = narrow(); Symbol[] tparams = symbol().typeParams(); Type[] targs = typeArgs(); Symbol sym = lookup(sym1.name); return sym.kind != NONE && (sym == sym1 || (sym.kind == sym1.kind || sym1.kind == TYPE) && self.memberInfo(sym).subst(tparams, targs) .isSubType(sym1.info().substThis(sym1.owner(), self)) && sym1.loBound().substThis(sym1.owner(), self) .isSubType(self.memberLoBound(sym).subst(tparams, targs)) || (sym.kind == TYPE && sym1.kind == ALIAS && sym1.info().unalias().isSameAs(sym.type()))); } /** Is this type the same as that type? */ public boolean isSameAs(Type that) { if (explainSwitch) { for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(this + " = " + that + "?"); indent++; } boolean result = isSameAs0(that); if (explainSwitch) { indent for (int i = 0; i < indent; i++) System.out.print(" "); System.out.println(result); } return result; } public boolean isSameAs0(Type that) { if (this == that) return true; switch (this) { case ErrorType: case AnyType: return true; case ThisType(Symbol sym): switch (that) { case ThisType(Symbol sym1): return sym == sym1; case SingleType(Type pre1, Symbol sym1): return sym1.isModule() && sym == sym1.moduleClass() && sym.owner().thisType().isSameAs(pre1) || deAlias(that) != that && this.isSameAs(deAlias(that)); } break; case SingleType(Type pre, Symbol sym): switch (that) { case SingleType(Type pre1, Symbol sym1): return sym == sym1 && pre.isSameAs(pre1) || (deAlias(this) != this || deAlias(that) != that) && deAlias(this).isSameAs(deAlias(that)); case ThisType(Symbol sym1): return sym.isModule() && sym.moduleClass() == sym1 && pre.isSameAs(sym1.owner().thisType()) || deAlias(this) != this && deAlias(this).isSameAs(that); } break; case TypeRef(Type pre, Symbol sym, Type[] args): switch (that) { case TypeRef(Type pre1, Symbol sym1, Type[] args1): if (sym == sym1 && pre.isSameAs(pre1) && isSameAs(args, args1)) return true; } break; case CompoundType(Type[] parts, Scope members): switch (that) { case CompoundType(Type[] parts1, Scope members1): if (parts.length != parts1.length) return false; for (int i = 0; i < parts.length; i++) if (!parts[i].isSameAs(parts1[i])) return false; return isSameAs(members, members1); } break; case MethodType(Symbol[] ps, Type res): switch (that) { case MethodType(Symbol[] ps1, Type res1): if (ps.length != ps1.length) return false; for (int i = 0; i < ps.length; i++) { Symbol p1 = ps1[i]; Symbol p = ps[i]; if (!p1.type().isSameAs(p.type()) || (p1.flags & (Modifiers.DEF | Modifiers.REPEATED)) != (p.flags & (Modifiers.DEF | Modifiers.REPEATED))) return false; } return res.isSameAs(res1); } break; case PolyType(Symbol[] ps, Type res): switch (that) { case PolyType(Symbol[] ps1, Type res1): if (ps.length != ps1.length) return false; for (int i = 0; i < ps.length; i++) if (!ps1[i].info().subst(ps1, ps).isSameAs(ps[i].info()) || !ps1[i].loBound().subst(ps1, ps).isSameAs(ps[i].loBound())) return false; return res.isSameAs(res1.subst(ps1, ps)); } break; case OverloadedType(Symbol[] alts, Type[] alttypes): switch (that) { case OverloadedType(Symbol[] alts1, Type[] alttypes1): return isSubSet(alttypes1, alttypes) && isSubSet(alttypes, alttypes1); } break; case UnboxedType(int kind): switch (that) { case UnboxedType(int kind1): return kind == kind1; } break; case UnboxedArrayType(Type elemtp): switch (that) { case UnboxedArrayType(Type elemtp1): return elemtp.isSameAs(elemtp1); } break; } switch (that) { case ErrorType: case AnyType: return true; case NoType: return false; case TypeVar(Type origin, Constraint constr): if (constr.inst != NoType) return constr.inst.isSameAs(this); else return constr.instantiate(this.any2typevar()); } switch (this) { case NoType: return false; case TypeRef(_, Symbol sym, _): if (sym.kind == ALIAS) return this.unalias().isSameAs(that); break; case TypeVar(Type origin, Constraint constr): if (constr.inst != NoType) return constr.inst.isSameAs(that); else return constr.instantiate(that.any2typevar()); } switch (that) { case TypeRef(_, Symbol sym, _): if (sym.kind == ALIAS) return this.isSameAs(that.unalias()); } return false; } //where Type deAlias(Type tp) { switch (tp) { case SingleType(_, _): Type tp1 = tp.singleDeref(); if (tp1.isStable()) return deAlias(tp1); } return tp; } /** Are types `these' the same as corresponding types `those'? */ public static boolean isSameAs(Type[] these, Type[] those) { if (these.length != those.length) return false; for (int i = 0; i < these.length; i++) { if (!these[i].isSameAs(those[i])) return false; } return true; } /** Do scopes `s1' and `s2' define he same symbols with the same kinds and infos? */ public boolean isSameAs(Scope s1, Scope s2) { return isSubScope(s1, s2) && isSubScope(s2, s1); } /** Does scope `s1' define all symbols of scope `s2' with the same kinds and infos? */ private boolean isSubScope(Scope s1, Scope s2) { for (Scope.SymbolIterator it = s2.iterator(); it.hasNext(); ) { Symbol sym2 = it.next(); Symbol sym1 = s1.lookup(sym2.name); if (sym1.kind != sym2.kind || !sym1.info().isSameAs( sym2.info().substThis( sym2.owner(), sym1.owner().thisType())) || !sym1.loBound().isSameAs( sym2.loBound().substThis( sym2.owner(), sym1.owner().thisType()))) return false; } return true; } boolean isSameAsAll(Type[] tps) { int i = 1; while (i < tps.length && isSameAs(tps[i])) i++; return i == tps.length; } /** Map every occurrence of AnyType to a fresh type variable. */ public static Map any2typevarMap = new Map() { public Type apply(Type t) { return t.any2typevar(); } }; public Type any2typevar() { switch (this) { case AnyType: return TypeVar(this, new Constraint()); default: return any2typevarMap.map(this); } } /** The closure of this type, i.e. the widened type itself followed by all * its direct and indirect (pre-) base types, sorted by Symbol.isLess(). */ public Type[] closure() { switch (this.widen().unalias()) { case TypeRef(Type pre, Symbol sym, Type[] args): return subst( asSeenFrom(sym.closure(), pre, sym.owner()), sym.typeParams(), args); case CompoundType(Type[] parts, Scope members): Type[][] closures = new Type[parts.length][]; for (int i = 0; i < parts.length; i++) closures[i] = parts[i].closure(); return union(closures); default: return new Type[]{this}; } } /** return union of array of closures. It is assumed that * for any two base types with the same class symbols the later one * is a subtype of the former. */ static private Type[] union(Type[][] closures) { if (closures.length == 1) return closures[0]; // fast special case int[] index = new int[closures.length]; int totalsize = 0; for (int i = 0; i < index.length; i++) { index[i] = 0; totalsize = totalsize + closures[i].length; } Type[] res = new Type[totalsize]; int j = 0; while (true) { // find minimal element Type min = null; for (int i = 0; i < index.length; i++) { if (index[i] < closures[i].length) { Type cltype = closures[i][index[i]]; if (min == null || cltype.symbol().isLess(min.symbol()) || cltype.symbol() == min.symbol()) { min = cltype; } } } if (min == null) break; res[j] = min; j = j + 1; // bump all indices that start with minimal element for (int i = 0; i < index.length; i++) { if (index[i] < closures[i].length && closures[i][index[i]].symbol() == min.symbol()) index[i] = index[i] + 1; } } Type[] result = new Type[j]; System.arraycopy(res, 0, result, 0, j); return result; } /** return intersection of non-empty array of closures */ static private Type[] intersection(Type[][] closures) { if (closures.length == 1) return closures[0]; // fast special case int[] index = new int[closures.length]; Type[] mintypes = new Type[closures.length]; int minsize = Integer.MAX_VALUE; for (int i = 0; i < index.length; i++) { index[i] = 0; if (closures[i].length < minsize) minsize = closures[i].length; } Type[] res = new Type[minsize]; int j = 0; L: while (true) { // find minimal element Symbol minsym = null; for (int i = 0; i < index.length; i++) { if (index[i] == closures[i].length) break L; Symbol clsym = closures[i][index[i]].symbol(); if (minsym == null || clsym.isLess(minsym)) minsym = clsym; } boolean agree = true; // bump all indices that start with minimal element for (int i = 0; i < index.length; i++) { Type cltype = closures[i][index[i]]; if (cltype.symbol() == minsym) { mintypes[i] = cltype; index[i] = index[i] + 1; } else { agree = false; } } if (agree) { Type mintype = argLub(mintypes); if (mintype.symbol().kind == CLASS) { res[j] = mintype; j = j + 1; } } } Type[] result = new Type[j]; System.arraycopy(res, 0, result, 0, j); return result; } /** same as lub, but all types are instances of the same class, * possibly with different prefixes and arguments. */ //todo: catch lubs not within bounds. static Type argLub(Type[] tps) { tps = elimRedundant(tps, true); if (tps.length == 1) return tps[0]; Type pre = tps[0].prefix(); Symbol sym = tps[0].symbol(); Symbol[] tparams = sym.typeParams(); Type[] args = new Type[tparams.length]; Type[][] argss = new Type[args.length][tps.length]; for (int i = 0; i < tps.length; i++) { switch (tps[i]) { case TypeRef(Type pre1, Symbol sym1, Type[] args1): assert sym == sym1; assert args1.length == args.length; if (!pre.isSameAs(pre1)) return NoType; for (int j = 0; j < args1.length; j++) argss[j][i] = args1[j]; break; case ErrorType: return ErrorType; default: assert false : tps[i]; } } for (int j = 0; j < args.length; j++) { if ((tparams[j].flags & COVARIANT) != 0) args[j] = lub(argss[j]); else if ((tparams[j].flags & CONTRAVARIANT) != 0) args[j] = glb(argss[j]); else return NoType; } return typeRef(pre, sym, args); } /** The frontier of a closure C is the minimal set of types such that * the union of the closures of these types equals C. */ static private Type[] frontier(Type[] closure) { Type[] front = new Type[closure.length]; int j = 0; for (int i = 0; i < closure.length; i++) { int k = 0; Type tp = closure[i]; while (k < j && !front[k].symbol().isSubClass(tp.symbol())) k++; if (k == j) { front[j] = tp; j++; } } Type[] result = new Type[j]; System.arraycopy(front, 0, result, 0, j); return result; } /** remove types that are subtypes of some other type. */ static private Type[] elimRedundant(Type[] tps, boolean elimLower) { Type.List tl = Type.List.EMPTY; int nredundant = 0; boolean[] redundant = new boolean[tps.length]; for (int i = 0; i < tps.length; i++) { if (tps[i] == ErrorType) { return new Type[]{ErrorType}; } else { assert tps[i].isObjectType(): tps[i]; for (int j = 0; j < i && !redundant[i]; j++) { if (!redundant[j]) { if (tps[i].isSubType(tps[j])) { redundant[elimLower ? i : j] = true; nredundant++; } else if (tps[j].isSubType(tps[i])) { redundant[elimLower ? j : i] = true; nredundant++; } } } } } if (nredundant != 0) { Type[] tps1 = new Type[tps.length - nredundant]; int n = 0; for (int i = 0; i < tps.length; i++) { if (!redundant[i]) tps1[n++] = tps[i]; } return tps1; } else { return tps; } } /** Return the least upper bound of non-empty array of types `tps'. */ public static Type lub(Type[] tps) { //System.out.println("lub" + ArrayApply.toString(tps));//DEBUG if (tps.length == 0) return Global.instance.definitions.ALL_TYPE; //If all types are method types with same parameters, //compute lub of their result types. // remove types that are subtypes of some other type. tps = elimRedundant(tps, true); if (tps.length == 1) return tps[0]; // intersect closures and build frontier. Type[][] closures = new Type[tps.length][]; for (int i = 0; i < tps.length; i++) { closures[i] = tps[i].closure(); } Type[] allBaseTypes = intersection(closures); Type[] leastBaseTypes = frontier(allBaseTypes); assert leastBaseTypes.length > 0 : ArrayApply.toString(tps); // add refinements where necessary Scope members = new Scope(); Type lubType = compoundType(leastBaseTypes, members); Type lubThisType = lubType.narrow(); //System.out.println("lubtype = " + lubType);//DEBUG Symbol[] rsyms = new Symbol[tps.length]; Type[] rtps = new Type[tps.length]; Type[] rlbs = new Type[tps.length]; for (int i = 0; i < allBaseTypes.length; i++) { for (Scope.SymbolIterator it = allBaseTypes[i].members().iterator(); it.hasNext(); ) { Symbol sym = it.next(); Name name = sym.name; if ((sym.flags & PRIVATE) == 0 && lubType.lookup(name) == sym) { Type symType = memberTp(lubThisType, sym); Type symLoBound = lubThisType.memberLoBound(sym); int j = 0; while (j < tps.length) { rsyms[j] = tps[j].lookupNonPrivate(name); if (rsyms[j] == sym) break; rtps[j] = memberTp(tps[j], rsyms[j]) .substThis(tps[j].symbol(), lubThisType); rlbs[j] = tps[j].memberLoBound(rsyms[j]) .substThis(tps[j].symbol(), lubThisType); if (rtps[j].isSameAs(symType) && rlbs[j].isSameAs(symLoBound)) break; j++; } if (j == tps.length) { Symbol lubSym = lub(rsyms, rtps, rlbs, lubType.symbol()); if (lubSym.kind != NONE && !(lubSym.kind == sym.kind && lubSym.info().isSameAs(symType) && lubSym.loBound().isSameAs(symType))) members.enter(lubSym); } } } } //System.out.print("lub "); System.out.print(ArrayApply.toString(tps)); System.out.println(" = " + lubType);//DEBUG if (leastBaseTypes.length == 1 && members.isEmpty()) return leastBaseTypes[0]; else return lubType; } //where private static Type memberTp(Type base, Symbol sym) { return sym.kind == CLASS ? base.memberType(sym) : base.memberInfo(sym); } private static Symbol lub(Symbol[] syms, Type[] tps, Type[] lbs, Symbol owner) { //System.out.println("lub" + ArrayApply.toString(syms));//DEBUG int lubKind = syms[0].kind; for (int i = 1; i < syms.length; i++) { Symbol sym = syms[i]; if (sym.kind == ERROR) return Symbol.NONE; if (sym.isType() && sym.kind != lubKind) lubKind = TYPE; } if (lubKind == syms[0].kind && tps[0].isSameAsAll(tps)) { return syms[0].cloneSymbol(); } Type lubType = lub(tps); if (lubType == Type.NoType) return Symbol.NONE; Symbol lubSym; switch (lubKind) { case VAL: lubSym = new TermSymbol(syms[0].pos, syms[0].name, owner, 0); break; case TYPE: case ALIAS: case CLASS: lubSym = new AbsTypeSymbol(syms[0].pos, syms[0].name, owner, 0); lubSym.setLoBound(glb(lbs)); break; default: throw new ApplicationError(); } lubSym.setInfo(lubType); return lubSym; } public static Type glb(Type[] tps) { if (tps.length == 0) return Global.instance.definitions.ANY_TYPE; // step one: eliminate redunandant types; return if one one is left tps = elimRedundant(tps, false); if (tps.length == 1) return tps[0]; // step two: build arrays of all typerefs and all refinements Type.List treftl = Type.List.EMPTY; Type.List comptl = Type.List.EMPTY; for (int i = 0; i < tps.length; i++) { switch (tps[i]) { case TypeRef(_, _, _): treftl = new Type.List(tps[i], treftl); break; case CompoundType(Type[] parents, Scope members): if (!members.isEmpty()) comptl = new Type.List(tps[i], comptl); for (int j = 0; j < parents.length; j++) treftl = new Type.List(parents[j], treftl); break; case ThisType(_): case SingleType(_, _): return Global.instance.definitions.ALL_TYPE; } } CompoundType glbType = compoundType(Type.EMPTY_ARRAY, new Scope()); Type glbThisType = glbType.narrow(); // step 3: compute glb of all refinements. Scope members = Scope.EMPTY; if (comptl != List.EMPTY) { Type[] comptypes = comptl.toArrayReverse(); Scope[] refinements = new Scope[comptypes.length]; for (int i = 0; i < comptypes.length; i++) refinements[i] = comptypes[i].members(); if (!setGlb(glbType.members, refinements, glbThisType)) { // refinements don't have lower bound, so approximate // by AllRef glbType.members = Scope.EMPTY; treftl = new Type.List( Global.instance.definitions.ALLREF_TYPE, treftl); } } // eliminate redudant typerefs Type[] treftypes = elimRedundant(treftl.toArrayReverse(), false); if (treftypes.length != 1 || !glbType.members.isEmpty()) { // step 4: replace all abstract types by their lower bounds. boolean hasAbstract = false; for (int i = 0; i < treftypes.length; i++) { if (treftypes[i].unalias().symbol().kind == TYPE) hasAbstract = true; } if (hasAbstract) { treftl = Type.List.EMPTY; for (int i = 0; i < treftypes.length; i++) { if (treftypes[i].unalias().symbol().kind == TYPE) treftl = new Type.List(treftypes[i].loBound(), treftl); else treftl = new Type.List(treftypes[i], treftl); } treftypes = elimRedundant(treftl.toArrayReverse(), false); } } if (treftypes.length != 1) { // step 5: if there are conflicting instantiations of same // class, replace them by lub/glb of arguments or lower bound. Type lb = NoType; for (int i = 0; i < treftypes.length && lb.symbol() != Global.instance.definitions.ALL_CLASS; i++) { for (int j = 0; j < i; j++) { if (treftypes[j].symbol() == treftypes[i].symbol()) lb = argGlb(treftypes[j], treftypes[i]); } } if (lb != NoType) return lb; } if (treftypes.length == 1 && glbType.members.isEmpty()) { return treftypes[0]; } else { glbType.parts = treftypes; return glbType; } } private static Type argGlb(Type tp1, Type tp2) { switch (tp1) { case TypeRef(Type pre1, Symbol sym1, Type[] args1): switch (tp2) { case TypeRef(Type pre2, Symbol sym2, Type[] args2): assert sym1 == sym2; if (pre1.isSameAs(pre2)) { Symbol[] tparams = sym1.typeParams(); Type[] args = new Type[tparams.length]; for (int i = 0; i < tparams.length; i++) { if (args1[i].isSameAs(args2[i])) args[i] = args1[i]; else if ((tparams[i].flags & COVARIANT) != 0) args[i]= lub(new Type[]{args1[i], args2[i]}); else if ((tparams[i].flags & CONTRAVARIANT) != 0) args[i]= glb(new Type[]{args1[i], args2[i]}); else return glb(new Type[]{tp1.loBound(), tp2.loBound()}); } return typeRef(pre1, sym1, args); } } } return glb(new Type[]{tp1.loBound(), tp2.loBound()}); } /** Set scope `result' to glb of scopes `ss'. Return true iff succeeded. */ private static boolean setGlb(Scope result, Scope[] ss, Type glbThisType) { for (int i = 0; i < ss.length; i++) for (Scope.SymbolIterator it = ss[i].iterator(); it.hasNext(); ) if (!addMember(result, it.next(), glbThisType)) return false; return true; } /** Add member `sym' to scope `s'. If`s' has already a member with same name, * overwrite its info/low bound to form glb of both symbols. */ private static boolean addMember(Scope s, Symbol sym, Type glbThisType) { Type syminfo = sym.info().substThis(sym.owner(), glbThisType); Type symlb = sym.loBound().substThis(sym.owner(), glbThisType); Scope.Entry e = s.lookupEntry(sym.name); if (e == Scope.Entry.NONE) { Symbol sym1 = sym.cloneSymbol(glbThisType.symbol()); sym1.setInfo(syminfo); if (sym1.kind == TYPE) sym1.setLoBound(symlb); s.enter(sym1); } else { Type einfo = e.sym.info(); if (einfo.isSameAs(syminfo)) { } else if (einfo.isSubType(syminfo) && sym.kind != ALIAS) { } else if (syminfo.isSubType(einfo) && e.sym.kind != ALIAS) { e.sym.setInfo(syminfo); } else if (sym.kind == VAL && e.sym.kind == VAL || sym.kind == TYPE && e.sym.kind == TYPE) { e.sym.setInfo(glb(new Type[]{einfo, syminfo})); } else { return false; } if (e.sym.kind == TYPE && sym.kind == TYPE) { Type elb = e.sym.loBound(); if (elb.isSameAs(symlb)) { } else if (symlb.isSubType(elb)) { } else if (elb.isSubType(symlb)) { e.sym.setLoBound(symlb); } else { e.sym.setLoBound(lub(new Type[]{elb, symlb})); } } } return true; } public static Map erasureMap = new MapOnlyTypes() { public Type apply(Type t) { return t.erasure(); } }; private static final Type[] unboxedType = new Type[LastUnboxedTag + 1 - FirstUnboxedTag]; private static final Type[] unboxedArrayType = new Type[LastUnboxedTag + 1 - FirstUnboxedTag]; private static final Name[] unboxedName = new Name[LastUnboxedTag + 1 - FirstUnboxedTag]; private static final Name[] boxedName = new Name[LastUnboxedTag + 1 - FirstUnboxedTag]; private static final Name[] boxedFullName = new Name[LastUnboxedTag + 1 - FirstUnboxedTag]; private static void mkStdClassType(int kind, String unboxedstr, String boxedstr) { unboxedType[kind - FirstUnboxedTag] = UnboxedType(kind); unboxedArrayType[kind - FirstUnboxedTag] = UnboxedArrayType(unboxedType(kind)); unboxedName[kind - FirstUnboxedTag] = Name.fromString(unboxedstr); boxedName[kind - FirstUnboxedTag] = Name.fromString(boxedstr); boxedFullName[kind - FirstUnboxedTag] = Name.fromString("scala." + boxedstr); } static { mkStdClassType(BYTE, "byte", "Byte"); mkStdClassType(SHORT, "short", "Short"); mkStdClassType(CHAR, "char", "Char"); mkStdClassType(INT, "int", "Int"); mkStdClassType(LONG, "long", "Long"); mkStdClassType(FLOAT, "float", "Float"); mkStdClassType(DOUBLE, "double", "Double"); mkStdClassType(BOOLEAN, "boolean", "Boolean"); mkStdClassType(UNIT, "void", "Unit"); } /** Return unboxed type of given kind. */ public static Type unboxedType(int kind) { return unboxedType[kind - FirstUnboxedTag]; } /** Return unboxed array type of given element kind. */ public static Type unboxedArrayType(int kind) { return unboxedArrayType[kind - FirstUnboxedTag]; } /** Return the name of unboxed type of given kind. */ public static Name unboxedName(int kind) { return unboxedName[kind - FirstUnboxedTag]; } /** Return the name of boxed type of given kind. */ public static Name boxedName(int kind) { return boxedName[kind - FirstUnboxedTag]; } /** Return the full name of boxed type of given kind. */ public static Name boxedFullName(int kind) { return boxedFullName[kind - FirstUnboxedTag]; } /** If type is boxed, return its unboxed equivalent; otherwise return the type * itself. */ public Type unbox() { switch (this) { case TypeRef(Type pre, Symbol sym, Type[] args): if ((sym.flags & MODUL) == 0) { Name fullname = sym.fullName(); if (fullname == Names.scala_Array && args.length == 1) { Type item = args[0].unalias(); Type bound = item.upperBound(); // todo: check with Philippe if this is what we want. if (item.symbol().isClass() || (bound.symbol() != Global.instance.definitions.ANY_CLASS && bound.symbol() != Global.instance.definitions.ANYVAL_CLASS)) { return UnboxedArrayType(args[0].erasure()); } } for (int i = 0; i < boxedFullName.length; i++) { if (boxedFullName[i] == fullname) return unboxedType[i]; } } } return this; } //where private Type upperBound() { switch (this) { case TypeRef(Type pre, Symbol sym, Type[] args): if (sym.kind == ALIAS || sym.kind == TYPE) return pre.memberInfo(sym).upperBound(); } return this; } /** Return the erasure of this type. */ public Type erasure() { switch (this) { case ThisType(_): case SingleType(_, _): return singleDeref().erasure(); case TypeRef(Type pre, Symbol sym, Type[] args): switch (sym.kind) { case ALIAS: case TYPE: return pre.memberInfo(sym).erasure(); case CLASS: if (sym == Global.instance.definitions.UNIT_CLASS) return this; Name fullname = sym.fullName(); if (fullname == Names.java_lang_Object || fullname == Names.scala_AnyRef || fullname == Names.scala_AnyVal || fullname == Names.scala_All || fullname == Names.scala_AllRef) return Global.instance.definitions.ANY_TYPE; else { Type this1 = unbox(); if (this1 != this) return this1; else return sym.typeConstructor(); } default: throw new ApplicationError(sym + " has wrong kind: " + sym.kind); } case CompoundType(Type[] parents, _): if (parents.length > 0) return parents[0].erasure(); else return this; case MethodType(Symbol[] params, Type tp): Symbol[] params1 = erasureMap.map(params); Type tp1 = tp.fullErasure(); switch (tp1) { case MethodType(Symbol[] params2, Type tp2): Symbol[] newparams = new Symbol[params1.length + params2.length]; System.arraycopy(params1, 0, newparams, 0, params1.length); System.arraycopy(params2, 0, newparams, params1.length, params2.length); return MethodType(newparams, tp2); default: if (params1 == params && tp1 == tp) return this; else return MethodType(params1, tp1); } case PolyType(_, Type result): return result.erasure(); default: return erasureMap.map(this); } } /** Return the full erasure of the type. Full erasure is the same * as "normal" erasure, except that the "Unit" type is erased to * the "void" type. */ public Type fullErasure() { if (Global.instance.definitions.UNIT_CLASS == symbol()) return unbox(); else return erasure(); } public String toString() { return new SymbolTablePrinter().printType(this).toString(); } public String toLongString() { String str = toString(); if (str.endsWith(".type")) return str + " (with underlying type " + widen() + ")"; else return str; } public int hashCode() { switch (this) { case ErrorType: return ERROR; case NoType: return NOtpe; case ThisType(Symbol sym): return THIStpe ^ (sym.hashCode() * 41); case TypeRef(Type pre, Symbol sym, Type[] args): return TYPEREFtpe ^ (pre.hashCode() * 41) ^ (sym.hashCode() * (41*41)) ^ (hashCode(args) * (41*41*41)); case SingleType(Type pre, Symbol sym): return SINGLEtpe ^ (pre.hashCode() * 41) ^ (sym.hashCode() * (41*41)); case CompoundType(Type[] parts, Scope members): return symbol().hashCode(); //return COMPOUNDtpe // ^ (hashCode(parts) * 41) // ^ (members.hashCode() * (41 * 41)); case MethodType(Symbol[] vparams, Type result): int h = METHODtpe; for (int i = 0; i < vparams.length; i++) h = (h << 4) ^ (vparams[i].flags & SOURCEFLAGS); return h ^ (hashCode(Symbol.type(vparams)) * 41) ^ (result.hashCode() * (41 * 41)); case PolyType(Symbol[] tparams, Type result): return POLYtpe ^ (hashCode(tparams) * 41) ^ (result.hashCode() * (41 * 41)); case OverloadedType(Symbol[] alts, Type[] alttypes): return OVERLOADEDtpe ^ (hashCode(alts) * 41) ^ (hashCode(alttypes) * (41 * 41)); case UnboxedType(int kind): return UNBOXEDtpe ^ (kind * 41); case UnboxedArrayType(Type elemtp): return UNBOXEDARRAYtpe ^ (elemtp.hashCode() * 41); default: throw new ApplicationError(); } } public static int hashCode(Object[] elems) { int h = 0; for (int i = 0; i < elems.length; i++) h = h * 41 + elems[i].hashCode(); return h; } // todo: change in relation to needs. public boolean equals(Object other) { if (this == other) { return true; } else if (other instanceof Type) { Type that = (Type) other; switch (this) { case ErrorType: return that == ErrorType; case NoType: return that == NoType; case ThisType(Symbol sym): switch (that) { case ThisType(Symbol sym1): return sym == sym1; default: return false; } case TypeRef(Type pre, Symbol sym, Type[] args): switch (that) { case TypeRef(Type pre1, Symbol sym1, Type[] args1): return pre.equals(pre1) && sym == sym1 && equals(args, args1); default: return false; } case SingleType(Type pre, Symbol sym): switch (that) { case SingleType(Type pre1, Symbol sym1): return pre.equals(pre1) && sym == sym1; default: return false; } case CompoundType(Type[] parts, Scope members): switch (that) { case CompoundType(Type[] parts1, Scope members1): return this.symbol() == that.symbol(); //return parts.equals(parts1) && members.equals(members1); default: return false; } case MethodType(Symbol[] vparams, Type result): switch (that) { case MethodType(Symbol[] vparams1, Type result1): if (vparams.length != vparams1.length) return false; for (int i = 0; i < vparams.length; i++) if ((vparams[i].flags & SOURCEFLAGS) != (vparams1[i].flags & SOURCEFLAGS)) return false; return equals(Symbol.type(vparams), Symbol.type(vparams1)) && result.equals(result1); default: return false; } case PolyType(Symbol[] tparams, Type result): switch (that) { case PolyType(Symbol[] tparams1, Type result1): return equals(tparams, tparams1) && result.equals(result1); default: return false; } case OverloadedType(Symbol[] alts, Type[] alttypes): switch (that) { case OverloadedType(Symbol[] alts1, Type[] alttypes1): return equals(alts, alts1) && equals(alttypes, alttypes1); default: return false; } case UnboxedType(int kind): switch (that) { case UnboxedType(int kind1): return kind == kind1; default: return false; } case UnboxedArrayType(Type elemtp): switch (that) { case UnboxedArrayType(Type elemtp1): return elemtp.equals(elemtp1); default: return false; } default: } } return false; } public static boolean equals(Object[] elems1, Object[] elems2) { if (elems1.length != elems2.length) return false; for (int i = 0; i < elems1.length; i++) { if (!elems1[i].equals(elems2[i])) return false; } return true; } /** A class for lists of types. */ public static class List { public Type head; public List tail; public List(Type head, List tail) { this.head = head; this.tail = tail; } public int length() { return (this == EMPTY) ? 0 : 1 + tail.length(); } public Type[] toArray() { Type[] ts = new Type[length()]; copyToArray(ts, 0, 1); return ts; } public void copyToArray(Type[] ts, int start, int delta) { if (this != EMPTY) { ts[start] = head; tail.copyToArray(ts, start+delta, delta); } } public Type[] toArrayReverse() { Type[] ts = new Type[length()]; copyToArray(ts, ts.length - 1, -1); return ts; } public String toString() { if (this == EMPTY) return "List()"; else return head + "::" + tail; } public static List EMPTY = new List(null, null); public static List append(List l, Type tp) { return (l == EMPTY) ? new List(tp, EMPTY) : new List(l.head, append(l.tail, tp)); } } /** A class for keeping sub/supertype constraints and instantiations * of type variables. */ public static class Constraint { public List lobounds = List.EMPTY; public List hibounds = List.EMPTY; public Type inst = NoType; public boolean instantiate(Type tp) { for (List l = lobounds; l != List.EMPTY; l = l.tail) { if (!l.head.isSubType(tp)) return false; } for (List l = hibounds; l != List.EMPTY; l = l.tail) { if (!tp.isSubType(l.head)) return false; } inst = tp; return true; } } /** A class for throwing type errors */ public static class Error extends java.lang.Error { public String msg; public Error(String msg) { super(msg); this.msg = msg; } } /** A class for throwing type errors */ public static class VarianceError extends Error { public VarianceError(String msg) { super(msg); } } public static void explainTypes(Type found, Type required) { if (Global.instance.explaintypes) { boolean s = explainSwitch; explainSwitch = true; found.isSubType(required); explainSwitch = s; } } } /* A standard pattern match: case ErrorType: case AnyType: case NoType: case ThisType(Symbol sym): case TypeRef(Type pre, Symbol sym, Type[] args): case SingleType(Type pre, Symbol sym): case CompoundType(Type[] parts, Scope members): case MethodType(Symbol[] vparams, Type result): case PolyType(Symbol[] tparams, Type result): case OverloadedType(Symbol[] alts, Type[] alttypes): */
package io.spine.test.validation; import com.google.common.collect.ImmutableList; import com.google.protobuf.DescriptorProtos.FieldOptions; import com.google.protobuf.GeneratedMessage.GeneratedExtension; import io.spine.option.OptionsProto; import io.spine.validate.FieldValue; import io.spine.validate.option.Constraint; import io.spine.validate.option.FieldValidatingOption; /** * A test-only implementation of a validating option. * * <p>It is sometimes required for tests that a call to validation fails with a predictable * exception. In such cases, the test authors may set up the fake option to fail validation. * * <p>This option is applied to any given field. Although the {@link #extension()} method returns * the {@code beta} extension, the option is not bound to any real Protobuf option. * * <p>If the {@link FakeOptionFactory#plannedException()} is non-null, the planned exception is * thrown by the constraint produced by this option. Otherwise, the constraint never discovers any * violations. */ @SuppressWarnings("Immutable") // effectively the 2nd type argument is an immutable Object. public final class FakeOption extends FieldValidatingOption<Void, Object> { FakeOption() { super(createExtension()); } @SuppressWarnings("unchecked") // OK for tests. private static GeneratedExtension<FieldOptions, Void> createExtension() { GeneratedExtension<FieldOptions, ?> beta = OptionsProto.beta; return (GeneratedExtension<FieldOptions, Void>) beta; } @Override public Constraint<FieldValue<Object>> constraintFor(FieldValue<Object> value) { RuntimeException exception = FakeOptionFactory.plannedException(); if (exception != null) { return v -> { throw exception; }; } else { return v -> ImmutableList.of(); } } @Override public boolean shouldValidate(FieldValue<Object> value) { return true; } }
package org.spongepowered.api.world; import static com.google.common.base.Preconditions.checkNotNull; import com.flowpowered.math.vector.Vector3d; import com.flowpowered.math.vector.Vector3i; import com.google.common.base.Optional; import org.spongepowered.api.block.BlockSnapshot; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.block.ScheduledBlockUpdate; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.service.persistence.data.DataHolder; import org.spongepowered.api.util.Direction; import org.spongepowered.api.world.extent.Extent; import java.util.Collection; /** * A position within a particular {@link Extent}. * * <p>This class is primarily a helper class to represent a location in a * particular {@link Extent}. The methods provided are proxy methods to ones * on {@link Extent}.</p> * * <p>Each instance can be used to either represent a block or a location on * a continuous coordinate system. Internally, positions are stored using * doubles. When a block-related method is used, the components of the * position are each rounded to an integer.</p> * * <p>Locations are immutable. Methods that change the properties of the * location create a new instance.</p> */ public class Location implements DataHolder { private final Extent extent; private final Vector3d position; private final Vector3i blockPosition; /** * Create a new instance. * * @param extent The extent * @param position The position */ public Location(Extent extent, Vector3d position) { checkNotNull(extent); checkNotNull(position); this.extent = extent; this.position = position; this.blockPosition = position.floor().toInt(); } /** * Get the underlying extent. * * @return The extent */ public Extent getExtent() { return this.extent; } /** * Get the underlying position. * * @return The underlying position */ public Vector3d getPosition() { return this.position; } /** * Get the underlying block position. * * @return The underlying block position */ public Vector3i getBlockPosition() { return this.blockPosition; } /** * Get the X component of this instance's position. * * @return The x component */ public double getX() { return getPosition().getX(); } /** * Get the Y component of this instance's position. * * @return The y component */ public double getY() { return getPosition().getY(); } /** * Get the Z component of this instance's position. * * @return The z component */ public double getZ() { return getPosition().getZ(); } /** * Get the floored X component of this instance's position. * * @return The floored x component */ public int getBlockX() { return getBlockPosition().getX(); } /** * Get the floored Y component of this instance's position. * * @return The floored y component */ public int getBlockY() { return getBlockPosition().getY(); } /** * Get the floored Z component of this instance's position. * * @return The floored z component */ public int getBlockZ() { return getBlockPosition().getZ(); } /** * Create a new instance with a new extent. * * @param extent The new extent * @return A new instance */ public Location setExtent(Extent extent) { checkNotNull(extent); if (extent == getExtent()) { return this; } return new Location(extent, getPosition()); } /** * Create a new instance with a new position. * * @param position The new position * @return A new instance */ public Location setPosition(Vector3d position) { checkNotNull(position); if (position == getPosition()) { return this; } return new Location(getExtent(), position); } /** * Add another Vector3d to the position on this instance, returning * a new Location instance. * * @param v The vector to add * @return A new instance */ public Location add(Vector3d v) { return add(v.getX(), v.getY(), v.getZ()); } /** * Add vector components to the position on this instance, returning * a new Location instance. * * @param x The x component * @param y The y component * @param z The z component * @return A new instance */ public Location add(double x, double y, double z) { return setPosition(getPosition().add(x, y, z)); } /** * Gets the location next to this one in the give direction. * * @param direction The direction to look in * @return The block in that direction */ public Location getRelative(Direction direction) { return add(direction.toVector3d()); } /** * Get the base type of block. * * <p>The type does not include block data such as the contents of * inventories.</p> * * @return The type of block */ public BlockType getType() { return getExtent().getBlockType(getBlockPosition()); } /** * Get the block state for this position. * * @return The current block state */ public BlockState getState() { return getExtent().getBlock(getBlockPosition()); } /** * Checks for whether the block at this position contains tile entity data. * * @return True if the block at this position has tile entity data, false otherwise */ boolean hasTileEntity() { return getExtent().getTileEntity(getBlockPosition()).isPresent(); } /** * Replace the block state at this position with a new state. * * <p>This will remove any extended block data at the given position.</p> * * @param state The new block state */ public void replaceWith(BlockState state) { getExtent().setBlock(getBlockPosition(), state); } /** * Replace the block at this position by a new type. * * <p>This will remove any extended block data at the given position.</p> * * @param type The new type */ public void replaceWith(BlockType type) { getExtent().setBlockType(getBlockPosition(), type); } /** * Replace the block at this position with a copy of the given snapshot. * * <p>Changing the snapshot afterwards will not affect the block that has * been placed at this location.</p> * * @param snapshot The snapshot */ public void replaceWith(BlockSnapshot snapshot) { getExtent().setBlockSnapshot(getBlockPosition(), snapshot); } /** * Remove the block at this position by replacing it with {@link BlockTypes#AIR}. * * <p>This will remove any extended block data at the given position.</p> */ @SuppressWarnings("ConstantConditions") void remove() { getExtent().setBlockType(getBlockPosition(), BlockTypes.AIR); } /** * Simulates the interaction with this object as if a player had done so. */ public void interact() { getExtent().interactBlock(getBlockPosition()); } /** * Simulates the interaction with this object using the given item as if * the player had done so. * * @param itemStack The item */ public void interactWith(ItemStack itemStack) { getExtent().interactBlockWith(getBlockPosition(), itemStack); } /** * Simulate the digging of the block as if a player had done so. * * @return Whether the block was destroyed */ public boolean dig() { return getExtent().digBlock(getBlockPosition()); } /** * Simulate the digging of the block with the given tool as if a player had * done so. * * @param itemStack The tool * @return Whether the block was destroyed */ public boolean digWith(ItemStack itemStack) { return getExtent().digBlockWith(getBlockPosition(), itemStack); } /** * Gets the time it takes to dig this block with a fist in ticks. * * @return The time in ticks */ public int getDigTime() { return getExtent().getBlockDigTime(getBlockPosition()); } /** * Gets the time it takes to dig this block the specified item in ticks. * * @param itemStack The item to pretend-dig with * @return The time in ticks */ public int getDigTimeWith(ItemStack itemStack) { return getExtent().getBlockDigTimeWith(getBlockPosition(), itemStack); } /** * Get the light level for this object. * * <p>Higher levels indicate a higher luminance.</p> * * @return A light level, nominally between 0 and 15, inclusive */ public byte getLuminance() { return getExtent().getLuminance(getBlockPosition()); } /** * Get the light level for this object that is caused by an overhead sky. * * <p>Higher levels indicate a higher luminance. If no sky is overheard, * the return value may be 0.</p> * * @return A light level, nominally between 0 and 15, inclusive */ public byte getLuminanceFromSky() { return getExtent().getLuminanceFromSky(getBlockPosition()); } /** * Get the light level for this object that is caused by everything other * than the sky. * * <p>Higher levels indicate a higher luminance.</p> * * @return A light level, nominally between 0 and 15, inclusive */ public byte getLuminanceFromGround() { return getExtent().getLuminanceFromGround(getBlockPosition()); } /** * Test whether the object is powered. * * @return Whether powered */ public boolean isPowered() { return getExtent().isBlockPowered(getBlockPosition()); } /** * Test whether the object is indirectly powered. * * @return Whether powered */ public boolean isIndirectlyPowered() { return getExtent().isBlockPowered(getBlockPosition()); } /** * Test whether the face in the given direction is powered. * * @param direction The direction * @return Whether powered */ public boolean isFacePowered(Direction direction) { return getExtent().isBlockFacePowered(getBlockPosition(), direction); } /** * Test whether the face in the given direction is indirectly powered. * * @param direction The direction * @return Whether powered */ public boolean isFaceIndirectlyPowered(Direction direction) { return getExtent().isBlockFaceIndirectlyPowered(getBlockPosition(), direction); } /** * Get all the faces of this block that are directly powered. * * @return Faces powered */ public Collection<Direction> getPoweredFaces() { return getExtent().getPoweredBlockFaces(getBlockPosition()); } /** * Get all faces of this block that are indirectly powered. * * @return Faces indirectly powered */ public Collection<Direction> getIndirectlyPoweredFaces() { return getExtent().getIndirectlyPoweredBlockFaces(getBlockPosition()); } /** * Test whether the the block will block the movement of entities. * * @return Blocks movement */ public boolean isPassable() { return getExtent().isBlockPassable(getBlockPosition()); } /** * Test whether the given face of the block can catch fire. * * @param direction The face of the block to check * @return Is flammable */ public boolean isFaceFlammable(Direction direction) { return getExtent().isBlockFlammable(getBlockPosition(), direction); } /** * Get a snapshot of this block at the current point in time. * * <p>A snapshot is disconnected from the {@link Extent} that it was taken * from so changes to the original block do not affect the snapshot.</p> * * @return A snapshot */ public BlockSnapshot getSnapshot() { return getExtent().getBlockSnapshot(getBlockPosition()); } @Override public <T> Optional<T> getData(Class<T> dataClass) { return getExtent().getBlockData(getBlockPosition(), dataClass); } /** * Gets a list of {@link ScheduledBlockUpdate}s on this block. * * @return A list of ScheduledBlockUpdates on this block */ Collection<ScheduledBlockUpdate> getScheduledUpdates() { return getExtent().getScheduledUpdates(getBlockPosition()); } /** * Adds a new {@link ScheduledBlockUpdate} to this block. * * @param priority The priority of the scheduled update * @param ticks The ticks until the scheduled update should be processed * @return The newly created scheduled update */ ScheduledBlockUpdate addScheduledUpdate(int priority, int ticks) { return getExtent().addScheduledUpdate(getBlockPosition(), priority, ticks); } /** * Removes a {@link ScheduledBlockUpdate} from this block. * * @param update The ScheduledBlockUpdate to remove */ void removeScheduledUpdate(ScheduledBlockUpdate update) { getExtent().removeScheduledUpdate(getBlockPosition(), update); } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return false; } }
package com.hannesdorfmann.sqlbrite.dao; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.hannesdorfmann.sqlbrite.dao.sql.SqlCompileable; import com.hannesdorfmann.sqlbrite.dao.sql.SqlFinishedStatement; import com.hannesdorfmann.sqlbrite.dao.sql.alter.ALTER_TABLE; import com.hannesdorfmann.sqlbrite.dao.sql.select.SELECT; import com.hannesdorfmann.sqlbrite.dao.sql.table.CREATE_TABLE; import com.hannesdorfmann.sqlbrite.dao.sql.table.DROP_TABLE; import com.hannesdorfmann.sqlbrite.dao.sql.table.DROP_TABLE_IF_EXISTS; import com.hannesdorfmann.sqlbrite.dao.sql.view.CREATE_VIEW; import com.hannesdorfmann.sqlbrite.dao.sql.view.CREATE_VIEW_IF_NOT_EXISTS; import com.hannesdorfmann.sqlbrite.dao.sql.view.DROP_VIEW; import com.hannesdorfmann.sqlbrite.dao.sql.view.DROP_VIEW_IF_EXISTS; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.QueryObservable; import java.util.Collections; import rx.Observable; import rx.functions.Func0; import static com.squareup.sqlbrite.BriteDatabase.Transaction; /** * Data Access Object (DAO). * * @author Hannes Dorfmann */ public abstract class Dao { /** * Builder pattern to build a query. */ public class QueryBuilder { String rawStatement; Iterable<String> rawStatementAffectedTables; SqlFinishedStatement statement; String[] args; boolean autoUpdate = true; public QueryBuilder(@Nullable Iterable<String> rawStatementAffectedTables, @NonNull String rawStatement) { if (rawStatement == null) { throw new NullPointerException("Raw SQL Query Statement is null"); } this.rawStatement = rawStatement; this.rawStatementAffectedTables = rawStatementAffectedTables; this.autoUpdate = rawStatementAffectedTables != null && rawStatementAffectedTables.iterator().hasNext(); } private QueryBuilder(@NonNull SqlFinishedStatement statement) { if (statement == null) { throw new NullPointerException("Statment is null!"); } this.statement = statement; } /** * Set the arguments used for the prepared statement * * @param args The strings used to replace "?" in the SELECT query statement * @return The QueryBuilder itself */ public QueryBuilder args(String... args) { this.args = args; return this; } /** * Registers this query for automatically updates through SQLBrite. SQLBrite offers a mechanism * to get notified on data changes on the queried database table (like insert, update or delete * rows) and automatically rerun this query. Per default this feature is enabled. * * @param autoUpdate true to enable, false to disable. * @return The QueryBuilder itself */ public QueryBuilder autoUpdates(boolean autoUpdate) { this.autoUpdate = autoUpdate; // Using raw statement, but no table to observe specified if (autoUpdate && statement == null && (rawStatementAffectedTables == null || !rawStatementAffectedTables.iterator().hasNext())) { throw new RuntimeException("You try to set autoUpdates(true) but, " + "your raw sql query statement has not specified which tables are affected by this query. Hence autoUpdates can not be enabled! Specify the affected tables as second parameter of rawQuery(String rawSQL, String ... affectedTables) method."); } return this; } /** * Executes the query and returns an {@code QueryObservable} * * @return {@code QueryObservable} * @see QueryObservable */ public QueryObservable run() { return executeQuery(this); } } protected BriteDatabase db; /** * Create here the database table for the given dao */ public abstract void createTable(SQLiteDatabase database); /** * This method will be called, if a Database has been updated and a database * table scheme may be needed * * @param db the database * @param oldVersion old database version * @param newVersion new database version */ public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion); /** * Set the {@link SQLiteOpenHelper}. This method will be called from the * {@link DaoManager} to inject the {@link SQLiteOpenHelper}. * <p> * You should not call this method directly. Let the {@link DaoManager} do * this, because it knows the right moment to invoke this method. * </p> * * @param db the database */ void setSqlBriteDb(BriteDatabase db) { this.db = db; } /** * Create a new Transaction. Don't forget to commit your changes by marking the transaction as * successful or rollback your changes. * * @return New transaction. */ public Transaction newTransaction() { return db.newTransaction(); } /** * Creates a query. * * @param statement the sql statement * @return QueryBuilder to proceed query building */ protected QueryBuilder query(@NonNull SqlFinishedStatement statement) { return new QueryBuilder(statement); } /** * Creates a raw query and enables auto updates for the given tables * * @param tables The affected table. updates get triggered if the observed tables changes. Use * {@code null} or * {@link #rawQuery(String)} if you don't want to register for automatic updates * @param sql The sql query statement * @return Observable of this query */ protected QueryBuilder rawQueryOnManyTables(@Nullable final Iterable<String> tables, @NonNull final String sql) { return new QueryBuilder(tables, sql); } /** * Creates a raw query and enables auto updates for the given single table * * @param table the affected table. updates get triggered if the observed tables changes. Use * {@code null} or * {@link #rawQuery(String)} if you don't want to register for automatic updates * @param sql The sql query statement */ protected QueryBuilder rawQuery(@Nullable final String table, @NonNull String sql) { return rawQueryOnManyTables(table == null ? null : Collections.singleton(table), sql); } /** * Creates a raw query. AutoUpdates are disabled since the name of the table to observe are not * specified. * * @param sql The raw SQL query statement. Arguments can still be specified with "?" as * placeholder */ protected QueryBuilder rawQuery(@NonNull String sql) { return rawQueryOnManyTables(null, sql); } /** * Executes the a query */ private QueryObservable executeQuery(QueryBuilder queryBuilder) { // Raw query properties as default String sql = queryBuilder.rawStatement; Iterable<String> affectedTables = queryBuilder.rawStatementAffectedTables; // If SqlFinishedStatement is set then use that one if (queryBuilder.statement != null) { SqlCompileable.CompileableStatement compileableStatement = queryBuilder.statement.asCompileableStatement(); sql = compileableStatement.sql; affectedTables = compileableStatement.tables; } // Check for auto update if (!queryBuilder.autoUpdate || affectedTables == null) { affectedTables = Collections.emptySet(); } return db.createQuery(affectedTables, sql, queryBuilder.args); } /** * Insert a row into the given table * * @param table the table name * @param contentValues The content values * @return An observable with the row Id of the new inserted row */ protected Observable<Long> insert(final String table, final ContentValues contentValues) { return Observable.defer(new Func0<Observable<Long>>() { @Override public Observable<Long> call() { return Observable.just(db.insert(table, contentValues)); } }); } /** * Insert a row into the given table * * @param table the table name * @param contentValues The content values * @param conflictAlgorithm The conflict algorithm * @return An observable with the row Id of the new inserted row */ protected Observable<Long> insert(final String table, final ContentValues contentValues, final int conflictAlgorithm) { return Observable.defer(new Func0<Observable<Long>>() { @Override public Observable<Long> call() { return Observable.just(db.insert(table, contentValues, conflictAlgorithm)); } }); } /** * Update rows * * @param table The table to update * @param values The values to update * @param whereClause The where clause * @param whereArgs The where clause arguments * @return An observable containing the number of rows that have been changed by this update */ protected Observable<Integer> update(@NonNull final String table, @NonNull final ContentValues values, @Nullable final String whereClause, @Nullable final String... whereArgs) { return Observable.defer(new Func0<Observable<Integer>>() { @Override public Observable<Integer> call() { return Observable.just(db.update(table, values, whereClause, whereArgs)); } }); } /** * Update rows * * @param table The table to update * @param values The values to update * @param conflictAlgorithm The conflict algorithm * @param whereClause The where clause * @param whereArgs The where clause arguments * @return An observable containing the number of rows that have been changed by this update */ protected Observable<Integer> update(@NonNull final String table, @NonNull final ContentValues values, final int conflictAlgorithm, @Nullable final String whereClause, @Nullable final String... whereArgs) { return Observable.defer(new Func0<Observable<Integer>>() { @Override public Observable<Integer> call() { return Observable.just(db.update(table, values, conflictAlgorithm, whereClause, whereArgs)); } }); } /** * Deletes all rows from a table * * @param table The table to delete * @return Observable with the number of deleted rows */ protected Observable<Integer> delete(@NonNull final String table) { return delete(table, null); } /** * Delete data from a table * * @param table The table name * @param whereClause the where clause * @param whereArgs the where clause arguments * @return Observable with the number of deleted rows */ protected Observable<Integer> delete(@NonNull final String table, @Nullable final String whereClause, @Nullable final String... whereArgs) { return Observable.defer(new Func0<Observable<Integer>>() { @Override public Observable<Integer> call() { return Observable.just(db.delete(table, whereClause, whereArgs)); } }); } /** * Start a SELECT query * * @param columns The columsn to select * @return {@link SELECT} */ protected SELECT SELECT(String... columns) { return new SELECT(columns); } /** * Creates a new SQL TABLE * * @param tableName The name of the table * @param columnDefs The column definitions */ protected CREATE_TABLE CREATE_TABLE(String tableName, String... columnDefs) { return new CREATE_TABLE(tableName, columnDefs); } /** * Drops a SQL Table */ protected DROP_TABLE DROP_TABLE(String tableName) { return new DROP_TABLE(tableName); } /** * Drop a SQL TABLE if the table exists */ protected DROP_TABLE_IF_EXISTS DROP_TABLE_IF_EXISTS(String tableName) { return new DROP_TABLE_IF_EXISTS(tableName); } /** * Execute a SQL <code>ALTER TABLE</code> command to change a table name or * definition */ protected ALTER_TABLE ALTER_TABLE(String tableName) { return new ALTER_TABLE(tableName); } /** * Create a SQL VIEW */ protected CREATE_VIEW CREATE_VIEW(String viewName) { return new CREATE_VIEW(viewName); } /** * Create a SQL VIEW IF NOT EXISTS */ protected CREATE_VIEW_IF_NOT_EXISTS CREATE_VIEW_IF_NOT_EXISTS(String viewName) { return new CREATE_VIEW_IF_NOT_EXISTS(viewName); } /** * Drop a sql View */ protected DROP_VIEW DROP_VIEW(String viewName) { return new DROP_VIEW(viewName); } /** * Drop a View if exists */ protected DROP_VIEW_IF_EXISTS DROP_VIEW_IF_EXISTS(String viewName) { return new DROP_VIEW_IF_EXISTS(viewName); } }
package net.fourbytes.shadow.map; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.LongMap; import com.badlogic.gdx.utils.ObjectMap.Entry; import net.fourbytes.shadow.Block; import net.fourbytes.shadow.Entity; import net.fourbytes.shadow.GameObject; import net.fourbytes.shadow.Layer; import net.fourbytes.shadow.Level; import net.fourbytes.shadow.Player; import net.fourbytes.shadow.TypeBlock; import net.fourbytes.shadow.blocks.BlockType; /** * An ShadowMap is an specially saved map. It mostly differs from the TilED maps by saving an "snapshot" of * the current state of the level into individual {@link Chunk}s instead of saving an "initial state" of * the level into one general map. */ public class ShadowMap { public LongMap<Chunk> chunks = new LongMap<Chunk>(); public ShadowMap() { } /** * Creates an fresh, "initial state" {@link GameObject}. * @param level Level to create the {@link GameObject} in. * @param x X position, * @param y Y position * @param ln Layer number * @param tid Tile ID (optional, use 0 by default) * @param type Type parameter ("block" or "entity") (optional) * @param subtype Subtype parameter ("Player" or "BlockDissolve.1") * @return {@link GameObject} "loaded" from map. */ public static GameObject convert(int x, int y, Layer layer, int tid, String type, String subtype) { GameObject obj = null; if (type == null || type.isEmpty()) { if (subtype.toLowerCase().startsWith("block")) { type = "block"; } else { type = "entity"; } } if ("block".equals(type)) { //System.out.println("tid: "+tid); Block block = BlockType.getInstance(subtype, x, y, layer); block.subtype = subtype; obj = block; } else if ("entity".equals(type)) { if ("Player".equals(subtype)) { Entity ent = new Player(new Vector2(x, y), layer); obj = ent; } } else { if (tid != 0) { throw new IllegalStateException("unknown type "+type+" for block id "+tid); } } return obj; } /** * Creates an {@link MapObject} out of an {@link GameObject} . * @param go {@link GameObject} to convert * @return {@link MapObject} that can be converted back * to create another {@link GameObject} <b> representing an SIMILAR (!)</b> {@link GameObject} to the original. */ public static MapObject convert(GameObject go) { MapObject mo = new MapObject(); if (go instanceof Block) { mo.type = "block"; } else if (go instanceof Entity) { mo.type = "entity"; } if (go instanceof Block) { mo.subtype = ((Block)go).subtype; } if (mo.subtype == null || mo.subtype.isEmpty()) { mo.subtype = go.getClass().getSimpleName(); } //TODO Decide whether convert fields or not return mo; } /** * Creates an {@link GameObject} out of an {@link MapObject} . * @param mo {@link MapObject} to convert * @param level Level to allocate the GameObject to. * @return {@link GameObject} representing an closest-possible, * thru-stream-sendable replica of the original {@link GameObject}. */ public static GameObject convert(MapObject mo, Level level) { Layer layer = null; if (level != null) { layer = level.layers.get(mo.layer); } int tid = 0; GameObject go = convert((int) mo.x, (int)mo.y, layer, tid, mo.type, mo.subtype); Object o = go; if (o instanceof TypeBlock) { o = ((TypeBlock)o).type; } for (Entry<String, Object> entry : mo.args.entries()) { try { o.getClass().getField(entry.key).set(o, entry.value); } catch (Exception e) { e.printStackTrace(); } } return go; } /** * Temporarily loads an ShadowMap into memory. Doesn't create an level. * @param file File to load map from. * @return ShadowMap containing {@link Chunk}s containing {@link MapObject}s NOT {@link GameObject}s. */ public static ShadowMap loadFile(FileHandle file) { ShadowMap map = null; //TODO Stub return map; } /** * Converts the temporarily loaded ShadowMap to an level. * @param level Level to fill. */ public void fillLevel(Level level) { //TODO Stub } /** * Creates an ShadowMap from an level to save afterwards. * @param level Level to get data from. * @return ShadowMap containing {@link Chunk}s containing {@link MapObject}s converted from * {@link GameObject}s of the level. */ public static ShadowMap createFrom(Level level) { ShadowMap map = null; //TODO Stub return map; } /** * Saves the ShadowMap to the file to load afterwards. * @param file File to save the ShadowMap to. */ public void save(FileHandle file) { //TODO Stub } }
package permafrost.tundra.lang; /** * A collection of convenience methods for working with booleans. */ public final class BooleanHelper { /** * Disallow instantiation of this class. */ private BooleanHelper() {} /** * Normalizes a boolean string to either "true" or "false", substituting the given default if the string is null. * * @param string The boolean string to normalize. * @param defaultValue The value to use if string is null. * @return The normalized boolean string. */ public static String normalize(String string, String defaultValue) { return normalize(string == null ? defaultValue : string); } /** * Normalizes a boolean string to either "true" or "false". * * @param string The boolean string to normalize. * @return The normalized boolean string. */ public static String normalize(String string) { return emit(parse(string)); } /** * Parses the given object to a boolean value. * * @param object An object which is either a Boolean or a String representation of a boolean. * @return The parsed boolean value. */ public static boolean parse(Object object) { if (object instanceof Boolean) { return (Boolean)object; } else { return parse(object == null ? (String)null : object.toString()); } } /** * Parses a string that can contain (ignoring case and leading and trailing whitespace) "true" or "1" to represent * true, or "false" or "0" to represent false. * * @param string The boolean string to be parsed. * @return The boolean value of the given string. */ public static boolean parse(String string) { return parse(string, false); } /** * Parses a string that can contain (ignoring case and leading and trailing whitespace) "true" or "1" to represent * true, or "false" or "0" to represent false. * * @param string The boolean string to be parsed. * @param defaultValue The boolean value returned if the given string is null. * @return The boolean value of the given string. */ public static boolean parse(String string, String defaultValue) { return parse(string, parse(defaultValue)); } /** * Parses a string that can contain (ignoring case and leading and trailing whitespace) "true" or "1" to represent * true, or "false" or "0" falseValue to represent false. * * @param string The boolean string to be parsed. * @param defaultValue The boolean value returned if the given string is null. * @return The boolean value of the given string. */ public static boolean parse(String string, boolean defaultValue) { return parse(string, null, null, defaultValue); } /** * Parses a string that can contain (ignoring case and leading and trailing whitespace) "true" or "1" or the given * trueValue to represent true, or "false" or "0" or the given falseValue to represent false. * * @param string The boolean string to be parsed. * @param trueValue The value used to determine if the string represents the boolean value true. * @param falseValue The value used to determine if the string represents the boolean value false. * @return The boolean value of the given string. */ public static boolean parse(String string, String trueValue, String falseValue) { return parse(string, trueValue, falseValue, false); } /** * Parses a string that can contain (ignoring case and leading and trailing whitespace) "true" or "1" or the given * trueValue to represent true, or "false" or "0" or the given falseValue to represent false. * * @param string The boolean string to be parsed. * @param trueValue The value used to determine if the string represents the boolean value true. * @param falseValue The value used to determine if the string represents the boolean value false. * @param defaultValue The boolean value returned if the given string is null. * @return The boolean value of the given string. */ public static boolean parse(String string, String trueValue, String falseValue, String defaultValue) { return parse(string, trueValue, falseValue, parse(defaultValue)); } /** * Parses a string that can contain (ignoring case and leading and trailing whitespace) "true" or "1" or the given * trueValue to represent true, or "false" or "0" or the given falseValue to represent false. * * @param string The boolean string to be parsed. * @param trueValue The value used to determine if the string represents the boolean value true. * @param falseValue The value used to determine if the string represents the boolean value false. * @param defaultValue The boolean value returned if the given string is null. * @return The boolean value of the given string. */ public static boolean parse(String string, String trueValue, String falseValue, boolean defaultValue) { if (string == null) return defaultValue; string = string.trim().toLowerCase(); boolean result; if (string.equals("1") || string.equals("true") || (trueValue != null && string.equalsIgnoreCase(trueValue))) { result = true; } else if (string.equals("0") || string.equals("false") || (falseValue != null && string.equalsIgnoreCase(falseValue))) { result = false; } else { throw new IllegalArgumentException("Unparseable boolean value: " + string); } return result; } /** * Returns a string representation of the given boolean value. * * @param bool The boolean to convert to a string. * @param trueValue The value returned if the given boolean is true. * @param falseValue The value returned if the given boolean is false. * @return The string representation of the given boolean. */ public static String emit(boolean bool, String trueValue, String falseValue) { return bool ? (trueValue == null ? Boolean.toString(bool) : trueValue) : (falseValue == null ? Boolean.toString(bool) : falseValue); } /** * Returns a boolean value in its canonical string form: "true" or "false". * * @param bool The boolean value to serialize to a string. * @return The canonical string representation of the given boolean value. */ public static String emit(boolean bool) { return emit(bool, null, null); } /** * Returns the negated boolean value of the given string. * * @param string The boolean string to be negated. * @param trueValue The value used to determine if the string represents the boolean value true. * @param falseValue The value used to determine if the string represents the boolean value false. * @return The given boolean string negated. */ public static String negate(String string, String trueValue, String falseValue) { return emit(negate(parse(string, trueValue, falseValue)), trueValue, falseValue); } /** * Returns the negated boolean value of the given string. * * @param string The boolean string to be negated. * @return The given boolean string negated. */ public static String negate(String string) { return negate(string, null, null); } /** * Returns the negated value of the given boolean. * * @param bool The boolean value to be negated. * @return The given boolean value negated. */ public static boolean negate(boolean bool) { return !bool; } /** * Formats the given boolean string using the given output boolean values. * * @param inString The string to be formatted. * @param inTrueValue The value used to determine if the string represents the boolean value true. * @param inFalseValue The value used to determine if the string represents the boolean value false. * @param outTrueValue The value returned if the given boolean is true. * @param outFalseValue The value returned if the given boolean is false. * @return The given string reformatted. */ public static String format(String inString, String inTrueValue, String inFalseValue, String outTrueValue, String outFalseValue) { return emit(parse(inString, inTrueValue, inFalseValue), outTrueValue, outFalseValue); } }
package tem.dataflow; import java.io.IOException; import java.io.InputStream; import org.junit.Test; import com.google.common.io.ByteSource; public final class StreamingWorkflow { @Test public void flowsTwice() throws IOException { ByteSource first = new CreateAndPrint(); ByteSource printed = new Prints(first); printed.copyTo(System.out); printed.copyTo(System.out); } private final class CreateAndPrint extends ByteSource { @Override public InputStream openStream() throws IOException { InputStream stream = Res.stream(); System.out.println("\nNew InputStream created."); return stream; } } private static final class Prints extends ByteSource { private final ByteSource from; public Prints(ByteSource from) { this.from = from; } @Override public InputStream openStream() throws IOException { InputStream input = from.openStream(); System.out.println("Second operation executed."); return input; } } }
package pl.pronux.sokker.utils.file; import java.io.File; import java.io.IOException; import java.util.GregorianCalendar; import pl.pronux.sokker.model.DatabaseSettings; import pl.pronux.sokker.model.SokkerViewerSettings; public class Database { public static boolean backup(SokkerViewerSettings settings, String filename) throws IOException { DatabaseSettings databaseSettings = settings.getDatabaseSettings(); if (databaseSettings.getType().equals(DatabaseSettings.HSQLDB)) { File dbDir = new File(settings.getBackupDirectory()); if (!dbDir.exists()) { if (!OperationOnFile.createDirectory(dbDir)) { throw new IOException("Missing backup directory"); //$NON-NLS-1$ } } if (new File(dbDir, settings.getUsername()).exists()) { dbDir = new File(dbDir, settings.getUsername()); } else { dbDir = new File(dbDir, settings.getUsername()); dbDir.mkdir(); } File dbFile = new File(settings.getBaseDirectory() + File.separator + "db" + File.separator + "db_file_" + settings.getUsername() + ".script"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (dbFile.exists()) { File dbBakFile = new File(dbDir, filename); OperationOnFile.copyFile(dbFile, dbBakFile); } return true; } return false; } public static boolean backup(SokkerViewerSettings settings) throws IOException { return backup(settings, new GregorianCalendar().getTimeInMillis() + ".bak"); //$NON-NLS-1$ } public static void restore(SokkerViewerSettings settings, String filename) throws IOException { DatabaseSettings databaseSettings = settings.getDatabaseSettings(); if (databaseSettings.getType().equals(DatabaseSettings.HSQLDB)) { File dbDir = new File(settings.getBackupDirectory() + File.separator + settings.getUsername() + File.separator); File dbFile = new File(settings.getBaseDirectory() + File.separator + "db" + File.separator + "db_file_" + settings.getUsername() + ".script"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ File dbBakFile = new File(dbDir, filename); OperationOnFile.copyFile(dbBakFile, dbFile); } } }
package refinedstorage.item; import cofh.api.energy.ItemEnergyContainer; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.IItemPropertyGetter; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.translation.I18n; import net.minecraft.world.World; import refinedstorage.RefinedStorage; import refinedstorage.RefinedStorageBlocks; import refinedstorage.tile.TileController; import refinedstorage.tile.grid.TileGrid; import java.util.List; public class ItemWirelessGrid extends ItemEnergyContainer { public static final String NBT_CONTROLLER_X = "ControllerX"; public static final String NBT_CONTROLLER_Y = "ControllerY"; public static final String NBT_CONTROLLER_Z = "ControllerZ"; public static final String NBT_SORTING_TYPE = "SortingType"; public static final String NBT_SORTING_DIRECTION = "SortingDirection"; public static final String NBT_SEARCH_BOX_MODE = "SearchBoxMode"; public static final int RANGE = 64; public static final int USAGE_OPEN = 30; public static final int USAGE_PULL = 3; public static final int USAGE_PUSH = 3; public ItemWirelessGrid() { super(3200); addPropertyOverride(new ResourceLocation("connected"), new IItemPropertyGetter() { @Override public float apply(ItemStack stack, World world, EntityLivingBase entity) { return canOpenWirelessGrid(world, entity, stack) ? 1.0f : 0.0f; } }); setMaxDamage(3200); setMaxStackSize(1); setHasSubtypes(false); setCreativeTab(RefinedStorage.TAB); } @Override public boolean isDamageable() { return true; } @Override public boolean isRepairable() { return false; } @Override public double getDurabilityForDisplay(ItemStack stack) { return 1d - ((double) getEnergyStored(stack) / (double) getMaxEnergyStored(stack)); } @Override public boolean isDamaged(ItemStack stack) { return true; } @Override public void setDamage(ItemStack stack, int damage) { // NO OP } @Override public void getSubItems(Item item, CreativeTabs tab, List list) { list.add(new ItemStack(item)); ItemStack fullyCharged = new ItemStack(item); receiveEnergy(fullyCharged, getMaxEnergyStored(fullyCharged), false); list.add(fullyCharged); } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean b) { list.add(I18n.translateToLocalFormatted("misc.refinedstorage:energy_stored", getEnergyStored(stack), getMaxEnergyStored(stack))); if (canOpenWirelessGrid(player.worldObj, player, stack)) { list.add(I18n.translateToLocalFormatted("misc.refinedstorage:wireless_grid.tooltip.0", getX(stack))); list.add(I18n.translateToLocalFormatted("misc.refinedstorage:wireless_grid.tooltip.1", getY(stack))); list.add(I18n.translateToLocalFormatted("misc.refinedstorage:wireless_grid.tooltip.2", getZ(stack))); } } @Override public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { Block block = worldIn.getBlockState(pos).getBlock(); if (block == RefinedStorageBlocks.CONTROLLER) { NBTTagCompound tag = stack.getTagCompound(); if (tag == null) { tag = new NBTTagCompound(); } tag.setInteger(NBT_CONTROLLER_X, pos.getX()); tag.setInteger(NBT_CONTROLLER_Y, pos.getY()); tag.setInteger(NBT_CONTROLLER_Z, pos.getZ()); tag.setInteger(NBT_SORTING_DIRECTION, TileGrid.SORTING_DIRECTION_DESCENDING); tag.setInteger(NBT_SORTING_TYPE, TileGrid.SORTING_TYPE_NAME); tag.setInteger(NBT_SEARCH_BOX_MODE, TileGrid.SEARCH_BOX_MODE_NORMAL); stack.setTagCompound(tag); return EnumActionResult.SUCCESS; } return EnumActionResult.PASS; } @Override public ActionResult<ItemStack> onItemRightClick(ItemStack stack, World world, EntityPlayer player, EnumHand hand) { if (!world.isRemote && canOpenWirelessGrid(world, player, stack)) { TileController tile = (TileController) world.getTileEntity(new BlockPos(getX(stack), getY(stack), getZ(stack))); tile.onOpenWirelessGrid(player, hand); return new ActionResult(EnumActionResult.SUCCESS, stack); } return new ActionResult(EnumActionResult.PASS, stack); } public static int getX(ItemStack stack) { return stack.getTagCompound().getInteger(NBT_CONTROLLER_X); } public static int getY(ItemStack stack) { return stack.getTagCompound().getInteger(NBT_CONTROLLER_Y); } public static int getZ(ItemStack stack) { return stack.getTagCompound().getInteger(NBT_CONTROLLER_Z); } public static int getSortingType(ItemStack stack) { return stack.getTagCompound().getInteger(NBT_SORTING_TYPE); } public static int getSortingDirection(ItemStack stack) { return stack.getTagCompound().getInteger(NBT_SORTING_DIRECTION); } public static int getSearchBoxMode(ItemStack stack) { return stack.getTagCompound().getInteger(NBT_SEARCH_BOX_MODE); } public static boolean isInRange(ItemStack stack, EntityLivingBase entity) { return (int) Math.sqrt(Math.pow(getX(stack) - entity.posX, 2) + Math.pow(getY(stack) - entity.posY, 2) + Math.pow(getZ(stack) - entity.posZ, 2)) < RANGE; } public static boolean canOpenWirelessGrid(World world, EntityLivingBase entity, ItemStack stack) { if (entity != null && stack.hasTagCompound() && stack.getTagCompound().hasKey(NBT_CONTROLLER_X) && stack.getTagCompound().hasKey(NBT_CONTROLLER_Y) && stack.getTagCompound().hasKey(NBT_CONTROLLER_Z) && stack.getTagCompound().hasKey(NBT_SORTING_DIRECTION) && stack.getTagCompound().hasKey(NBT_SORTING_TYPE) && stack.getTagCompound().hasKey(NBT_SEARCH_BOX_MODE)) { if (world == null) { world = entity.worldObj; } int x = getX(stack); int y = getY(stack); int z = getZ(stack); return isInRange(stack, entity) && world.getTileEntity(new BlockPos(x, y, z)) instanceof TileController; } return false; } @Override public String getUnlocalizedName() { return "item." + RefinedStorage.ID + ":wireless_grid"; } @Override public String getUnlocalizedName(ItemStack stack) { return getUnlocalizedName(); } }
package rs.bojanb89.datamodel.to; public class ExceptionTO { public int code; public String error; public ExceptionTO() { } public ExceptionTO(int code, String error) { super(); this.code = code; this.error = error; } }
package ru.r2cloud.jradio.blocks; import java.io.IOException; import ru.r2cloud.jradio.Context; import ru.r2cloud.jradio.FloatInput; import ru.r2cloud.jradio.util.CircularComplexArray; import ru.r2cloud.jradio.util.MathUtils; public class FLLBandEdge implements FloatInput { private final FloatInput source; private ComplexFIRFilter filterUpper; private ComplexFIRFilter filterLower; private ControlLoop controlLoop; private final CircularComplexArray array; private boolean outputReal = true; private final float[] currentComplex = new float[2]; private final float[] currentUpperComplex = new float[2]; private final float[] currentLowerComplex = new float[2]; public FLLBandEdge(FloatInput source, float samplesPerSymbol, float rolloff, int filterSize, float bandwidth) { if (source.getContext().getChannels() != 2) { throw new IllegalArgumentException("not a complex input: " + source.getContext().getChannels()); } if (samplesPerSymbol <= 0) { throw new IllegalArgumentException("invalid samples per symbol. Must be positive: " + samplesPerSymbol); } if (rolloff < 0 || rolloff > 1.0) { throw new IllegalArgumentException("invalid rolloff factor. Must be in [0,1]: " + samplesPerSymbol); } if (filterSize <= 0) { throw new IllegalArgumentException("invalid filter size. Must be positive: " + filterSize); } this.source = source; this.array = new CircularComplexArray(filterSize); this.controlLoop = new ControlLoop(bandwidth, (float) ((2 * Math.PI) * (2.0 / samplesPerSymbol)), (float) (-(2 * Math.PI) * (2.0 / samplesPerSymbol))); designFilter(samplesPerSymbol, rolloff, filterSize); } @Override public float readFloat() throws IOException { if (outputReal) { float sourceReal = source.readFloat(); float sourceImg = source.readFloat(); double phaseImg = Math.sin(controlLoop.getPhase()); float phaseReal = (float) MathUtils.fastCos(controlLoop.getPhase(), phaseImg); MathUtils.multiply(currentComplex, sourceReal, sourceImg, phaseReal, (float) phaseImg); array.add(currentComplex[0], currentComplex[1]); // Perform the dot product of the output with the filters filterLower.filterComplex(currentUpperComplex, array); filterUpper.filterComplex(currentLowerComplex, array); float error = MathUtils.norm(currentLowerComplex) - MathUtils.norm(currentUpperComplex); controlLoop.advanceLoop(error); outputReal = !outputReal; return currentComplex[0]; } outputReal = !outputReal; return currentComplex[1]; } private void designFilter(float samplesPerSymbol, float rolloff, int filterSize) { int m = (int) Math.rint(filterSize / samplesPerSymbol); float power = 0; // Create the baseband filter by adding two sincs together float[] basebandTaps = new float[filterSize]; for (int i = 0; i < basebandTaps.length; i++) { float k = -m + i * 2.0f / samplesPerSymbol; float tap = MathUtils.sinc(rolloff * k - 0.5f) + MathUtils.sinc(rolloff * k + 0.5f); power += tap; basebandTaps[i] = tap; } if (power == 0.0f) { throw new IllegalArgumentException("invalid power: " + power); } float[] tapsLowerReal = new float[filterSize]; float[] tapsLowerImg = new float[filterSize]; float[] tapsUpperReal = new float[filterSize]; float[] tapsUpperImg = new float[filterSize]; // Create the band edge filters by spinning the baseband // filter up and down to the right places in frequency. // Also, normalize the power in the filters float[] tempComplex = new float[2]; int n = (int) ((basebandTaps.length - 1.0) / 2.0); for (int i = 0; i < filterSize; i++) { float tap = basebandTaps[i] / power; float k = (-n + i) / (2.0f * samplesPerSymbol); MathUtils.expj(tempComplex, -(2 * (float) Math.PI) * (1 + rolloff) * k); MathUtils.multiply(tap, tempComplex); tapsLowerReal[filterSize - i - 1] = tempComplex[0]; tapsLowerImg[filterSize - i - 1] = tempComplex[1]; MathUtils.expj(tempComplex, (2 * (float) Math.PI) * (1 + rolloff) * k); MathUtils.multiply(tap, tempComplex); tapsUpperReal[filterSize - i - 1] = tempComplex[0]; tapsUpperImg[filterSize - i - 1] = tempComplex[1]; } filterUpper = new ComplexFIRFilter(tapsUpperReal, tapsUpperImg); filterLower = new ComplexFIRFilter(tapsLowerReal, tapsLowerImg); } @Override public void close() throws IOException { source.close(); } @Override public Context getContext() { return source.getContext(); } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.demo.ui; import playn.core.Font; import playn.core.PlayN; import react.Function; import tripleplay.ui.Background; import tripleplay.ui.Constraints; import tripleplay.ui.Group; import tripleplay.ui.Icons; import tripleplay.ui.Label; import tripleplay.ui.Shim; import tripleplay.ui.Slider; import tripleplay.ui.Style; import tripleplay.ui.ValueLabel; import tripleplay.ui.layout.AxisLayout; import tripleplay.demo.DemoScreen; public class SliderDemo extends DemoScreen { @Override protected String name () { return "Sliders"; } @Override protected String title () { return "UI: Sliders"; } @Override protected Group createIface () { Group iface = new Group(AxisLayout.vertical().gap(10)).add( new Shim(15, 15), new Label("Click and drag the slider to change the value:"), sliderAndLabel(new Slider(0, -100, 100), "-000"), new Shim(15, 15), new Label("This one counts by 2s:"), sliderAndLabel(new Slider(0, -50, 50).setIncrement(2), "-00"), new Shim(15, 15), new Label("With a background, custom bar and thumb image:"), sliderAndLabel( new Slider(0, -50, 50).addStyles( Style.BACKGROUND.is(Background.roundRect(0xFFFFFFFF, 16).inset(4)), Slider.THUMB_IMAGE.is(Icons.loader( PlayN.assets().getImage("images/smiley.png"), 24, 24)), Slider.BAR_HEIGHT.is(18f), Slider.BAR_BACKGROUND.is(Background.roundRect(0xFFFF0000, 9))), "-00")); return iface; } protected Group sliderAndLabel (Slider slider, String minText) { ValueLabel label = new ValueLabel(slider.value.map(FORMATTER)). setStyles(Style.HALIGN.right, Style.FONT.is(FIXED)). setConstraint(Constraints.minSize(minText)); return new Group(AxisLayout.horizontal()).add(slider, label); } protected Function<Float,String> FORMATTER = new Function<Float,String>() { public String apply (Float value) { return String.valueOf(value.intValue()); } }; protected static Font FIXED = PlayN.graphics().createFont("Fixed", Font.Style.PLAIN, 16); }
package seedu.task.model.util; import java.io.IOException; import seedu.task.commons.exceptions.DataConversionException; import seedu.task.model.ReadOnlyTaskManager; import seedu.task.model.task.Task; import seedu.task.storage.XmlTaskManagerStorage; //@@author A0139938L public class SampleDataUtil { private static final String SAMPLE_DATA_FILE_PATH = "./src/test/data/sandbox/sampleData.xml"; public static Task[] getSampleTasks() throws DataConversionException, IOException { ReadOnlyTaskManager sampleTaskManager = getSampleTaskManager(); Task[] tasks = sampleTaskManager.getTaskArray(); return tasks; } public static ReadOnlyTaskManager getSampleTaskManager() throws DataConversionException, IOException { // TODO: Make this read from resource XmlTaskManagerStorage sampleStorage = new XmlTaskManagerStorage(SAMPLE_DATA_FILE_PATH); ReadOnlyTaskManager taskManager = sampleStorage.getReadOnlyTaskManager(SAMPLE_DATA_FILE_PATH); return taskManager; } } //@@author
package yuku.alkitab.base.dialog; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.text.SpannableStringBuilder; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.StyleSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.afollestad.materialdialogs.MaterialDialog; import yuku.afw.D; import yuku.afw.V; import yuku.alkitab.base.S; import yuku.alkitab.base.dialog.base.BaseDialog; import yuku.alkitab.base.util.Appearances; import yuku.alkitab.base.util.TargetDecoder; import yuku.alkitab.base.widget.VerseRenderer; import yuku.alkitab.base.widget.VersesView; import yuku.alkitab.base.widget.VersesView.VerseSelectionMode; import yuku.alkitab.debug.R; import yuku.alkitab.model.SingleChapterVerses; import yuku.alkitab.model.Version; import yuku.alkitab.model.XrefEntry; import yuku.alkitab.util.Ari; import yuku.alkitab.util.IntArrayList; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class XrefDialog extends BaseDialog { public static final String TAG = XrefDialog.class.getSimpleName(); private static final String EXTRA_arif = "arif"; public interface XrefDialogListener { void onVerseSelected(XrefDialog dialog, int arif_source, int ari_target); } TextView tXrefText; VersesView versesView; XrefDialogListener listener; int arif_source; XrefEntry xrefEntry; int displayedLinkPos = -1; // -1 indicates that we should auto-select the first link List<String> displayedVerseTexts; List<String> displayedVerseNumberTexts; IntArrayList displayedRealAris; Version sourceVersion = S.activeVersion; String sourceVersionId = S.activeVersionId; float textSizeMult = S.getDb().getPerVersionSettings(sourceVersionId).fontSizeMultiplier; public XrefDialog() { } public static XrefDialog newInstance(int arif) { XrefDialog res = new XrefDialog(); Bundle args = new Bundle(); args.putInt(EXTRA_arif, arif); res.setArguments(args); return res; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (getParentFragment() instanceof XrefDialogListener) { listener = (XrefDialogListener) getParentFragment(); } else { listener = (XrefDialogListener) activity; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NO_TITLE, 0); arif_source = getArguments().getInt(EXTRA_arif); xrefEntry = sourceVersion.getXrefEntry(arif_source); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View res = inflater.inflate(R.layout.dialog_xref, container, false); tXrefText = V.get(res, R.id.tXrefText); versesView = V.get(res, R.id.versesView); res.setBackgroundColor(S.applied.backgroundColor); versesView.setCacheColorHint(S.applied.backgroundColor); versesView.setVerseSelectionMode(VerseSelectionMode.singleClick); versesView.setSelectedVersesListener(versesView_selectedVerses); tXrefText.setMovementMethod(LinkMovementMethod.getInstance()); if (xrefEntry != null) { renderXrefText(); } else { new MaterialDialog.Builder(getActivity()) .content(String.format(Locale.US, "Error: xref at arif 0x%08x couldn't be loaded", arif_source)) .positiveText(R.string.ok) .show(); } return res; } @Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (xrefEntry == null) { dismiss(); } } void renderXrefText() { final SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(VerseRenderer.XREF_MARK); sb.append(" "); final int[] linkPos = {0}; findTags(xrefEntry.content, new FindTagsListener() { @Override public void onTaggedText(final String tag, int start, int end) { final int thisLinkPos = linkPos[0]; linkPos[0]++; int sb_len = sb.length(); sb.append(xrefEntry.content, start, end); if (tag.startsWith("t")) { // the only supported tag at the moment final String encodedTarget = tag.substring(1); if (thisLinkPos == displayedLinkPos || (displayedLinkPos == -1 && thisLinkPos == 0)) { // just make it bold, because this is the currently displayed link sb.setSpan(new StyleSpan(Typeface.BOLD), sb_len, sb.length(), 0); if (displayedLinkPos == -1) { showVerses(0, encodedTarget); } } else { sb.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { showVerses(thisLinkPos, encodedTarget); } }, sb_len, sb.length(), 0); } } } @Override public void onPlainText(int start, int end) { sb.append(xrefEntry.content, start, end); } }); Appearances.applyTextAppearance(tXrefText, textSizeMult); tXrefText.setText(sb); } void showVerses(int linkPos, String encodedTarget) { displayedLinkPos = linkPos; final IntArrayList ranges = decodeTarget(encodedTarget); if (D.EBUG) { Log.d(TAG, "linkPos " + linkPos + " target=" + encodedTarget + " ranges=" + ranges); } displayedVerseTexts = new ArrayList<>(); displayedVerseNumberTexts = new ArrayList<>(); displayedRealAris = new IntArrayList(); int verse_count = sourceVersion.loadVersesByAriRanges(ranges, displayedRealAris, displayedVerseTexts); if (verse_count > 0) { // set up verse number texts for (int i = 0; i < verse_count; i++) { int ari = displayedRealAris.get(i); displayedVerseNumberTexts.add(Ari.toChapter(ari) + ":" + Ari.toVerse(ari)); } class Verses extends SingleChapterVerses { @Override public String getVerse(int verse_0) { final String res = displayedVerseTexts.get(verse_0); // prevent crash if the target xref is not available if (res == null) { return getString(R.string.generic_verse_not_available_in_this_version); } return res; } @Override public int getVerseCount() { return displayedVerseTexts.size(); } @Override public String getVerseNumberText(int verse_0) { return displayedVerseNumberTexts.get(verse_0); } } int firstAri = displayedRealAris.get(0); versesView.setData(Ari.toBookChapter(firstAri), new Verses(), null, null, 0, sourceVersion, sourceVersionId); } renderXrefText(); } private IntArrayList decodeTarget(final String encodedTarget) { return TargetDecoder.decode(encodedTarget); } VersesView.SelectedVersesListener versesView_selectedVerses = new VersesView.DefaultSelectedVersesListener() { @Override public void onVerseSingleClick(VersesView v, int verse_1) { listener.onVerseSelected(XrefDialog.this, arif_source, displayedRealAris.get(verse_1 - 1)); } }; interface FindTagsListener { void onPlainText(int start, int end); void onTaggedText(String tag, int start, int end); } // look for "<@" "@>" "@/" tags void findTags(String s, FindTagsListener listener) { int pos = 0; while (true) { int p = s.indexOf("@<", pos); if (p == -1) break; listener.onPlainText(pos, p); int q = s.indexOf("@>", p+2); if (q == -1) break; int r = s.indexOf("@/", q+2); if (r == -1) break; listener.onTaggedText(s.substring(p+2, q), q+2, r); pos = r+2; } listener.onPlainText(pos, s.length()); } public void setSourceVersion(Version sourceVersion, String sourceVersionId) { this.sourceVersion = sourceVersion; this.sourceVersionId = sourceVersionId; textSizeMult = S.getDb().getPerVersionSettings(sourceVersionId).fontSizeMultiplier; } }
package io.asfjava.ui.demo.screen; import java.io.Serializable; import io.asfjava.ui.core.form.CheckBox; import io.asfjava.ui.core.form.ComboBox; import io.asfjava.ui.core.form.Number; import io.asfjava.ui.core.form.Password; import io.asfjava.ui.core.form.RadioBox; import io.asfjava.ui.core.form.Tab; import io.asfjava.ui.core.form.TextArea; import io.asfjava.ui.core.form.TextField; public class DemoForm implements Serializable { @TextField(title = "Pesonal Website",fieldAddonLeft="http://", description = "This is TextField with fieldAddonLeft") private String webSite; @TextField(title = "Your Github Mail",fieldAddonRight="@github.com", description = "This is TextField with fieldAddonRight") private String gitHub; // @Tab(title = "Contact", index = 2) @Password(title = "Password", placeHolder = "Please set you password",description = "This is password") private String password; @Tab(title = "Info", index = 1) @TextField(title = "First Name", placeHolder = "Your first name",minLenght=3,maxLenght=10, validationMessage = "The First Name must contain a minimum of 3 and a max of 10 characters ", description = "This is a description for your first name field with minLenght and maxLenght") private String firstName; // @Tab(title = "Info", index = 1) @TextField(title = "Last Name", placeHolder = "Your last name") private String lastName; @Tab(title = "Contact", index = 2) @TextField(title = "eMail", placeHolder = "Your email", pattern = "^\\S+@\\S+$", validationMessage = "Your mail must be in this format jhondoe@example.com", description = "This is Text Field with pattern and validation message") private String email; @Tab(title = "Additional Info", index = 3) @Number(title = "Number of children", placeHolder = "Number of children", description = "This is a number") private Integer number; @Tab(title = "Info", index = 1) @ComboBox(title = "Gender", titleMap = GenderTitleMap.class) private String gender; // @Tab(title = "Additional Info", index = 3) @ComboBox(title = "Currency", values = { "euro", "dollar" }) private String currency; @Tab(title = "Additional Info", index = 3) @RadioBox(title = "Civil State", titleMap = CivilStateTitelsMap.class) private String civilState; // @Tab(title = "Contact", index = 2) @TextArea(title = "Address", placeHolder = "Fill your address please", description = "This is textarea") private String address; @Tab(title = "Additional Info", index = 3) @CheckBox(title = "Color", values = { "red", "bleu", "green" }, defaultvalue = "red") private String color; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setEmail(String eMail) { this.email = eMail; } public String getEmail() { return email; } public void setGitHub(String github) { this.gitHub = github; } public String getGitHub() { return gitHub; } public void setWebSite(String website) { this.webSite = website; } public String getWebSite() { return webSite; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getGender() { return gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCivilState() { return civilState; } public void setCivilState(String civilState) { this.civilState = civilState; } public String getCurrency() { return currency; } public String getColor() { return color; } private static final long serialVersionUID = -5073515619469444978L; }
package seedu.taskell.logic.commands; import seedu.taskell.commons.core.EventsCenter; import seedu.taskell.commons.core.Messages; import seedu.taskell.commons.events.ui.IncorrectCommandAttemptedEvent; import seedu.taskell.commons.events.ui.JumpToListRequestEvent; import seedu.taskell.model.History; import seedu.taskell.model.HistoryManager; import seedu.taskell.model.Model; /** * Represents a command with hidden internal logic and the ability to be executed. */ public abstract class Command { protected Model model; protected static History history; /** * Constructs a feedback message to summarise an operation that displayed a listing of tasks. * * @param displaySize used to generate summary * @return summary message for tasks displayed */ public static String getMessageForTaskListShownSummary(int displaySize) { return String.format(Messages.MESSAGE_TASKS_LISTED_OVERVIEW, displaySize); } /** * Executes the command and returns the result message. * * @return feedback message of the operation result for display */ public abstract CommandResult execute(); /** * Provides any needed dependencies to the command. * Commands making use of any of these should override this method to gain * access to the dependencies. */ public void setData(Model model) { this.model = model; } /** * initialize History */ public static void initHistory() { history = HistoryManager.getInstance(); } /** * Raises an event to indicate an attempt to execute an incorrect command */ protected void indicateAttemptToExecuteIncorrectCommand() { EventsCenter.getInstance().post(new IncorrectCommandAttemptedEvent(this)); } //@@author A0139257X-reused /** * Raises an event to jump to the given index */ protected void jumpToIndex(int index) { EventsCenter.getInstance().post(new JumpToListRequestEvent(index)); } //@@author }
package scala; import scala.runtime.RunTime; /** * Run-time types for Scala. * * @author Michel Schinz * @version 1.0 */ abstract public class Type { public static final Type[] EMPTY_ARRAY = new Type[]{}; /** @meta method [?T](scala.Int) scala.Array[?T]; */ abstract public Array newArray(int size); /** Return the default value for the type (_ in Scala) */ abstract public Object defaultValue(); /** * Return true iff the given object is an instance of a subtype of * this type (implement Scala's isInstanceOf operation). */ abstract public boolean hasAsInstance(Object o); /** * Check that the given object can be cast to this type, and throw * an exception if this is not possible (implement Scala's * asInstanceOf operation). */ public Object checkCastability(Object o) { if (! (o == null || hasAsInstance(o))) throw new ClassCastException(); // TODO provide a message return o; } // Basic types public static final TypeDouble Double = new TypeDouble(); public static final TypeFloat Float = new TypeFloat(); public static final TypeLong Long = new TypeLong(); public static final TypeInt Int = new TypeInt(); public static final TypeShort Short = new TypeShort(); public static final TypeChar Char = new TypeChar(); public static final TypeByte Byte = new TypeByte(); public static final TypeBoolean Boolean = new TypeBoolean(); } public class ConstructedType extends Type { private Object outer; private Class typeConstr; private Type[] args; public ConstructedType(Object outer, String typeConstrName) { this(outer, typeConstrName, Type.EMPTY_ARRAY); } public ConstructedType(Object outer, String typeConstrName, Type arg1) { this(outer, typeConstrName, new Type[]{ arg1 }); } public ConstructedType(Object outer, String typeConstrName, Type arg1, Type arg2) { this(outer, typeConstrName, new Type[]{ arg1, arg2 }); } public ConstructedType(Object outer, String typeConstrName, Type arg1, Type arg2, Type arg3) { this(outer, typeConstrName, new Type[]{ arg1, arg2, arg3 }); } public ConstructedType(Object outer, String typeConstrName, Type arg1, Type arg2, Type arg3, Type arg4) { this(outer, typeConstrName, new Type[]{ arg1, arg2, arg3, arg4 }); } public ConstructedType(Object outer, String typeConstrName, Type[] args) { try { this.outer = outer; this.typeConstr = Class.forName(typeConstrName, false, getClass().getClassLoader()); this.args = args; } catch (ClassNotFoundException e) { throw new Error(e); } } public Array newArray(int size) { // TODO is that correct if we have type arguments? Object[] array = (Object[])java.lang.reflect.Array.newInstance(typeConstr, size); return RunTime.box_oarray(array); } public Object defaultValue() { return null; } public boolean hasAsInstance(Object o) { return typeConstr.isInstance(o); // TODO complete } } public class SingleType extends Type { private final Object instance; public SingleType(Object instance) { this.instance = instance; } public Array newArray(int size) { throw new Error(); // TODO } public Object defaultValue() { throw new Error(); // TODO } public boolean hasAsInstance(Object o) { return (o == instance); } } // The following classes may not be defined in class Type because // inner classes confuse pico which then attributes the metadata to // the wrong members. class TypeDouble extends Type { private final Double ZERO = RunTime.box_dvalue(0.0); public Array newArray(int size) { return RunTime.box_darray(new double[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeFloat extends Type { private final Float ZERO = RunTime.box_fvalue(0.0f); public Array newArray(int size) { return RunTime.box_farray(new float[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeLong extends Type { private final Long ZERO = RunTime.box_lvalue(0l); public Array newArray(int size) { return RunTime.box_larray(new long[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeInt extends Type { private final Int ZERO = RunTime.box_ivalue(0); public Array newArray(int size) { return RunTime.box_iarray(new int[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeShort extends Type { private final Short ZERO = RunTime.box_svalue((short)0); public Array newArray(int size) { return RunTime.box_sarray(new short[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeChar extends Type { private final Char ZERO = RunTime.box_cvalue((char)0); public Array newArray(int size) { return RunTime.box_carray(new char[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeByte extends Type { private final Byte ZERO = RunTime.box_bvalue((byte)0); public Array newArray(int size) { return RunTime.box_barray(new byte[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } }; class TypeBoolean extends Type { private final Boolean ZERO = RunTime.box_zvalue(false); public Array newArray(int size) { return RunTime.box_zarray(new boolean[size]); } public Object defaultValue() { return ZERO; } public boolean hasAsInstance(Object o) { throw new UnsupportedOperationException(); } };
package edu.wustl.catissuecore.applet.util; import java.awt.Component; import javax.swing.JApplet; import netscape.javascript.JSObject; /** * <p> This util class is used to specify common applet level operations. * Here all applet related util methods should reside.</p> * @author Ashwin Gupta * @version 1.1 */ public final class CommonAppletUtil { /** * gets the base applet from a given component * @param component component * @return applet */ public static JApplet getBaseApplet(Component component) { while (component != null) { if (component instanceof JApplet) { return ((JApplet) component); } component = component.getParent(); } return null; } /** * This method calls given javascript function. * * @param component * @param functionName * @param parameters */ public static void callJavaScriptFunction(Component component, String functionName, Object[] parameters) { JApplet applet = getBaseApplet(component); if (applet != null) { JSObject jsObject = JSObject.getWindow(applet); jsObject.call(functionName, parameters); } } /** * Checks that the input String contains only numeric digits. * @param numString The string whose characters are to be checked. * @return Returns false if the String contains any alphabet else returns true. * */ public static boolean isNumeric(String numString) { try { long longValue = Long.parseLong(numString); if (longValue <= 0) { return false; } return true; } catch(NumberFormatException exp) { return false; } } }
package org.nick.wwwjdic.history; import java.util.ArrayList; import java.util.List; import android.support.v4.app.ActionBar; import android.support.v4.app.ActionBar.Tab; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; public class TabsPagerAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener { private final ActionBar actionBar; private final ViewPager viewPager; private final List<HistoryFragmentBase> tabs = new ArrayList<HistoryFragmentBase>(); public TabsPagerAdapter(FragmentActivity activity, ActionBar actionBar, ViewPager pager) { super(activity.getSupportFragmentManager()); this.actionBar = actionBar; this.viewPager = pager; this.viewPager.setAdapter(this); this.viewPager.setOnPageChangeListener(this); } public void addTab(ActionBar.Tab tab, HistoryFragmentBase tabFragment) { tabFragment.setHasOptionsMenu(true); tabs.add(tabFragment); actionBar.addTab(tab.setTabListener(this)); notifyDataSetChanged(); } @Override public int getCount() { return tabs.size(); } @Override public Fragment getItem(int position) { return tabs.get(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); // TODO -- refreshing kills action bar? // refresh(position); } @SuppressWarnings("unused") private void refresh(int position) { HistoryFragmentBase fragment = (HistoryFragmentBase) getItem(position); fragment.refresh(); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { int position = tab.getPosition(); viewPager.setCurrentItem(position); // TODO -- refreshing kills action bar? // refresh(position); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { } }
package seedu.taskmanager.ui; import java.util.Date; import java.util.logging.Logger; import org.controlsfx.control.StatusBar; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXML; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import seedu.taskmanager.commons.core.LogsCenter; import seedu.taskmanager.commons.events.model.TaskManagerChangedEvent; import seedu.taskmanager.commons.events.storage.TaskManagerStorageDirectoryChangedEvent; import seedu.taskmanager.commons.util.FxViewUtil; /** * A ui for the status bar that is displayed at the footer of the application. */ public class StatusBarFooter extends UiPart<Region> { private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class); @FXML private StatusBar syncStatus; @FXML private StatusBar saveLocationStatus; private static final String FXML = "StatusBarFooter.fxml"; public StatusBarFooter(AnchorPane placeHolder, String saveLocation) { super(FXML); addToPlaceholder(placeHolder); setSyncStatus("Not updated yet in this session"); setSaveLocation(saveLocation); registerAsAnEventHandler(this); } private void addToPlaceholder(AnchorPane placeHolder) { FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0); placeHolder.getChildren().add(getRoot()); } private void setSaveLocation(String location) { this.saveLocationStatus.setText(location); } private void setSyncStatus(String status) { this.syncStatus.setText(status); } @Subscribe public void handleTaskManagerChangedEvent(TaskManagerChangedEvent abce) { String lastUpdated = (new Date()).toString(); logger.info(LogsCenter.getEventHandlingLogMessage(abce, "Setting last updated status to " + lastUpdated)); setSyncStatus("Last Updated: " + lastUpdated); } @Subscribe public void handleTaskManagerStorageDirectoryChangedEvent(TaskManagerStorageDirectoryChangedEvent abce) { logger.info(LogsCenter.getEventHandlingLogMessage(abce)); setSaveLocation(abce.getNewFilePath()); } }
package edu.wustl.query.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.querysuite.queryobject.IQuery; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.query.actionForm.CategorySearchForm; import edu.wustl.query.util.global.Constants; import edu.wustl.query.util.global.Variables; import edu.wustl.query.util.querysuite.DefinedQueryUtil; import edu.wustl.query.util.querysuite.QueryModuleSearchQueryUtil; import edu.wustl.query.util.querysuite.QueryModuleUtil; /** * * @author deepti_shelar * */ public class OpenDecisionMakingPageAction extends Action { /** * This method loads define results jsp. * @param mapping mapping * @param form form * @param request request * @param response response * @throws Exception Exception * @return ActionForward actionForward */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CategorySearchForm actionForm = (CategorySearchForm) form; HttpSession session = request.getSession(); String pageOf = (String)request.getParameter(Constants.PAGE_OF); request.setAttribute(Constants.PAGE_OF, pageOf); IQuery query = (IQuery) session.getAttribute(Constants.QUERY_OBJECT); SessionDataBean sessionDataBean = (SessionDataBean) session.getAttribute(Constants.SESSION_DATA); String noOfResults = (String) session .getAttribute(Constants.TREE_NODE_LIMIT_EXCEEDED_RECORDS); String option = actionForm.getOptions(); String forward=Constants.SUCCESS; QueryModuleSearchQueryUtil QMSearchQuery = new QueryModuleSearchQueryUtil(request, query); //inserts Defined Query DefinedQueryUtil definedQueryUtil=new DefinedQueryUtil(); ParameterizedQuery parameterizedQuery=(ParameterizedQuery)query; parameterizedQuery.setName(actionForm.getQueryTitle()); definedQueryUtil.insertQuery(parameterizedQuery,sessionDataBean,false); if (option == null) { ActionErrors errors = new ActionErrors(); ActionError addMsg = new ActionError("query.decision.making.message", noOfResults, Variables.maximumTreeNodeLimit); errors.add(ActionErrors.GLOBAL_ERROR, addMsg); saveErrors(request, errors); } else { final boolean isRulePresentInDag = QueryModuleUtil.checkIfRulePresentInDag(query); if (isRulePresentInDag) { QMSearchQuery.searchQuery(option); } forward=Constants.VIEW_ALL_RECORDS; } return mapping.findForward(forward); } }
package skadistats.clarity.decoder; public class BitStream { private final long[] masks = { 0x0L, 0x1L, 0x3L, 0x7L, 0xfL, 0x1fL, 0x3fL, 0x7fL, 0xffL, 0x1ffL, 0x3ffL, 0x7ffL, 0xfffL, 0x1fffL, 0x3fffL, 0x7fffL, 0xffffL, 0x1ffffL, 0x3ffffL, 0x7ffffL, 0xfffffL, 0x1fffffL, 0x3fffffL, 0x7fffffL, 0xffffffL, 0x1ffffffL, 0x3ffffffL, 0x7ffffffL, 0xfffffffL, 0x1fffffffL, 0x3fffffffL, 0x7fffffffL, 0xffffffffL, 0x1ffffffffL, 0x3ffffffffL, 0x7ffffffffL, 0xfffffffffL, 0x1fffffffffL, 0x3fffffffffL, 0x7fffffffffL, 0xffffffffffL, 0x1ffffffffffL, 0x3ffffffffffL, 0x7ffffffffffL, 0xfffffffffffL, 0x1fffffffffffL, 0x3fffffffffffL, 0x7fffffffffffL, 0xffffffffffffL, 0x1ffffffffffffL, 0x3ffffffffffffL, 0x7ffffffffffffL, 0xfffffffffffffL, 0x1fffffffffffffL, 0x3fffffffffffffL, 0x7fffffffffffffL }; final long[] data; int pos; public BitStream(byte[] bytes) { data = new long[(bytes.length + 7) / 8]; pos = 0; long akku = 0; for (int i = 0; i < bytes.length; i++) { int shift = 8 * (i & 7); long val = ((long) bytes[i]) & 0xFF; akku = akku | (val << shift); if ((i & 7) == 7) { data[i / 8] = akku; akku = 0; } } if ((bytes.length & 7) != 0) { data[bytes.length / 8] = akku; } } public int readNumericBits(int n) { int start = pos >> 6; int end = (pos + n - 1) >> 6; int s = pos & 63; long ret; if (start == end) { ret = (data[start] >>> s) & masks[n]; } else { // wrap around ret = ((data[start] >>> s) | (data[end] << (64 - s))) & masks[n]; } pos += n; return (int) ret; } public boolean readBit() { return readNumericBits(1) == 1; } public byte[] readBits(int num) { byte[] result = new byte[(num + 7) / 8]; int i = 0; while (num > 7) { num -= 8; result[i] = (byte) readNumericBits(8); i++; } if (num != 0) { result[i] = (byte) readNumericBits(num); } return result; } public String readString(int num) { StringBuffer buf = new StringBuffer(); while (num > 0) { char c = (char) readNumericBits(8); if (c == 0) { break; } buf.append(c); num } return buf.toString(); } public int readVarInt() { int run = 0; int value = 0; while (true) { int bits = readNumericBits(8); value = value | ((bits & 0x7f) << run); run += 7; if ((bits >> 7) == 0 || run == 35) { break; } } return value; } public String toString() { StringBuffer buf = new StringBuffer(); int min = Math.max(0, (pos - 32) / 64); int max = Math.min(data.length - 1, (pos + 63) / 64); for (int i = min; i <= max; i++) { buf.append(new StringBuffer(String.format("%64s", Long.toBinaryString(data[i])).replace(' ', '0')).reverse()); } buf.insert(pos - min * 32, '*'); return buf.toString(); } }
package nl.mpi.kinnate.ui.menu; import java.io.File; import java.util.HashMap; import javax.swing.filechooser.FileFilter; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.export.ExportToR; import nl.mpi.kinnate.transcoder.DiagramTranscoder; import nl.mpi.kinnate.ui.DiagramTranscoderPanel; import nl.mpi.kinnate.ui.ImportSamplesFileMenu; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.window.AbstractDiagramManager; public class FileMenu extends javax.swing.JMenu { private javax.swing.JMenuItem importGedcomUrl; private javax.swing.JMenuItem importGedcomFile; // private javax.swing.JMenuItem importCsvFile; private javax.swing.JMenuItem closeTabMenuItem; private javax.swing.JMenuItem entityUploadMenuItem; private javax.swing.JMenuItem exitApplication; private javax.swing.JMenuItem exportToR; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JPopupMenu.Separator jSeparator2; private javax.swing.JPopupMenu.Separator jSeparator3; private javax.swing.JPopupMenu.Separator jSeparator4; private javax.swing.JPopupMenu.Separator jSeparator5; private javax.swing.JMenuItem newDiagramMenuItem; private javax.swing.JMenuItem openDiagram; private RecentFileMenu recentFileMenu; private javax.swing.JMenuItem saveAsDefaultMenuItem; private javax.swing.JMenuItem saveDiagram; private javax.swing.JMenuItem saveDiagramAs; private javax.swing.JMenuItem savePdfMenuItem; private AbstractDiagramManager diagramWindowManager; private SessionStorage sessionStorage; private MessageDialogHandler dialogHandler; //ArbilWindowManager public FileMenu(AbstractDiagramManager diagramWindowManager, SessionStorage sessionStorage, MessageDialogHandler dialogHandler) { this.diagramWindowManager = diagramWindowManager; this.sessionStorage = sessionStorage; this.dialogHandler = dialogHandler; this.diagramWindowManager = diagramWindowManager; importGedcomUrl = new javax.swing.JMenuItem(); importGedcomFile = new javax.swing.JMenuItem(); // importCsvFile = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); newDiagramMenuItem = new javax.swing.JMenuItem(); jMenu3 = new DocumentNewMenu(diagramWindowManager); openDiagram = new javax.swing.JMenuItem(); recentFileMenu = new RecentFileMenu(diagramWindowManager, sessionStorage); jMenu1 = new SamplesFileMenu(diagramWindowManager, dialogHandler); jMenu2 = new ImportSamplesFileMenu(diagramWindowManager); jSeparator2 = new javax.swing.JPopupMenu.Separator(); entityUploadMenuItem = new javax.swing.JMenuItem(); jSeparator4 = new javax.swing.JPopupMenu.Separator(); saveDiagram = new javax.swing.JMenuItem(); saveDiagramAs = new javax.swing.JMenuItem(); savePdfMenuItem = new javax.swing.JMenuItem(); exportToR = new javax.swing.JMenuItem(); closeTabMenuItem = new javax.swing.JMenuItem(); jSeparator3 = new javax.swing.JPopupMenu.Separator(); saveAsDefaultMenuItem = new javax.swing.JMenuItem(); jSeparator5 = new javax.swing.JPopupMenu.Separator(); exitApplication = new javax.swing.JMenuItem(); // todo: Ticket #1297 add an import gedcom and csv menu item this.setText("File"); this.addMenuListener(new javax.swing.event.MenuListener() { public void menuSelected(javax.swing.event.MenuEvent evt) { fileMenuMenuSelected(evt); } public void menuDeselected(javax.swing.event.MenuEvent evt) { } public void menuCanceled(javax.swing.event.MenuEvent evt) { } }); this.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileMenuActionPerformed(evt); } }); newDiagramMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); newDiagramMenuItem.setText("New (default diagram)"); newDiagramMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newDiagramMenuItemActionPerformed(evt); } }); this.add(newDiagramMenuItem); jMenu3.setText("New Diagram of Type"); this.add(jMenu3); openDiagram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); openDiagram.setText("Open Diagram"); openDiagram.setActionCommand("open"); openDiagram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { openDiagramActionPerformed(evt); } }); this.add(openDiagram); this.add(recentFileMenu); jMenu1.setText("Open Sample Diagram"); this.add(jMenu1); this.add(jSeparator1); importGedcomFile.setText("Import Gedcom / CSV File"); importGedcomFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importGedcomFileActionPerformed(evt); } }); this.add(importGedcomFile); // importCsvFile.setText("Import CSV File"); // importCsvFile.addActionListener(new java.awt.event.ActionListener() { // public void actionPerformed(java.awt.event.ActionEvent evt) { // importCsvFileActionPerformed(evt); // this.add(importCsvFile); jMenu2.setText("Import Sample Data"); this.add(jMenu2); importGedcomUrl.setText("Import Gedcom Samples (from internet)"); importGedcomUrl.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importGedcomUrlActionPerformed(evt); } }); importGedcomUrl.setEnabled(false); this.add(importGedcomUrl); this.add(jSeparator2); entityUploadMenuItem.setText("Entity Upload"); entityUploadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { entityUploadMenuItemActionPerformed(evt); } }); this.add(entityUploadMenuItem); this.add(jSeparator4); saveDiagram.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); saveDiagram.setText("Save"); saveDiagram.setActionCommand("save"); saveDiagram.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveDiagramActionPerformed(evt); } }); this.add(saveDiagram); saveDiagramAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); saveDiagramAs.setText("Save As"); saveDiagramAs.setActionCommand("saveas"); saveDiagramAs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveDiagramAsActionPerformed(evt); } }); this.add(saveDiagramAs); savePdfMenuItem.setText("Export as PDF/JPEG"); savePdfMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { savePdfMenuItemActionPerformed(evt); } }); this.add(savePdfMenuItem); exportToR.setText("Export for R / SPSS"); exportToR.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportToRActionPerformed(evt); } }); this.add(exportToR); closeTabMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK)); closeTabMenuItem.setText("Close"); closeTabMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeTabMenuItemActionPerformed(evt); } }); this.add(closeTabMenuItem); this.add(jSeparator3); saveAsDefaultMenuItem.setText("Save as Default Diagram"); saveAsDefaultMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveAsDefaultMenuItemActionPerformed(evt); } }); this.add(saveAsDefaultMenuItem); this.add(jSeparator5); exitApplication.setText("Exit"); exitApplication.setActionCommand("exit"); exitApplication.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitApplicationActionPerformed(evt); } }); this.add(exitApplication); } private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) { } private HashMap<String, FileFilter> getSvgFileFilter() { HashMap<String, FileFilter> fileFilterMap = new HashMap<String, FileFilter>(2); for (final String[] currentType : new String[][]{{"Kinship Diagram (SVG format)", ".svg"}}) { // "Scalable Vector Graphics (SVG)"; fileFilterMap.put(currentType[0], new FileFilter() { @Override public boolean accept(File selectedFile) { final String extensionLowerCase = currentType[1].toLowerCase(); return (selectedFile.exists() && (selectedFile.isDirectory() || selectedFile.getName().toLowerCase().endsWith(extensionLowerCase))); } @Override public String getDescription() { return currentType[0]; } }); } return fileFilterMap; } private void openDiagramActionPerformed(java.awt.event.ActionEvent evt) { final File[] selectedFilesArray = dialogHandler.showFileSelectBox("Open Diagram", false, true, getSvgFileFilter(), MessageDialogHandler.DialogueType.open, null); if (selectedFilesArray != null) { for (File selectedFile : selectedFilesArray) { diagramWindowManager.openDiagram(selectedFile.getName(), selectedFile.toURI(), true); } } } private void saveDiagramActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(); } private void saveDiagramAsActionPerformed(java.awt.event.ActionEvent evt) { final File[] selectedFilesArray = dialogHandler.showFileSelectBox("Save Diagram As", false, false, getSvgFileFilter(), MessageDialogHandler.DialogueType.save, null); if (selectedFilesArray != null) { for (File selectedFile : selectedFilesArray) { if (!selectedFile.getName().toLowerCase().endsWith(".svg")) { selectedFile = new File(selectedFile.getParentFile(), selectedFile.getName() + ".svg"); } int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(selectedFile); RecentFileMenu.addRecentFile(sessionStorage, selectedFile); diagramWindowManager.setDiagramTitle(tabIndex, selectedFile.getName()); } } } private void exitApplicationActionPerformed(java.awt.event.ActionEvent evt) { // check that things are saved and ask user if not if (diagramWindowManager.offerUserToSaveAll()) { System.exit(0); } } private void fileMenuMenuSelected(javax.swing.event.MenuEvent evt) { // set the save, save as and close text to include the tab to which the action will occur int selectedIndex = diagramWindowManager.getSavePanelIndex(); SavePanel savePanel = null; if (selectedIndex > -1) { String currentTabText = diagramWindowManager.getSavePanelTitle(selectedIndex); savePanel = diagramWindowManager.getSavePanel(selectedIndex); saveDiagramAs.setText("Save As (" + currentTabText + ")"); saveDiagramAs.setActionCommand(Integer.toString(selectedIndex)); saveDiagram.setText("Save (" + currentTabText + ")"); saveDiagram.setActionCommand(Integer.toString(selectedIndex)); closeTabMenuItem.setText("Close (" + currentTabText + ")"); closeTabMenuItem.setActionCommand(Integer.toString(selectedIndex)); saveAsDefaultMenuItem.setText("Set Default Diagram as (" + currentTabText + ")"); saveAsDefaultMenuItem.setActionCommand(Integer.toString(selectedIndex)); } if (savePanel != null) { saveDiagram.setEnabled(savePanel.hasSaveFileName() && savePanel.requiresSave()); saveDiagramAs.setEnabled(true); exportToR.setEnabled(true); closeTabMenuItem.setEnabled(true); saveAsDefaultMenuItem.setEnabled(true); savePdfMenuItem.setEnabled(true); } else { saveDiagramAs.setEnabled(false); saveDiagram.setEnabled(false); exportToR.setEnabled(false); closeTabMenuItem.setEnabled(false); saveAsDefaultMenuItem.setEnabled(false); savePdfMenuItem.setEnabled(false); } } private void closeTabMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); String diagramTitle = diagramWindowManager.getSavePanelTitle(tabIndex); boolean userCanceled = diagramWindowManager.offerUserToSave(savePanel, diagramTitle); if (!userCanceled) { diagramWindowManager.closeSavePanel(tabIndex); } } private void newDiagramMenuItemActionPerformed(java.awt.event.ActionEvent evt) { diagramWindowManager.newDiagram(); } private void importGedcomFileActionPerformed(java.awt.event.ActionEvent evt) { HashMap<String, FileFilter> fileFilterMap = new HashMap<String, FileFilter>(2); fileFilterMap.put("importfiles", new FileFilter() { @Override public boolean accept(File selectedFile) { if (selectedFile.isDirectory()) { return true; } final String currentFileName = selectedFile.getName().toLowerCase(); if (currentFileName.endsWith(".gedcom")) { return true; } if (currentFileName.endsWith(".txt")) { return true; } if (currentFileName.endsWith(".csv")) { return true; } return false; } @Override public String getDescription() { return "GEDCOM or CSV Kinship Data"; } }); File[] importFiles = dialogHandler.showFileSelectBox("Import Kinship Data", false, true, fileFilterMap, MessageDialogHandler.DialogueType.open, null); if (importFiles != null) { if (importFiles.length == 0) { dialogHandler.addMessageDialogToQueue("No files selected for import", "Import Kinship Data"); } else { for (File importFile : importFiles) { diagramWindowManager.openImportPanel(importFile); } } } } private void importCsvFileActionPerformed(java.awt.event.ActionEvent evt) { importGedcomFileActionPerformed(evt); } private void importGedcomUrlActionPerformed(java.awt.event.ActionEvent evt) { // todo: Ticket #1297 either remove this or change it so it does not open so many tabs / windows String[] importList = new String[]{"http://gedcomlibrary.com/gedcoms.html", "http://GedcomLibrary.com/gedcoms/gl120365.ged", // Tammy Carter Inman "http://GedcomLibrary.com/gedcoms/gl120366.ged", // Luis Lemonnier "http://GedcomLibrary.com/gedcoms/gl120367.ged", // Cheryl Marion Follansbee // New England Genealogical Detective "http://GedcomLibrary.com/gedcoms/gl120368.ged", // Phil Willaims "http://GedcomLibrary.com/gedcoms/gl120369.ged", // Francisco Castaeda "http://GedcomLibrary.com/gedcoms/gl120370.ged", // Kim Carter "http://GedcomLibrary.com/gedcoms/gl120371.ged", // Maria Perusia "http://GedcomLibrary.com/gedcoms/gl120372.ged", // R. J. Bosman "http://GedcomLibrary.com/gedcoms/liverpool.ged", // William Robinette "http://GedcomLibrary.com/gedcoms/misc2a.ged", // William Robinette "http://GedcomLibrary.com/gedcoms/myline.ged", // William Robinette "http://gedcomlibrary.com/gedcoms/gl120368.ged", // "http://GedcomLibrary.com/gedcoms/gl120367.ged", // "http://GedcomLibrary.com/gedcoms/liverpool.ged", // "http://GedcomLibrary.com/gedcoms/misc2a.ged", // "http://GedcomLibrary.com/gedcoms/gl120372.ged"}; for (String importUrlString : importList) { diagramWindowManager.openImportPanel(importUrlString); } } private void savePdfMenuItemActionPerformed(java.awt.event.ActionEvent evt) { final DiagramTranscoder diagramTranscoder = new DiagramTranscoder(diagramWindowManager.getCurrentSavePanel()); DiagramTranscoderPanel diagramTranscoderPanel = new DiagramTranscoderPanel(diagramTranscoder); final File[] selectedFilesArray = dialogHandler.showFileSelectBox("Export as PDF/JPEG", false, false, null, MessageDialogHandler.DialogueType.save, diagramTranscoderPanel); if (selectedFilesArray != null) { for (File selectedFile : selectedFilesArray) { diagramTranscoder.exportDiagram(selectedFile); } } } private void exportToRActionPerformed(java.awt.event.ActionEvent evt) { SavePanel currentSavePanel = diagramWindowManager.getCurrentSavePanel(); HashMap<String, FileFilter> fileFilterMap = new HashMap<String, FileFilter>(2); for (final String[] currentType : new String[][]{{"Data Frame Tab-separated Values", ".tab"}}) { // "Data Frame (CSV)" fileFilterMap.put(currentType[0], new FileFilter() { @Override public boolean accept(File selectedFile) { final String extensionLowerCase = currentType[1].toLowerCase(); return (selectedFile.exists() && (selectedFile.isDirectory() || selectedFile.getName().toLowerCase().endsWith(extensionLowerCase))); } @Override public String getDescription() { return currentType[0]; } }); } final File[] selectedFilesArray = dialogHandler.showFileSelectBox("Export Tab-separated Values", false, false, fileFilterMap, MessageDialogHandler.DialogueType.save, null); if (selectedFilesArray != null) { for (File selectedFile : selectedFilesArray) { if (!selectedFile.getName().toLowerCase().endsWith(".tab")) { selectedFile = new File(selectedFile.getParentFile(), selectedFile.getName() + ".tab"); } new ExportToR(sessionStorage, dialogHandler).doExport(this, currentSavePanel, selectedFile); } } } private void entityUploadMenuItemActionPerformed(java.awt.event.ActionEvent evt) { diagramWindowManager.openEntityUploadPanel(); } private void saveAsDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex = Integer.valueOf(evt.getActionCommand()); SavePanel savePanel = diagramWindowManager.getSavePanel(tabIndex); savePanel.saveToFile(KinDiagramPanel.getDefaultDiagramFile(sessionStorage)); } }
package storm.benchmark.benchmarks; import backtype.storm.Config; import backtype.storm.generated.StormTopology; import backtype.storm.spout.MultiScheme; import backtype.storm.tuple.Fields; import com.google.common.collect.Sets; import org.apache.hadoop.hbase.client.Durability; import org.apache.storm.hbase.trident.mapper.SimpleTridentHBaseMapper; import org.apache.storm.hbase.trident.state.HBaseState; import org.apache.storm.hbase.trident.state.HBaseStateFactory; import org.apache.storm.hbase.trident.state.HBaseUpdater; import storm.benchmark.benchmarks.common.StormBenchmark; import storm.benchmark.lib.spout.RandomMessageSpout; import storm.benchmark.metrics.BasicMetricsCollector; import storm.benchmark.metrics.IMetricsCollector; import storm.benchmark.util.BenchmarkUtils; import storm.kafka.BrokerHosts; import storm.kafka.ZkHosts; import storm.kafka.trident.OpaqueTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.Stream; import storm.trident.TridentTopology; import storm.trident.state.StateFactory; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class TSolHBase extends StormBenchmark { public static final String TOPOLOGY_LEVEL = "topology.level"; public static final String SPOUT_ID = "spout"; public static final String SPOUT_NUM = "component.spout_num"; public static final String BOLT_ID = "bolt"; public static final String BOLT_NUM = "component.bolt_num"; public static final String BATCH_SIZE = "batch.size"; public static final String SHUFFLE = "topology.shuffle"; public static final int DEFAULT_SHUFFLE = 1; // 0 = disabled; other = enabled public static final int DEFAULT_SPOUT_NUM = 4; public static final int DEFAULT_BOLT_NUM = 4; public static final int DEFAULT_BATCH_SIZE = 100; private static final String FIELD1_NAME = "id"; private static final String FIELD2_NAME = "bytes"; @Override public StormTopology getTopology(Config config) { final int spoutNum = BenchmarkUtils.getInt(config, SPOUT_NUM, DEFAULT_SPOUT_NUM); int boltNum = BenchmarkUtils.getInt(config, BOLT_NUM, DEFAULT_BOLT_NUM); final int batchSize = BenchmarkUtils.getInt(config, BATCH_SIZE, DEFAULT_BATCH_SIZE); final int shuffle = BenchmarkUtils.getInt(config, SHUFFLE, DEFAULT_SHUFFLE); String zkHost = BenchmarkUtils.getStr(config, "zookeeper.host"); String zkConnString = zkHost + ":2181"; //String zkConnString = "cn069.l42scl.hortonworks.com:2181"; String topicName = BenchmarkUtils.getStr(config, "kafka.topic"); // String topicName = "parts_4_100b"; String hbase_table = BenchmarkUtils.getStr(config, "hbase_table.name"); String hbase_table_column = BenchmarkUtils.getStr(config, "hbase_table_column.name"); String namenode_host = BenchmarkUtils.getStr(config, "hdfs_namenode.host"); String zookeeper_znode_parent = BenchmarkUtils.getStr(config, "zookeeper.znode.parent"); BrokerHosts zk = new ZkHosts(zkConnString); TridentKafkaConfig spoutConf = new TridentKafkaConfig(zk, topicName); spoutConf.scheme = new SimpleSchemehb(); spoutConf.ignoreZkOffsets = true; spoutConf.fetchSizeBytes = batchSize; OpaqueTridentKafkaSpout kspout = new OpaqueTridentKafkaSpout(spoutConf); SimpleTridentHBaseMapper hbaseMapper = new SimpleTridentHBaseMapper() .withColumnFamily(hbase_table_column) .withRowKeyField(FIELD1_NAME) .withColumnFields(new Fields(FIELD2_NAME)) ; String hbase_root_dir_value = "hdfs://" + namenode_host + ":8020/apps/hbase/data"; Map<String, Object> hbConf = new HashMap<String, Object>(); hbConf.put("hbase.rootdir", hbase_root_dir_value); hbConf.put("hbase.zookeeper.property.clientPort", "2181"); hbConf.put("hbase.zookeeper.quorum",zkHost); hbConf.put("zookeeper.znode.parent", zookeeper_znode_parent); hbConf.put("hbase.zookeeper.useMulti","true"); config.put("hbase.conf", hbConf); String hbaseTable = hbase_table; HBaseState.Options options = new HBaseState.Options() .withConfigKey("hbase.conf") .withDurability(Durability.SYNC_WAL) .withMapper(hbaseMapper) .withTableName("stormperf"); StateFactory factory = new HBaseStateFactory(options); TridentTopology trident = new TridentTopology(); Stream strm = trident.newStream("spout", kspout).parallelismHint(spoutNum); if(shuffle!=0) { strm.shuffle(); } else { boltNum = spoutNum; //override if not shuffling } strm.partitionPersist(factory, new Fields(FIELD1_NAME, FIELD2_NAME), new HBaseUpdater(), new Fields()) .parallelismHint(boltNum); return trident.build(); } @Override public IMetricsCollector getMetricsCollector(Config config, StormTopology topology) { return new BasicMetricsCollector(config, topology, Sets.newHashSet(IMetricsCollector.MetricsItem.ALL)); } } class SimpleSchemehb implements MultiScheme { public Iterable<List<Object>> deserialize(byte[] bytes) { ArrayList<List<Object>> res = new ArrayList(1); res.add(tuple(UUID.randomUUID().toString(), deserializeString(bytes)) ); return res; } public static String deserializeString(byte[] string) { try { return new String(string, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public Fields getOutputFields() { return new Fields("id", "bytes"); } public static ArrayList<Object> tuple(Object... values) { ArrayList<Object> arr = new ArrayList<Object>(values.length); for (Object value : values) { arr.add(value); } return arr; } }
package org.zanata.action; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceException; import org.apache.deltaspike.jpa.api.transaction.Transactional; import org.hibernate.exception.ConstraintViolationException; import javax.inject.Inject; import org.apache.deltaspike.core.api.exclude.Exclude; import org.apache.deltaspike.core.api.projectstage.ProjectStage; import javax.inject.Named; import org.zanata.dao.AccountActivationKeyDAO; import org.zanata.dao.AccountDAO; import org.zanata.dao.PersonDAO; import org.zanata.i18n.Messages; import org.zanata.model.HAccount; import org.zanata.model.HAccountActivationKey; import org.zanata.model.HPerson; import org.zanata.seam.security.IdentityManager; import org.zanata.service.EmailService; import org.zanata.service.UserAccountService; import org.zanata.ui.AbstractListFilter; import lombok.Getter; import org.zanata.ui.faces.FacesMessages; import org.zanata.util.ServiceLocator; import static javax.faces.application.FacesMessage.SEVERITY_ERROR; /** * Extension of Seam management's UserAction class' behaviour. * * @see {@link org.jboss.seam.security.management.action.UserAction} * @author Carlos Munoz <a * href="mailto:camunoz@redhat.com">camunoz@redhat.com</a> */ @Named("userAction") @javax.faces.bean.ViewScoped public class UserAction implements Serializable { private static final long serialVersionUID = 1L; @Inject private IdentityManager identityManager; @Inject private EntityManager entityManager; @Inject private FacesMessages facesMessages; @Inject private Messages msgs; @Inject private UserAccountService userAccountServiceImpl; @Inject private EmailService emailServiceImpl; @Inject private PersonDAO personDAO; @Inject private AccountDAO accountDAO; @Inject private AccountActivationKeyDAO accountActivationKeyDAO; private String originalUsername; @Getter private AbstractListFilter<String> userFilter = new AbstractListFilter<String>() { AccountDAO accountDAO = ServiceLocator.instance().getInstance(AccountDAO.class); @Override protected List<String> fetchRecords(int start, int max, String filter) { return accountDAO.getUserNames(filter, start, max); } @Override protected long fetchTotalRecords(String filter) { return accountDAO.getUserCount(filter); } }; private List<String> roles; private String username; private String password; private String confirm; private boolean enabled; @Transactional public void deleteUser(String userName) { try { identityManager.deleteUser(userName); // NB: Need to call flush here to be able to catch the persistence // exception, otherwise it would be caught by Seam. entityManager.flush(); userFilter.reset(); } catch (PersistenceException e) { if (e.getCause() instanceof ConstraintViolationException) { facesMessages .addFromResourceBundle(SEVERITY_ERROR, "jsf.UserManager.delete.constraintViolation.error"); } } } public String getEmail(String username) { return personDAO.findEmail(username); } public String getName(String username) { return personDAO.findByUsername(username).getName(); } public void loadUser() { roles = identityManager.getGrantedRoles(username); enabled = identityManager.isUserEnabled(username); originalUsername = username; } @Transactional public String save() { boolean usernameChanged = false; String newUsername = getUsername(); // Allow user name changes when editing if (!originalUsername.equals(newUsername)) { if (isNewUsernameValid(newUsername)) { userAccountServiceImpl.editUsername(originalUsername, newUsername); usernameChanged = true; } else { facesMessages.addToControl("username", msgs.format("jsf.UsernameNotAvailable", getUsername())); setUsername(originalUsername); // reset the username field return "failure"; } } String saveResult; saveResult = saveExistingUser(); if (usernameChanged) { String email = getEmail(newUsername); String message = emailServiceImpl.sendUsernameChangedEmail( email, newUsername); facesMessages.addGlobal(message); } return saveResult; } private String saveExistingUser() { // Check if a new password has been entered if (password != null && !"".equals(password)) { if (!password.equals(confirm)) { facesMessages.addToControl("password", "Passwords do not match"); return "failure"; } else { identityManager.changePassword(username, password); } } List<String> grantedRoles = identityManager.getGrantedRoles(username); if (grantedRoles != null) { for (String role : grantedRoles) { if (!roles.contains(role)) identityManager.revokeRole(username, role); } } for (String role : roles) { if (grantedRoles == null || !grantedRoles.contains(role)) { identityManager.grantRole(username, role); } } if (enabled) { enableAccount(username); } else { identityManager.disableUser(username); } return "success"; } private void enableAccount(String username) { identityManager.enableUser(username); identityManager.grantRole(username, "user"); HAccount account = accountDAO.getByUsername(username); HAccountActivationKey key = account.getAccountActivationKey(); if(key != null) { account.setAccountActivationKey(null); accountDAO.makePersistent(account); accountActivationKeyDAO.makeTransient(key); } } /** * Validate that a user name is not already in the system, by another * account */ private boolean isNewUsernameValid(String username) { try { entityManager .createQuery("from HAccount a where a.username = :username") .setParameter("username", username).getSingleResult(); return false; } catch (NoResultException e) { // pass return true; } } public String cancel() { return "success"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } }
package nl.mpi.kinnate.ui.menu; import java.awt.Component; import java.awt.Rectangle; import java.io.IOException; import java.net.URI; import java.util.ResourceBundle; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import nl.mpi.arbil.ArbilVersion; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.ApplicationVersion; import nl.mpi.arbil.util.ApplicationVersionManager; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.arbil.util.BugCatcherManager; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.entityindexer.EntityServiceException; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.KinOathHelp; import nl.mpi.kinnate.ui.window.AbstractDiagramManager; import org.xml.sax.SAXException; public class HelpMenu extends JMenu { private static final ResourceBundle menus = ResourceBundle.getBundle("nl/mpi/kinoath/localisation/Menus"); JFrame helpWindow = null; public HelpMenu(final AbstractDiagramManager diagramWindowManager, final ArbilWindowManager dialogHandler, final SessionStorage sessionStorage, final ApplicationVersionManager versionManager, final Component parentComponent) { this.setText(menus.getString("HELP")); JMenuItem aboutMenuItem = new JMenuItem(menus.getString("ABOUT")); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // todo: move this into the window manager ApplicationVersion appVersion = versionManager.getApplicationVersion(); String messageString = menus.getString("KINOATH IS AN APPLICATION FOR KINSHIP AND ARCHIVING.") + java.text.MessageFormat.format(menus.getString("KINOATH VERSION: {0}.{1}.{2}"), new Object[]{appVersion.currentMajor, appVersion.currentMinor, appVersion.currentRevision}) + appVersion.lastCommitDate + java.text.MessageFormat.format(menus.getString("" + "COMPILE DATE: {0}"), new Object[]{appVersion.compileDate}) + java.text.MessageFormat.format(menus.getString("ARBIL VERSION: {0}.{1}.{2}"), new Object[]{new ArbilVersion().currentMajor, new ArbilVersion().currentMinor, new ArbilVersion().currentRevision}) + java.text.MessageFormat.format(menus.getString("JAVA VERSION: {0} BY {1}"), new Object[]{System.getProperty("java.version"), System.getProperty("java.vendor")}); dialogHandler.addMessageDialogToQueue(messageString, java.text.MessageFormat.format(menus.getString("ABOUT_BOX_TITLE {0}"), new Object[]{versionManager.getApplicationVersion().applicationTitle})); } }); this.add(aboutMenuItem); JMenuItem helpMenuItem = new JMenuItem(menus.getString("INTERNAL HELP")); helpMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0)); helpMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { if (helpWindow == null) { helpWindow = diagramWindowManager.createHelpWindow(menus.getString("INTERNAL HELP"), new KinOathHelp(), new Rectangle(600, 400)); } else { helpWindow.setVisible(true); helpWindow.toFront(); } } catch (IOException ex) { dialogHandler.addMessageDialogToQueue(java.text.MessageFormat.format(menus.getString("COULD NOT START THE HELP SYSTEM:{0}"), new Object[]{ex.getMessage()}), "Internal Help"); BugCatcherManager.getBugCatcher().logError(ex); } catch (SAXException ex) { dialogHandler.addMessageDialogToQueue(java.text.MessageFormat.format(menus.getString("COULD NOT START THE HELP SYSTEM:{0}"), new Object[]{ex.getMessage()}), "Internal Help"); BugCatcherManager.getBugCatcher().logError(ex); } } }); helpMenuItem.setEnabled(true); this.add(helpMenuItem); JMenuItem arbilWebsiteMenuItem = new JMenuItem(menus.getString("KINOATH WEBSITE")); arbilWebsiteMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { dialogHandler.openFileInExternalApplication(new URI("http://tla.mpi.nl/tools/tla-tools/kinoath")); } catch (Exception ex) { BugCatcherManager.getBugCatcher().logError(ex); } } }); this.add(arbilWebsiteMenuItem); JMenuItem arbilOnlineManualMenuItem = new JMenuItem(menus.getString("KINOATH ONLINE MANUAL")); arbilOnlineManualMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { dialogHandler.openFileInExternalApplication(new URI("http: } catch (Exception ex) { BugCatcherManager.getBugCatcher().logError(ex); } } }); this.add(arbilOnlineManualMenuItem); JMenuItem arbilForumMenuItem = new JMenuItem(menus.getString("KINOATH FORUM (WEBSITE)")); arbilForumMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { dialogHandler.openFileInExternalApplication(new URI("http://tla.mpi.nl/forums/software/kinoath")); } catch (Exception ex) { BugCatcherManager.getBugCatcher().logError(ex); } } }); this.add(arbilForumMenuItem); final JMenuItem viewErrorLogMenuItem = new JMenuItem(menus.getString("VIEW ERROR LOG")); viewErrorLogMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { dialogHandler.openFileInExternalApplication(ArbilBugCatcher.getLogFile(sessionStorage, versionManager.getApplicationVersion()).toURI()); } catch (Exception ex) { BugCatcherManager.getBugCatcher().logError(ex); } } }); this.add(viewErrorLogMenuItem); JMenuItem reindexFilesMenuItem = new JMenuItem(menus.getString("REINDEX ALL FILES FOR THIS PROJECT")); reindexFilesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { if (dialogHandler.showConfirmDialogBox(menus.getString("THIS WILL REINDEX ALL FILES IN THE PROJECT, THIS MAY TAKE SOME TIME, DO YOU WANT TO PROCEED?"), menus.getString("REINDEX ALL FILES"))) { new Thread(new Runnable() { public void run() { SavePanel currentSavePanel = diagramWindowManager.getCurrentSavePanel(parentComponent); try { if (currentSavePanel instanceof KinDiagramPanel) { final KinDiagramPanel diagramPanel = (KinDiagramPanel) currentSavePanel; diagramPanel.showProgressBar(); diagramPanel.getEntityCollection().recreateDatabase(); } // JProgressBar progressBar = new JProgressBar(); // progressBar.setString("reindexing all files"); // progressBar.setIndeterminate(true); dialogHandler.addMessageDialogToQueue(menus.getString("REINDEXING COMPLETE."), menus.getString("REINDEX ALL FILES")); } catch (EntityServiceException exception) { dialogHandler.addMessageDialogToQueue(exception.getMessage(), "Database Error"); } if (currentSavePanel instanceof KinDiagramPanel) { ((KinDiagramPanel) currentSavePanel).clearProgressBar(); } } }).start(); } } }); this.add(reindexFilesMenuItem); JMenuItem checkForUpdatesMenuItem = new JMenuItem(menus.getString("CHECK FOR UPDATES")); checkForUpdatesMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { if (!versionManager.forceUpdateCheck()) { ApplicationVersion appVersion = versionManager.getApplicationVersion(); String versionString = appVersion.currentMajor + "." + appVersion.currentMinor + "." + appVersion.currentRevision; dialogHandler.addMessageDialogToQueue(java.text.MessageFormat.format(menus.getString("NO UPDATES FOUND, CURRENT VERSION IS {0}"), new Object[]{versionString}), menus.getString("CHECK FOR UPDATES")); } } catch (Exception ex) { BugCatcherManager.getBugCatcher().logError(ex); } } }); this.add(checkForUpdatesMenuItem); // JMenuItem updateKmdiProfileMenuItem = new JMenuItem("Check Component Registry Updates (this will be moved to a panel)"); // updateKmdiProfileMenuItem.addActionListener(new java.awt.event.ActionListener() { // // todo: move this to a panel with more options. // public void actionPerformed(java.awt.event.ActionEvent evt) { // try { // String profileId = "clarin.eu:cr1:p_1320657629627"; // File xsdFile = new File(sessionStorage.getCacheDirectory(), "individual" + "-" + profileId + ".xsd"); // new CmdiTransformer(sessionStorage, bugCatcher).transformProfileXmlToXsd(xsdFile, profileId); // } catch (IOException exception) { // System.out.println("exception: " + exception.getMessage()); // } catch (TransformerException exception) { // System.out.println("exception: " + exception.getMessage()); // this.add(updateKmdiProfileMenuItem); this.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent evt) { } public void menuDeselected(MenuEvent evt) { } public void menuSelected(MenuEvent evt) { viewErrorLogMenuItem.setEnabled(ArbilBugCatcher.getLogFile(sessionStorage, versionManager.getApplicationVersion()).exists()); } }); } }
package org.jasig.portal.channels.portlet; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import javax.portlet.PortletMode; import javax.portlet.PortletRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.pluto.PortletContainer; import org.apache.pluto.PortletContainerServices; import org.apache.pluto.core.InternalActionResponse; import org.apache.pluto.factory.PortletObjectAccess; import org.apache.pluto.om.entity.PortletEntity; import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.window.PortletWindow; import org.apache.pluto.services.information.DynamicInformationProvider; import org.apache.pluto.services.information.InformationProviderAccess; import org.apache.pluto.services.information.PortletActionProvider; import org.apache.pluto.services.property.PropertyManager; import org.apache.pluto.services.property.PropertyManagerService; import org.jasig.portal.ChannelCacheKey; import org.jasig.portal.ChannelDefinition; import org.jasig.portal.ChannelRegistryStoreFactory; import org.jasig.portal.ChannelRuntimeData; import org.jasig.portal.ChannelRuntimeProperties; import org.jasig.portal.ChannelStaticData; import org.jasig.portal.IMultithreadedCacheable; import org.jasig.portal.IMultithreadedCharacterChannel; import org.jasig.portal.IMultithreadedDirectResponse; import org.jasig.portal.IMultithreadedPrivileged; import org.jasig.portal.PortalControlStructures; import org.jasig.portal.PortalEvent; import org.jasig.portal.PortalException; import org.jasig.portal.container.PortletContainerImpl; import org.jasig.portal.container.om.common.ObjectIDImpl; import org.jasig.portal.container.om.entity.PortletEntityImpl; import org.jasig.portal.container.om.portlet.PortletApplicationDefinitionImpl; import org.jasig.portal.container.om.portlet.PortletDefinitionImpl; import org.jasig.portal.container.om.portlet.UserAttributeImpl; import org.jasig.portal.container.om.portlet.UserAttributeListImpl; import org.jasig.portal.container.om.window.PortletWindowImpl; import org.jasig.portal.container.services.FactoryManagerServiceImpl; import org.jasig.portal.container.services.PortletContainerEnvironmentImpl; import org.jasig.portal.container.services.information.DynamicInformationProviderImpl; import org.jasig.portal.container.services.information.InformationProviderServiceImpl; import org.jasig.portal.container.services.information.PortletStateManager; import org.jasig.portal.container.services.log.LogServiceImpl; import org.jasig.portal.container.services.property.PropertyManagerServiceImpl; import org.jasig.portal.container.servlet.EmptyRequestImpl; import org.jasig.portal.container.servlet.ServletObjectAccess; import org.jasig.portal.container.servlet.ServletRequestImpl; import org.jasig.portal.layout.IUserLayoutChannelDescription; import org.jasig.portal.security.IOpaqueCredentials; import org.jasig.portal.security.IPerson; import org.jasig.portal.security.ISecurityContext; import org.jasig.portal.security.provider.NotSoOpaqueCredentials; import org.jasig.portal.utils.SAXHelper; import org.xml.sax.ContentHandler; /** * A JSR 168 Portlet adapter that presents a portlet * through the uPortal channel interface. * <p> * There is a related channel type called * "Portlet Adapter" that is included with uPortal, so to use * this channel, just select the "Portlet" type when publishing. * </p> * <p> * Note: A portlet can specify the String "password" in the * user attributes section of the portlet.xml. In this is done, * this adapter will look for the user's cached password. If * the user's password is being stored in memory by a caching * security context, the adapter will consult the cache to fill the * request for the attribute. If the user's password is not cached, * <code>null</code> will be set for the attributes value. * </p> * @author Ken Weiner, kweiner@unicon.net * @version $Revision$ */ public class CPortletAdapter implements IMultithreadedCharacterChannel, IMultithreadedPrivileged, IMultithreadedCacheable, IMultithreadedDirectResponse { private static final Log log = LogFactory.getLog(CPortletAdapter.class); protected static Map channelStateMap; private static boolean portletContainerInitialized; private static PortletContainer portletContainer; private static ServletConfig servletConfig; private static ChannelCacheKey systemCacheKey; private static ChannelCacheKey instanceCacheKey; private static final String uniqueContainerName = "Pluto-in-uPortal"; // Publish parameters expected by this channel private static final String portletDefinitionIdParamName = "portletDefinitionId"; public static final String portletPreferenceNamePrefix = "PORTLET."; static { channelStateMap = Collections.synchronizedMap(new HashMap()); portletContainerInitialized = false; // Initialize cache keys systemCacheKey = new ChannelCacheKey(); systemCacheKey.setKeyScope(ChannelCacheKey.SYSTEM_KEY_SCOPE); systemCacheKey.setKey("SYSTEM_SCOPE_KEY"); instanceCacheKey = new ChannelCacheKey(); instanceCacheKey.setKeyScope(ChannelCacheKey.INSTANCE_KEY_SCOPE); instanceCacheKey.setKey("INSTANCE_SCOPE_KEY"); } /** * Receive the servlet config from uPortal's PortalSessionManager servlet. * Pluto needs access to this object from serveral places. * @param config the servlet config */ public static void setServletConfig(ServletConfig config) { servletConfig = config; } protected void initPortletContainer(String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); PortalControlStructures pcs = channelState.getPortalControlStructures(); try { PortletContainerEnvironmentImpl environment = new PortletContainerEnvironmentImpl(); LogServiceImpl logService = new LogServiceImpl(); FactoryManagerServiceImpl factorManagerService = new FactoryManagerServiceImpl(); InformationProviderServiceImpl informationProviderService = new InformationProviderServiceImpl(); PropertyManagerService propertyManagerService = new PropertyManagerServiceImpl(); logService.init(servletConfig, null); factorManagerService.init(servletConfig, null); informationProviderService.init(servletConfig, null); environment.addContainerService(logService); environment.addContainerService(factorManagerService); environment.addContainerService(informationProviderService); environment.addContainerService(propertyManagerService); //Call added in case the context has been re-loaded PortletContainerServices.destroyReference(uniqueContainerName); portletContainer = new PortletContainerImpl(); portletContainer.init(uniqueContainerName, servletConfig, environment, new Properties()); portletContainerInitialized = true; } catch (Exception e) { String message = "Initialization of the portlet container failed."; log.error( message, e); throw new PortalException(message, e); } } protected void initPortletWindow(String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelRuntimeData rd = channelState.getRuntimeData(); ChannelStaticData sd = channelState.getStaticData(); ChannelData cd = channelState.getChannelData(); PortalControlStructures pcs = channelState.getPortalControlStructures(); try { synchronized(this) { if (!portletContainerInitialized) { initPortletContainer(uid); } } PortletContainerServices.prepare(uniqueContainerName); // Get the portlet definition Id which must be specified as a publish // parameter. The syntax of the ID is [portlet-context-name].[portlet-name] String portletDefinitionId = sd.getParameter(portletDefinitionIdParamName); if (portletDefinitionId == null) { throw new PortalException("Missing publish parameter '" + portletDefinitionIdParamName + "'"); } // Create the PortletDefinition PortletDefinitionImpl portletDefinition = (PortletDefinitionImpl)InformationProviderAccess.getStaticProvider().getPortletDefinition(ObjectIDImpl.createFromString(portletDefinitionId)); if (portletDefinition == null) { throw new PortalException("Unable to find portlet definition for ID '" + portletDefinitionId + "'"); } ChannelDefinition channelDefinition = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl().getChannelDefinition(Integer.parseInt(sd.getChannelPublishId())); portletDefinition.setChannelDefinition(channelDefinition); portletDefinition.loadPreferences(); // Create the PortletEntity PortletEntityImpl portletEntity = new PortletEntityImpl(); portletEntity.setId(sd.getChannelPublishId()); portletEntity.setPortletDefinition(portletDefinition); portletEntity.setUserLayout(pcs.getUserPreferencesManager().getUserLayoutManager().getUserLayout()); portletEntity.setChannelDescription((IUserLayoutChannelDescription)pcs.getUserPreferencesManager().getUserLayoutManager().getNode(sd.getChannelSubscribeId())); portletEntity.setPerson(sd.getPerson()); portletEntity.loadPreferences(); // Add the user information into the request See PLT.17.2. Map userInfo = cd.getUserInfo(); if (userInfo == null) { userInfo = new HashMap(); IPerson person = sd.getPerson(); if (person.getSecurityContext().isAuthenticated()) { UserAttributeListImpl userAttributes = ((PortletApplicationDefinitionImpl)portletDefinition.getPortletApplicationDefinition()).getUserAttributes(); for (Iterator iter = userAttributes.iterator(); iter.hasNext(); ) { UserAttributeImpl userAttribute = (UserAttributeImpl)iter.next(); String attName = userAttribute.getName(); String attValue = (String)person.getAttribute(attName); final String PASSWORD_ATTR = "password"; if ((attValue == null || attValue.equals("")) && attName.equals(PASSWORD_ATTR)) { attValue = getPassword(person); } userInfo.put(attName, attValue); } cd.setUserInfo(userInfo); } } // Wrap the request ServletRequestImpl wrappedRequest = new ServletRequestImpl(pcs.getHttpServletRequest(), sd.getPerson(), portletDefinition.getInitSecurityRoleRefSet()); // Now create the PortletWindow and hold a reference to it PortletWindowImpl portletWindow = new PortletWindowImpl(); portletWindow.setId(sd.getChannelSubscribeId()); portletWindow.setPortletEntity(portletEntity); portletWindow.setChannelRuntimeData(rd); portletWindow.setHttpServletRequest(wrappedRequest); cd.setPortletWindow(portletWindow); // Ask the container to load the portlet synchronized(this) { portletContainer.portletLoad(portletWindow, wrappedRequest, pcs.getHttpServletResponse()); } cd.setPortletWindowInitialized(true); } catch (Exception e) { String message = "Initialization of the portlet container failed."; log.error( message, e); throw new PortalException(message, e); } finally { PortletContainerServices.release(); } } /** * Sets channel runtime properties. * @param uid a unique ID used to identify the state of the channel * @return channel runtime properties */ public ChannelRuntimeProperties getRuntimeProperties(String uid) { return new ChannelRuntimeProperties(); } /** * React to portal events. * Removes channel state from the channel state map when the session expires. * @param ev a portal event * @param uid a unique ID used to identify the state of the channel */ public void receiveEvent(PortalEvent ev, String uid) { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelData cd = channelState.getChannelData(); PortalControlStructures pcs = channelState.getPortalControlStructures(); try { PortletContainerServices.prepare(uniqueContainerName); cd.setReceivedEvent(true); DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(pcs.getHttpServletRequest()); switch (ev.getEventNumber()) { // Detect portlet mode changes // Cannot use the PortletActionProvider to change modes here. It uses // PortletWindow information to store the changes and the window is // not current at this point. case PortalEvent.EDIT_BUTTON_EVENT: cd.setNewPortletMode(PortletMode.EDIT); break; case PortalEvent.HELP_BUTTON_EVENT: cd.setNewPortletMode(PortletMode.HELP); break; case PortalEvent.ABOUT_BUTTON_EVENT: // We might want to consider a custom ABOUT mode here break; // Detect portlet window state changes case PortalEvent.DETACH_BUTTON_EVENT: // Maybe we want to consider a custom window state here or used MAXIMIZED break; // Detect end of session or portlet removed from layout case PortalEvent.UNSUBSCRIBE: //User is removing this portlet from their layout, remove all //the preferences they have stored for it. PortletEntityImpl pe = (PortletEntityImpl)cd.getPortletWindow().getPortletEntity(); try { pe.removePreferences(); } catch (Exception e) { } case PortalEvent.SESSION_DONE: // For both SESSION_DONE and UNSUBSCRIBE, we might want to // release resources here if we need to PortletStateManager.clearState(pcs.getHttpServletRequest()); break; default: break; } if (channelState != null) { channelState.setPortalEvent(ev); if (ev.getEventNumber() == PortalEvent.SESSION_DONE) { channelStateMap.remove(uid); // Clean up } } } finally { PortletContainerServices.release(); } } /** * Sets the channel static data. * @param sd the channel static data * @param uid a unique ID used to identify the state of the channel * @throws org.jasig.portal.PortalException */ public void setStaticData(ChannelStaticData sd, String uid) throws PortalException { ChannelState channelState = new ChannelState(); channelState.setStaticData(sd); channelStateMap.put(uid, channelState); try { // Register rendering dependencies to ensure that setRuntimeData is called on // all CPortletAdapters before any of them is asked to render List portletIds = (List)sd.getJNDIContext().lookup("/portlet-ids"); Iterator iter = portletIds.iterator(); while (iter.hasNext()) { String portletId = (String)iter.next(); sd.getICCRegistry().addInstructorChannel(portletId); sd.getICCRegistry().addListenerChannel(portletId); } portletIds.add(sd.getChannelSubscribeId()); } catch (Exception e) { throw new PortalException(e); } } /** * Sets the channel runtime data. * @param rd the channel runtime data * @param uid a unique ID used to identify the state of the channel * @throws org.jasig.portal.PortalException */ public void setRuntimeData(ChannelRuntimeData rd, String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); channelState.setRuntimeData(rd); ChannelStaticData sd = channelState.getStaticData(); ChannelData cd = channelState.getChannelData(); try { PortletContainerServices.prepare(uniqueContainerName); if (cd.isPortletWindowInitialized()) { PortalControlStructures pcs = channelState.getPortalControlStructures(); ServletRequestImpl wrappedRequest = new ServletRequestImpl(pcs.getHttpServletRequest(), sd.getPerson(), cd.getPortletWindow().getPortletEntity().getPortletDefinition().getInitSecurityRoleRefSet()); // Add the user information wrappedRequest.setAttribute(PortletRequest.USER_INFO, cd.getUserInfo()); // Put the current runtime data and wrapped request into the portlet window PortletWindowImpl portletWindow = (PortletWindowImpl)cd.getPortletWindow(); portletWindow.setChannelRuntimeData(rd); portletWindow.setHttpServletRequest(wrappedRequest); // Get the portlet url manager which will analyze the request parameters DynamicInformationProvider dip = InformationProviderAccess.getDynamicProvider(wrappedRequest); PortletStateManager psm = ((DynamicInformationProviderImpl)dip).getPortletStateManager(portletWindow); // If portlet is rendering as root, change mode to maximized, otherwise minimized PortletActionProvider pap = dip.getPortletActionProvider(portletWindow); if (rd.isRenderingAsRoot()) { pap.changePortletWindowState(WindowState.MAXIMIZED); } else { pap.changePortletWindowState(WindowState.NORMAL); } PortletMode newMode = cd.getNewPortletMode(); if (newMode != null) { pap.changePortletMode(newMode); cd.setNewPortletMode(null); } // Process action if this is the targeted channel and the URL is an action URL if (rd.isTargeted() && psm.isAction()) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), pw); //System.out.println("Processing portlet action on " + cd.getPortletWindow().getId()); portletContainer.processPortletAction(portletWindow, wrappedRequest, wrappedResponse); InternalActionResponse actionResponse = (InternalActionResponse)PortletObjectAccess.getActionResponse(cd.getPortletWindow(), pcs.getHttpServletRequest(), pcs.getHttpServletResponse()); cd.setProcessedAction(true); //FIXME WindowState switches are NOT honored! } catch (Exception e) { throw new PortalException(e); } } } } finally { PortletContainerServices.release(); } } /** * Sets the portal control structures. * @param pcs the portal control structures * @param uid a unique ID used to identify the state of the channel * @throws org.jasig.portal.PortalException */ public void setPortalControlStructures(PortalControlStructures pcs, String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); channelState.setPortalControlStructures(pcs); } /** * Output channel content to the portal as raw characters * @param pw a print writer * @param uid a unique ID used to identify the state of the channel */ public void renderCharacters(PrintWriter pw, String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelData cd = channelState.getChannelData(); if (!cd.isPortletWindowInitialized()) { initPortletWindow(uid); } try { String markupString = getMarkup(uid); pw.print(markupString); } catch (Exception e) { throw new PortalException(e); } } /** * Output channel content to the portal. This version of the * render method is normally not used since this is a "character channel". * @param out a sax document handler * @param uid a unique ID used to identify the state of the channel */ public void renderXML(ContentHandler out, String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelData cd = channelState.getChannelData(); if (!cd.isPortletWindowInitialized()) { initPortletWindow(uid); } try { String markupString = getMarkup(uid); // Output content. This assumes that markupString // is well-formed. Consider changing to a character // channel when it becomes available. Until we use the // character channel, these <div> tags will be necessary. SAXHelper.outputContent(out, "<div>" + markupString + "</div>"); } catch (Exception e) { throw new PortalException(e); } } /** * This is where we do the real work of getting the markup. * This is called from both renderXML() and renderCharacters(). * @param uid a unique ID used to identify the state of the channel */ protected synchronized String getMarkup(String uid) throws PortalException { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelRuntimeData rd = channelState.getRuntimeData(); ChannelStaticData sd = channelState.getStaticData(); ChannelData cd = channelState.getChannelData(); PortletWindow portletWindow = cd.getPortletWindow(); PortalControlStructures pcs = channelState.getPortalControlStructures(); String markup = "<b>Problem rendering portlet " + sd.getParameter("portletDefinitionId") + "</b>"; try { PortletContainerServices.prepare(uniqueContainerName); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); HttpServletRequest wrappedRequest = ((PortletWindowImpl)cd.getPortletWindow()).getHttpServletRequest(); HttpServletResponse wrappedResponse = ServletObjectAccess.getStoredServletResponse(pcs.getHttpServletResponse(), pw); transferActionResultsToRequest(channelState, wrappedRequest); // Hide the request parameters if this portlet isn't targeted if (!rd.isTargeted()) { wrappedRequest = new EmptyRequestImpl(wrappedRequest); } // Add the user information wrappedRequest.setAttribute(PortletRequest.USER_INFO, cd.getUserInfo()); //System.out.println("Rendering portlet " + cd.getPortletWindow().getId()); portletContainer.renderPortlet(portletWindow, wrappedRequest, wrappedResponse); //Support for the portlet modifying it's cache timeout Map properties = PropertyManager.getRequestProperties(portletWindow, wrappedRequest); String[] exprCacheTimeStr = (String[])properties.get(RenderResponse.EXPIRATION_CACHE); if (exprCacheTimeStr != null && exprCacheTimeStr.length > 0) { PortletEntity pe = portletWindow.getPortletEntity(); PortletDefinition pd = pe.getPortletDefinition(); try { Integer.parseInt(exprCacheTimeStr[0]); //Check for valid number cd.setExpirationCache(exprCacheTimeStr[0]); } catch (NumberFormatException nfe) { log.error("The specified RenderResponse.EXPIRATION_CACHE value of (" + exprCacheTimeStr + ") is not a number.", nfe); throw nfe; } } markup = sw.toString(); cd.setProcessedAction(false); ((PortletWindowImpl)cd.getPortletWindow()).setInternalActionResponse(null); } catch (Throwable t) { // TODO: review this // t.printStackTrace(); // since the stack trace will be logged, this printStackTrace() // was overkill? -andrew.petro@yale.edu log.error(t, t); throw new PortalException(t.getMessage()); } finally { PortletContainerServices.release(); } //Keep track of the last time the portlet was successfully rendered cd.setLastRenderTime(System.currentTimeMillis()); return markup; } /** * Generates a channel cache key. The key scope is set to be system-wide * when the channel is anonymously accessed, otherwise it is set to be * instance-wide. The caching implementation here is simple and may not * handle all cases. It may also violate the Portlet Specification so * this obviously needs further discussion. * @param uid the unique identifier * @return the channel cache key */ public ChannelCacheKey generateKey(String uid) { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelStaticData staticData = channelState.getStaticData(); ChannelCacheKey cck = null; // Anonymously accessed pages can be cached system-wide if(staticData.getPerson().isGuest()) { cck = systemCacheKey; } else { cck = instanceCacheKey; } return cck; } /** * Determines whether the cached content for this channel is still valid. * <p> * Return <code>true</code> when:<br> * <ol> * <li>We have not just received an event</li> * <li>No runtime parameters are sent to the channel</li> * <li>The focus hasn't switched.</li> * </ol> * Otherwise, return <code>false</code>. * <p> * In other words, cache the content in all cases <b>except</b> * for when a user clicks a channel button, a link or form button within the channel, * or the <i>focus</i> or <i>unfocus</i> button. * @param validity the validity object * @param uid the unique identifier * @return <code>true</code> if the cache is still valid, otherwise <code>false</code> */ public boolean isCacheValid(Object validity, String uid) { ChannelState channelState = (ChannelState)channelStateMap.get(uid); ChannelStaticData staticData = channelState.getStaticData(); ChannelRuntimeData runtimeData = channelState.getRuntimeData(); PortalControlStructures pcs = channelState.getPortalControlStructures(); ChannelData cd = channelState.getChannelData(); PortletWindow pw = cd.getPortletWindow(); PortletEntity pe = pw.getPortletEntity(); PortletDefinition pd = pe.getPortletDefinition(); //Expiration based caching support for the portlet. String portletSetExprCacheTime = cd.getExpirationCache(); String exprCacheTimeStr = pd.getExpirationCache(); try { if (portletSetExprCacheTime != null) exprCacheTimeStr = portletSetExprCacheTime; int exprCacheTime = Integer.parseInt(exprCacheTimeStr); if (exprCacheTime == 0) { return false; } else if (exprCacheTime > 0) { long lastRenderTime = cd.getLastRenderTime(); if ((lastRenderTime + (exprCacheTime * 1000)) < System.currentTimeMillis()) return false; } } catch (Exception e) { if (log.isWarnEnabled()) { String portletId = staticData.getParameter(portletDefinitionIdParamName); log.warn("Error parsing portlet expiration time (" + exprCacheTimeStr + ") for portlet (" + portletId + ").", e); } } // Determine if the channel focus has changed boolean previouslyFocused = cd.isFocused(); cd.setFocused(runtimeData.isRenderingAsRoot()); boolean focusHasSwitched = cd.isFocused() != previouslyFocused; // Dirty cache only when we receive an event, one or more request params, or a change in focus boolean cacheValid = !(cd.hasReceivedEvent() || runtimeData.isTargeted() || focusHasSwitched); cd.setReceivedEvent(false); return cacheValid; } /** * Checks if the portlet has just processed an action during this request. If so then the * changes that the portlet may have made during it's processAction are captured from the * portlet's ActionResponse and they are added to the request that will be passed to the portlet * container. * * <br> * <b>PortletContainerServices.prepare</b> MUST be called before this method is called. * <br> * <b>PortletContainerServices.release</b> MUST be called after this method is called. * * @param channelState The state to read the action information from * @param wrappedRequest The request to add data from the action to */ private void transferActionResultsToRequest(ChannelState channelState, HttpServletRequest wrappedRequest) { ChannelData cd = channelState.getChannelData(); PortalControlStructures pcs = channelState.getPortalControlStructures(); if (cd.hasProcessedAction()) { InternalActionResponse actionResponse = ((PortletWindowImpl)cd.getPortletWindow()).getInternalActionResponse(); PortletActionProvider pap = InformationProviderAccess.getDynamicProvider(pcs.getHttpServletRequest()).getPortletActionProvider(cd.getPortletWindow()); // Change modes if (actionResponse.getChangedPortletMode() != null) { pap.changePortletMode(actionResponse.getChangedPortletMode()); } // Change window states if (actionResponse.getChangedWindowState() != null) { pap.changePortletWindowState(actionResponse.getChangedWindowState()); } // Change render parameters Map renderParameters = actionResponse.getRenderParameters(); ((ServletRequestImpl)wrappedRequest).setParameters(renderParameters); } } /** * Retrieves the users password by iterating over * the user's security contexts and returning the first * available cached password. * @param person the person whose password is being sought * @return the users password */ private String getPassword(IPerson person) { String password = null; ISecurityContext ic = (ISecurityContext) person.getSecurityContext(); IOpaqueCredentials oc = ic.getOpaqueCredentials(); if (oc instanceof NotSoOpaqueCredentials) { NotSoOpaqueCredentials nsoc = (NotSoOpaqueCredentials)oc; password = nsoc.getCredentials(); } // If still no password, loop through subcontexts to find cached credentials Enumeration en = ic.getSubContexts(); while (password == null && en.hasMoreElements()) { ISecurityContext sctx = (ISecurityContext)en.nextElement(); IOpaqueCredentials soc = sctx.getOpaqueCredentials(); if (soc instanceof NotSoOpaqueCredentials) { NotSoOpaqueCredentials nsoc = (NotSoOpaqueCredentials)soc; password = nsoc.getCredentials(); } } return password; } }
package org.jivesoftware.smackx.debugger; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.text.*; import java.util.Date; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.debugger.*; import org.jivesoftware.smack.packet.*; import org.jivesoftware.smack.util.*; /** * The EnhancedDebugger is a debugger that allows to debug sent, received and interpreted messages * but also provides the ability to send ad-hoc messages composed by the user.<p> * * A new EnhancedDebugger will be created for each connection to debug. All the EnhancedDebuggers * will be shown in the same debug window provided by the class EnhancedDebuggerWindow. * * @author Gaston Dombiak */ public class EnhancedDebugger implements SmackDebugger { private static final String NEWLINE = "\n"; private static ImageIcon packetReceivedIcon; private static ImageIcon packetSentIcon; private static ImageIcon presencePacketIcon; private static ImageIcon iqPacketIcon; private static ImageIcon messagePacketIcon; private static ImageIcon unknownPacketTypeIcon; { URL url; // Load the image icons url = Thread.currentThread().getContextClassLoader().getResource("images/nav_left_blue.png"); if (url != null) { packetReceivedIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/nav_right_red.png"); if (url != null) { packetSentIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/photo_portrait.png"); if (url != null) { presencePacketIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource( "images/question_and_answer.png"); if (url != null) { iqPacketIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/message.png"); if (url != null) { messagePacketIcon = new ImageIcon(url); } url = Thread.currentThread().getContextClassLoader().getResource("images/unknown.png"); if (url != null) { unknownPacketTypeIcon = new ImageIcon(url); } } private DefaultTableModel messagesTable = null; private JTextArea messageTextArea = null; private JFormattedTextField userField = null; private JFormattedTextField statusField = null; private XMPPConnection connection = null; private PacketListener packetReaderListener = null; private PacketListener packetWriterListener = null; private ConnectionListener connListener = null; private Writer writer; private Reader reader; private ReaderListener readerListener; private WriterListener writerListener; private Date creationTime = new Date(); // Statistics variables private DefaultTableModel statisticsTable = null; private int sentPackets = 0; private int receivedPackets = 0; private int sentIQPackets = 0; private int receivedIQPackets = 0; private int sentMessagePackets = 0; private int receivedMessagePackets = 0; private int sentPresencePackets = 0; private int receivedPresencePackets = 0; private int sentOtherPackets = 0; private int receivedOtherPackets = 0; JTabbedPane tabbedPane; public EnhancedDebugger(XMPPConnection connection, Writer writer, Reader reader) { this.connection = connection; this.writer = writer; this.reader = reader; createDebug(); EnhancedDebuggerWindow.addDebugger(this); } /** * Creates the debug process, which is a GUI window that displays XML traffic. */ private void createDebug() { // We'll arrange the UI into six tabs. The first tab contains all data, the second // client generated XML, the third server generated XML, the fourth allows to send // ad-hoc messages and the fifth contains connection information. tabbedPane = new JTabbedPane(); // Add the All Packets, Sent, Received and Interpreted panels addBasicPanels(); // Add the panel to send ad-hoc messages addAdhocPacketPanel(); // Add the connection information panel addInformationPanel(); // Create a thread that will listen for all incoming packets and write them to // the GUI. This is what we call "interpreted" packet data, since it's the packet // data as Smack sees it and not as it's coming in as raw XML. packetReaderListener = new PacketListener() { SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss aaa"); public void processPacket(Packet packet) { addReadPacketToTable(dateFormatter, packet); } }; // Create a thread that will listen for all outgoing packets and write them to // the GUI. packetWriterListener = new PacketListener() { SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss aaa"); public void processPacket(Packet packet) { addSentPacketToTable(dateFormatter, packet); } }; // Create a thread that will listen for any connection closed event connListener = new ConnectionListener() { public void connectionClosed() { statusField.setValue("Closed"); EnhancedDebuggerWindow.connectionClosed(EnhancedDebugger.this); } public void connectionClosedOnError(Exception e) { statusField.setValue("Closed due to an exception"); EnhancedDebuggerWindow.connectionClosedOnError(EnhancedDebugger.this, e); } }; } private void addBasicPanels() { JPanel allPane = new JPanel(); allPane.setLayout(new GridLayout(2, 1)); tabbedPane.add("All Packets", allPane); tabbedPane.setToolTipTextAt(0, "Sent and received packets processed by Smack"); messagesTable = new DefaultTableModel( new Object[] { "Hide", "Timestamp", "", "", "Message", "Id", "Type", "To", "From" }, 0) { public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } public Class getColumnClass(int columnIndex) { if (columnIndex == 2 || columnIndex == 3) { return Icon.class; } return super.getColumnClass(columnIndex); } }; JTable table = new JTable(messagesTable); // Allow only single a selection table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Hide the first column table.getColumnModel().getColumn(0).setMaxWidth(0); table.getColumnModel().getColumn(0).setMinWidth(0); table.getTableHeader().getColumnModel().getColumn(0).setMaxWidth(0); table.getTableHeader().getColumnModel().getColumn(0).setMinWidth(0); // Set the column "timestamp" size table.getColumnModel().getColumn(1).setMaxWidth(300); table.getColumnModel().getColumn(1).setPreferredWidth(70); // Set the column "direction" icon size table.getColumnModel().getColumn(2).setMaxWidth(50); table.getColumnModel().getColumn(2).setPreferredWidth(30); // Set the column "packet type" icon size table.getColumnModel().getColumn(3).setMaxWidth(50); table.getColumnModel().getColumn(3).setPreferredWidth(30); // Set the column "Id" size table.getColumnModel().getColumn(5).setMaxWidth(100); table.getColumnModel().getColumn(5).setPreferredWidth(55); // Set the column "type" size table.getColumnModel().getColumn(6).setMaxWidth(200); table.getColumnModel().getColumn(6).setPreferredWidth(50); // Set the column "to" size table.getColumnModel().getColumn(7).setMaxWidth(300); table.getColumnModel().getColumn(7).setPreferredWidth(90); // Set the column "from" size table.getColumnModel().getColumn(8).setMaxWidth(300); table.getColumnModel().getColumn(8).setPreferredWidth(90); // Create a table listener that listen for row selection events SelectionListener selectionListener = new SelectionListener(table); table.getSelectionModel().addListSelectionListener(selectionListener); table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener); allPane.add(new JScrollPane(table)); messageTextArea = new JTextArea(); messageTextArea.setEditable(false); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // Set the sent text as the new content of the clipboard clipboard.setContents(new StringSelection(messageTextArea.getText()), null); } }); menu.add(menuItem1); // Add listener to the text area so the popup menu can come up. messageTextArea.addMouseListener(new PopupListener(menu)); allPane.add(new JScrollPane(messageTextArea)); // Create UI elements for client generated XML traffic. final JTextArea sentText = new JTextArea(); sentText.setEditable(false); sentText.setForeground(new Color(112, 3, 3)); tabbedPane.add("Raw Sent Packets", new JScrollPane(sentText)); tabbedPane.setToolTipTextAt(1, "Raw text of the sent packets"); // Add pop-up menu. menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // Set the sent text as the new content of the clipboard clipboard.setContents(new StringSelection(sentText.getText()), null); } }); JMenuItem menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sentText.setText(""); } }); // Add listener to the text area so the popup menu can come up. sentText.addMouseListener(new PopupListener(menu)); menu.add(menuItem1); menu.add(menuItem2); // Create UI elements for server generated XML traffic. final JTextArea receivedText = new JTextArea(); receivedText.setEditable(false); receivedText.setForeground(new Color(6, 76, 133)); tabbedPane.add("Raw Received Packets", new JScrollPane(receivedText)); tabbedPane.setToolTipTextAt( 2, "Raw text of the received packets before Smack process them"); // Add pop-up menu. menu = new JPopupMenu(); menuItem1 = new JMenuItem("Copy"); menuItem1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the clipboard Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); // Set the sent text as the new content of the clipboard clipboard.setContents(new StringSelection(receivedText.getText()), null); } }); menuItem2 = new JMenuItem("Clear"); menuItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { receivedText.setText(""); } }); // Add listener to the text area so the popup menu can come up. receivedText.addMouseListener(new PopupListener(menu)); menu.add(menuItem1); menu.add(menuItem2); // Create a special Reader that wraps the main Reader and logs data to the GUI. ObservableReader debugReader = new ObservableReader(reader); readerListener = new ReaderListener() { public void read(String str) { int index = str.lastIndexOf(">"); if (index != -1) { receivedText.append(str.substring(0, index + 1)); receivedText.append(NEWLINE); if (str.length() > index) { receivedText.append(str.substring(index + 1)); } } else { receivedText.append(str); } } }; debugReader.addReaderListener(readerListener); // Create a special Writer that wraps the main Writer and logs data to the GUI. ObservableWriter debugWriter = new ObservableWriter(writer); writerListener = new WriterListener() { public void write(String str) { sentText.append(str); if (str.endsWith(">")) { sentText.append(NEWLINE); } } }; debugWriter.addWriterListener(writerListener); // Assign the reader/writer objects to use the debug versions. The packet reader // and writer will use the debug versions when they are created. reader = debugReader; writer = debugWriter; } private void addAdhocPacketPanel() { // Create UI elements for sending ad-hoc messages. final JTextArea adhocMessages = new JTextArea(); adhocMessages.setEditable(true); adhocMessages.setForeground(new Color(1, 94, 35)); tabbedPane.add("Ad-hoc message", new JScrollPane(adhocMessages)); tabbedPane.setToolTipTextAt(3, "Panel that allows you to send adhoc packets"); // Add pop-up menu. JPopupMenu menu = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Message"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<message to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"><body></body></message>"); } }); menu.add(menuItem); menuItem = new JMenuItem("IQ Get"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<iq type=\"get\" to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"><query xmlns=\"\"></query></iq>"); } }); menu.add(menuItem); menuItem = new JMenuItem("IQ Set"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<iq type=\"set\" to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"><query xmlns=\"\"></query></iq>"); } }); menu.add(menuItem); menuItem = new JMenuItem("Presence"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText( "<presence to=\"\" id=\"" + StringUtils.randomString(5) + "-X\"/>"); } }); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Send"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!"".equals(adhocMessages.getText())) { AdHocPacket packetToSend = new AdHocPacket(adhocMessages.getText()); connection.sendPacket(packetToSend); } } }); menu.add(menuItem); menuItem = new JMenuItem("Clear"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adhocMessages.setText(null); } }); menu.add(menuItem); // Add listener to the text area so the popup menu can come up. adhocMessages.addMouseListener(new PopupListener(menu)); } private void addInformationPanel() { // Create UI elements for connection information. JPanel informationPanel = new JPanel(); informationPanel.setLayout(new BorderLayout()); // Add the Host information JPanel connPanel = new JPanel(); connPanel.setLayout(new GridBagLayout()); connPanel.setBorder(BorderFactory.createTitledBorder("Connection information")); JLabel label = new JLabel("Host: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); JFormattedTextField field = new JFormattedTextField(connection.getHost()); field.setMinimumSize(new java.awt.Dimension(150, 20)); field.setMaximumSize(new java.awt.Dimension(150, 20)); field.setEditable(false); field.setBorder(null); connPanel.add( field, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the Port information label = new JLabel("Port: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); field = new JFormattedTextField(new Integer(connection.getPort())); field.setMinimumSize(new java.awt.Dimension(150, 20)); field.setMaximumSize(new java.awt.Dimension(150, 20)); field.setEditable(false); field.setBorder(null); connPanel.add( field, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection's User information label = new JLabel("User: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); userField = new JFormattedTextField(); userField.setMinimumSize(new java.awt.Dimension(150, 20)); userField.setMaximumSize(new java.awt.Dimension(150, 20)); userField.setEditable(false); userField.setBorder(null); connPanel.add( userField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection's creationTime information label = new JLabel("Creation time: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); field = new JFormattedTextField(new SimpleDateFormat("yyyy.MM.dd hh:mm:ss aaa")); field.setMinimumSize(new java.awt.Dimension(150, 20)); field.setMaximumSize(new java.awt.Dimension(150, 20)); field.setValue(creationTime); field.setEditable(false); field.setBorder(null); connPanel.add( field, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection's creationTime information label = new JLabel("Status: "); label.setMinimumSize(new java.awt.Dimension(150, 14)); label.setMaximumSize(new java.awt.Dimension(150, 14)); connPanel.add( label, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, 21, 0, new Insets(0, 0, 0, 0), 0, 0)); statusField = new JFormattedTextField(); statusField.setMinimumSize(new java.awt.Dimension(150, 20)); statusField.setMaximumSize(new java.awt.Dimension(150, 20)); statusField.setValue("Active"); statusField.setEditable(false); statusField.setBorder(null); connPanel.add( statusField, new GridBagConstraints(1, 4, 1, 1, 0.0, 0.0, 10, 2, new Insets(0, 0, 0, 0), 0, 0)); // Add the connection panel to the information panel informationPanel.add(connPanel, BorderLayout.NORTH); // Add the Number of sent packets information JPanel packetsPanel = new JPanel(); packetsPanel.setLayout(new GridLayout(1, 1)); packetsPanel.setBorder(BorderFactory.createTitledBorder("Transmitted Packets")); statisticsTable = new DefaultTableModel(new Object[][] { { "IQ", new Integer(0), new Integer(0)}, { "Message", new Integer(0), new Integer(0) }, { "Presence", new Integer(0), new Integer(0) }, { "Other", new Integer(0), new Integer(0) }, { "Total", new Integer(0), new Integer(0) } }, new Object[] { "Type", "Received", "Sent" }) { public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } }; JTable table = new JTable(statisticsTable); // Allow only single a selection table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); packetsPanel.add(new JScrollPane(table)); // Add the packets panel to the information panel informationPanel.add(packetsPanel, BorderLayout.CENTER); tabbedPane.add("Information", new JScrollPane(informationPanel)); tabbedPane.setToolTipTextAt(4, "Information and statistics about the debugged connection"); } public void userHasLogged(String user) { userField.setText(user); EnhancedDebuggerWindow.userHasLogged(this, user); // Add the connection listener to the connection so that the debugger can be notified // whenever the connection is closed. connection.addConnectionListener(connListener); } public Reader getReader() { return reader; } public Writer getWriter() { return writer; } public PacketListener getReaderListener() { return packetReaderListener; } public PacketListener getWriterListener() { return packetWriterListener; } /** * Updates the statistics table */ private void updateStatistics() { statisticsTable.setValueAt(new Integer(receivedIQPackets), 0, 1); statisticsTable.setValueAt(new Integer(sentIQPackets), 0, 2); statisticsTable.setValueAt(new Integer(receivedMessagePackets), 1, 1); statisticsTable.setValueAt(new Integer(sentMessagePackets), 1, 2); statisticsTable.setValueAt(new Integer(receivedPresencePackets), 2, 1); statisticsTable.setValueAt(new Integer(sentPresencePackets), 2, 2); statisticsTable.setValueAt(new Integer(receivedOtherPackets), 3, 1); statisticsTable.setValueAt(new Integer(sentOtherPackets), 3, 2); statisticsTable.setValueAt(new Integer(receivedPackets), 4, 1); statisticsTable.setValueAt(new Integer(sentPackets), 4, 2); } /** * Adds the received packet detail to the messages table. * * @param dateFormatter the SimpleDateFormat to use to format Dates * @param packet the read packet to add to the table */ private void addReadPacketToTable(SimpleDateFormat dateFormatter, Packet packet) { String messageType = null; String from = packet.getFrom(); String type = ""; Icon packetTypeIcon; receivedPackets++; if (packet instanceof IQ) { packetTypeIcon = iqPacketIcon; messageType = "IQ Received (class=" + packet.getClass().getName() + ")"; type = ((IQ) packet).getType().toString(); receivedIQPackets++; } else if (packet instanceof Message) { packetTypeIcon = messagePacketIcon; messageType = "Message Received"; type = ((Message) packet).getType().toString(); receivedMessagePackets++; } else if (packet instanceof Presence) { packetTypeIcon = presencePacketIcon; messageType = "Presence Received"; type = ((Presence) packet).getType().toString(); receivedPresencePackets++; } else { packetTypeIcon = unknownPacketTypeIcon; messageType = packet.getClass().getName() + " Received"; receivedOtherPackets++; } messagesTable.addRow( new Object[] { formatXML(packet.toXML()), dateFormatter.format(new Date()), packetReceivedIcon, packetTypeIcon, messageType, packet.getPacketID(), type, "", from }); // Update the statistics table updateStatistics(); } /** * Adds the sent packet detail to the messages table. * * @param dateFormatter the SimpleDateFormat to use to format Dates * @param packet the sent packet to add to the table */ private void addSentPacketToTable(SimpleDateFormat dateFormatter, Packet packet) { String messageType = null; String to = packet.getTo(); String type = ""; Icon packetTypeIcon; sentPackets++; if (packet instanceof IQ) { packetTypeIcon = iqPacketIcon; messageType = "IQ Sent (class=" + packet.getClass().getName() + ")"; type = ((IQ) packet).getType().toString(); sentIQPackets++; } else if (packet instanceof Message) { packetTypeIcon = messagePacketIcon; messageType = "Message Sent"; type = ((Message) packet).getType().toString(); sentMessagePackets++; } else if (packet instanceof Presence) { packetTypeIcon = presencePacketIcon; messageType = "Presence Sent"; type = ((Presence) packet).getType().toString(); sentPresencePackets++; } else { packetTypeIcon = unknownPacketTypeIcon; messageType = packet.getClass().getName() + " Sent"; sentOtherPackets++; } messagesTable.addRow( new Object[] { formatXML(packet.toXML()), dateFormatter.format(new Date()), packetSentIcon, packetTypeIcon, messageType, packet.getPacketID(), type, to, "" }); // Update the statistics table updateStatistics(); } private String formatXML(String str) { try { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // Transform the requested string into a nice formatted XML string StreamSource source = new StreamSource(new StringReader(str)); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return sw.toString(); } catch (TransformerConfigurationException tce) { // Error generated by the parser System.out.println("\n** Transformer Factory error"); System.out.println(" " + tce.getMessage()); // Use the contained exception, if any Throwable x = tce; if (tce.getException() != null) x = tce.getException(); x.printStackTrace(); } catch (TransformerException te) { // Error generated by the parser System.out.println("\n** Transformation error"); System.out.println(" " + te.getMessage()); // Use the contained exception, if any Throwable x = te; if (te.getException() != null) x = te.getException(); x.printStackTrace(); } return str; } /** * Returns true if the debugger's connection with the server is up and running. * * @return true if the connection with the server is active. */ boolean isConnectionActive() { return connection.isConnected(); } /** * Stops debugging the connection. Removes any listener on the connection. * */ void cancel() { connection.removeConnectionListener(connListener); connection.removePacketListener(packetReaderListener); connection.removePacketWriterListener(packetWriterListener); ((ObservableReader)reader).removeReaderListener(readerListener); ((ObservableWriter)writer).removeWriterListener(writerListener); messagesTable = null; } /** * An ad-hoc packet is like any regular packet but with the exception that it's intention is * to be used only <b>to send packets</b>.<p> * * The whole text to send must be passed to the constructor. This implies that the client of * this class is responsible for sending a valid text to the constructor. * */ private class AdHocPacket extends Packet { private String text; /** * Create a new AdHocPacket with the text to send. The passed text must be a valid text to * send to the server, no validation will be done on the passed text. * * @param text the whole text of the packet to send */ public AdHocPacket(String text) { this.text = text; } public String toXML() { return text; } } /** * Listens for debug window popup dialog events. */ private class PopupListener extends MouseAdapter { JPopupMenu popup; PopupListener(JPopupMenu popupMenu) { popup = popupMenu; } public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } private class SelectionListener implements ListSelectionListener { JTable table; // It is necessary to keep the table since it is not possible // to determine the table from the event's source SelectionListener(JTable table) { this.table = table; } public void valueChanged(ListSelectionEvent e) { if (table.getSelectedRow() == -1) { // Clear the messageTextArea since there is none packet selected messageTextArea.setText(null); } else { // Set the detail of the packet in the messageTextArea messageTextArea.setText( (String) table.getModel().getValueAt(table.getSelectedRow(), 0)); // Scroll up to the top messageTextArea.setCaretPosition(0); } } } }
package co.shinetech.dto; import java.util.Arrays; /** * @author Robin * */ public class User implements Domain { private final long id; private String login; private char[] password; private Profile profile; public User(long id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public char[] getPassword() { return password; } public void setPassword(char[] password) { this.password = password; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } public long getPk() { return this.id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (id ^ (id >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id != other.id) return false; return true; } @Override public String toString() { return "User [id=" + id + ", login=" + login + ", password=" + Arrays.toString(password) + ", profile=" + profile + "]"; } }
package utask.logic.parser; import static utask.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static utask.logic.parser.CliSyntax.PREFIX_DEADLINE; import static utask.logic.parser.CliSyntax.PREFIX_DONE; import static utask.logic.parser.CliSyntax.PREFIX_FREQUENCY; import static utask.logic.parser.CliSyntax.PREFIX_NAME; import static utask.logic.parser.CliSyntax.PREFIX_TAG; import static utask.logic.parser.CliSyntax.PREFIX_TIMESTAMP; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import utask.commons.exceptions.IllegalValueException; import utask.logic.commands.Command; import utask.logic.commands.IncorrectCommand; import utask.logic.commands.UpdateCommand; import utask.model.tag.UniqueTagList; import utask.model.task.EditTaskDescriptor; /** * Parses input arguments and creates a new EditCommand object */ // @@author A0138423J public class EditCommandParser { /** * Parses the given {@code String} of arguments in the context of the * EditCommand and returns an EditCommand object for execution. */ public Command parse(String args) { assert args != null; ArgumentTokenizer argsTokenizer = new ArgumentTokenizer(PREFIX_NAME, PREFIX_DEADLINE, PREFIX_TIMESTAMP, PREFIX_FREQUENCY, PREFIX_TAG, PREFIX_DONE); argsTokenizer.tokenize(args); List<Optional<String>> preambleFields = ParserUtil .splitPreamble(argsTokenizer.getPreamble().orElse(""), 2); Optional<Integer> index = preambleFields.get(0) .flatMap(ParserUtil::parseIndex); if (!index.isPresent()) { return new IncorrectCommand(String.format( MESSAGE_INVALID_COMMAND_FORMAT, UpdateCommand.MESSAGE_USAGE)); } // creates list of int to store to indicate which attribute to remove // 0 : Deadline, 1 : Timestamp, 2 : Tags, 3 : Frequency ArrayList<String> attributesToRemove = new ArrayList<String>(); EditTaskDescriptor editTaskDescriptor = new EditTaskDescriptor(); try { editTaskDescriptor.setName( ParserUtil.parseName(argsTokenizer.getValue(PREFIX_NAME))); editTaskDescriptor.setDeadline(ParserUtil .parseDeadline(argsTokenizer.getValue(PREFIX_DEADLINE))); if (!argsTokenizer.tryGet(PREFIX_DEADLINE).isEmpty()) { if (argsTokenizer.tryGet(PREFIX_DEADLINE).equals("-")) { attributesToRemove.add("deadline"); } } editTaskDescriptor.setTimeStamp(ParserUtil .parseTimestamp(argsTokenizer.getValue(PREFIX_TIMESTAMP))); if (!argsTokenizer.tryGet(PREFIX_TIMESTAMP).isEmpty()) { if (argsTokenizer.tryGet(PREFIX_TIMESTAMP).equals("-")) { attributesToRemove.add("timestamp"); } } editTaskDescriptor.setTags(parseTagsForEdit( ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_TAG)))); if (!argsTokenizer.tryGet(PREFIX_TAG).isEmpty()) { if (argsTokenizer.tryGet(PREFIX_TAG).equals("-")) { attributesToRemove.add("tag"); } } editTaskDescriptor.setFrequency(ParserUtil .parseFrequency(argsTokenizer.getValue(PREFIX_FREQUENCY))); if (!argsTokenizer.tryGet(PREFIX_FREQUENCY).isEmpty()) { if (argsTokenizer.tryGet(PREFIX_FREQUENCY).equals("-")) { attributesToRemove.add("frequency"); } } editTaskDescriptor.setIsCompleted(ParserUtil .parseIsCompleted(argsTokenizer.getValue(PREFIX_DONE))); } catch (IllegalValueException ive) { System.out.println(ive.toString()); return new IncorrectCommand(ive.getMessage()); } if (!editTaskDescriptor.isAnyFieldEdited()) { return new IncorrectCommand(UpdateCommand.MESSAGE_NOT_EDITED); } return new UpdateCommand(index.get(), editTaskDescriptor, attributesToRemove); } /** * Parses {@code Collection<String> tags} into an * {@code Optional<UniqueTagList>} if {@code tags} is non-empty. If * {@code tags} contain only one element which is an empty string, it will * be parsed into a {@code Optional<UniqueTagList>} containing zero tags. */ private Optional<UniqueTagList> parseTagsForEdit(Collection<String> tags) throws IllegalValueException { assert tags != null; if (tags.isEmpty()) { return Optional.empty(); } Collection<String> tagSet = tags.size() == 1 && tags.contains("") ? Collections.emptySet() : tags; return Optional.of(ParserUtil.parseTags(tagSet)); } }
package client; // cc GetTryWithResourcesExample Example application retrieving data from HBase using a Java 7 construct import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Get; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import util.HBaseHelper; import java.io.IOException; public class GetTryWithResourcesExample { public static void main(String[] args) throws IOException { // vv GetTryWithResourcesExample Configuration conf = HBaseConfiguration.create(); // co GetTryWithResourcesExample-1-CreateConf Create the configuration. // ^^ GetTryWithResourcesExample HBaseHelper helper = HBaseHelper.getHelper(conf); if (!helper.existsTable("testtable")) { helper.createTable("testtable", "colfam1"); } // vv GetTryWithResourcesExample try ( Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("testtable")); // co GetTryWithResourcesExample-2-NewTable Instantiate a new table reference in "try" block. ) { Get get = new Get(Bytes.toBytes("row1")); get.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1")); Result result = table.get(get); byte[] val = result.getValue(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1")); System.out.println("Value: " + Bytes.toString(val)); } // co GetTryWithResourcesExample-3-Close No explicit close needed, Java will handle AutoClosable's. // ^^ GetTryWithResourcesExample helper.close(); } }
package ru.job4j.iterator.map; import java.util.Calendar; public class User { private String name; private int children; private Calendar birthday; User(String name, int children) { this.name = name; this.children = children; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + children; return result; } }
package edu.wustl.xipHost.caGrid; import java.io.FileNotFoundException; import java.io.IOException; import java.net.ConnectException; import java.rmi.RemoteException; import java.util.HashMap; import edu.wustl.xipHost.caGrid.GridLocation.Type; import edu.wustl.xipHost.dataModel.SearchResult; import gov.nih.nci.cagrid.cqlquery.CQLQuery; import gov.nih.nci.cagrid.data.MalformedQueryException; import gov.nih.nci.ivi.dicom.HashmapToCQLQuery; import gov.nih.nci.ivi.dicom.modelmap.ModelMap; import gov.nih.nci.ivi.dicom.modelmap.ModelMapException; import gov.nih.nci.ncia.domain.Series; import junit.framework.TestCase; /** * @author Jaroslaw Krych * */ public class QueryGridLocationTest extends TestCase implements GridSearchListener { GridLocation gridLoc = new GridLocation("http://ividemo.bmi.ohio-state.edu:8080/wsrf/services/cagrid/DICOMDataService", Type.DICOM, "DICOM", "OSU"); CQLQuery cqlQuery = null; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { //try to simulate gid in form of stub or mock object super.setUp(); /* Create CQL for grid query */ HashMap<String, String> queryHashMap = new HashMap<String, String>(); queryHashMap.put(HashmapToCQLQuery.TARGET_NAME_KEY, Series.class.getCanonicalName()); //queryHashMap.put(HashmapToCQLQuery.TARGET_NAME_KEY, Patient.class.getCanonicalName()); queryHashMap.put("gov.nih.nci.ncia.domain.Series.seriesInstanceUID", "1.3.6.1.4.1.9328.50.1.9263"); //queryHashMap.put("gov.nih.nci.ncia.domain.Patient.patientId", "E09615"); //queryHashMap.put("gov.nih.nci.ncia.domain.Patient.patientName", "E09615"); HashmapToCQLQuery h2cql; try { h2cql = new HashmapToCQLQuery(new ModelMap()); try { cqlQuery = h2cql.makeCQLQuery(queryHashMap); } catch (MalformedQueryException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ModelMapException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } //GridManagerImpl - query grid 1A - basic flow. //CQL statement and GridLocation are valid and network is on. public void testQueryGridLocation1A() throws org.apache.axis.types.URI.MalformedURIException, RemoteException, ConnectException { SearchResult result = null; GridQuery gridQuery = new GridQuery(cqlQuery, gridLoc, null, null); gridQuery.addGridSearchListener(this); Thread t = new Thread(gridQuery); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } result = gridQuery.getSearchResult(); //Check if return type is an instance of DicomSearchResult and is not null Boolean blnType = result instanceof SearchResult; //blnType will be false when result would be null assertTrue("Expected returned value should be CQLQueryResultsIterator but system did not define it this way.", blnType); } //GridManagerImpl - query grid 1B - alternative flow. //CQL statement is invalid and GridLocation is valid and network is on. public void testQueryGridLocation1B() throws org.apache.axis.types.URI.MalformedURIException, ConnectException { /* Create CQL for grid query */ HashMap<String, String> queryHashMap = new HashMap<String, String>(); if (queryHashMap.isEmpty()) { queryHashMap.put(HashmapToCQLQuery.TARGET_NAME_KEY, Series.class.getCanonicalName()); queryHashMap.put("gov.nih.nci.ncia.domain.Series.generalSeriesInstanceUID", "1.3.6.1.4.1.9328.50.1.9263"); //"gov.nih.nci.ncia.domain.Series.generalSeriesInstanceUID" is incorrect }else{ } HashmapToCQLQuery h2cql; try { h2cql = new HashmapToCQLQuery(new ModelMap()); try { cqlQuery = h2cql.makeCQLQuery(queryHashMap); } catch (MalformedQueryException e) { e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ModelMapException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } GridQuery gridQuery = new GridQuery(cqlQuery, gridLoc, null, null); gridQuery.addGridSearchListener(this); Thread t = new Thread(gridQuery); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } //assertNull("CQL statement was invalid. Returned result should be null but system did not define it this way.", result); fail("CQL statement was invalid but system failed to report an error."); } //GridManagerImpl - query grid 1C - alternative flow. //CQL statement and GridLocation are valid but network is off. public void testQueryGridLocation1C() { //simulate network problems //1. No connection //2. Connection broken fail(); } //GridManagerImpl - query grid 1D - alternative flow. //CQL statement is valid but GridLocation does not exist and network is on. public void testQueryGridLocation1D() throws RemoteException, ConnectException { gridLoc = new GridLocation("http: GridQuery gridQuery = new GridQuery(cqlQuery, gridLoc, null, null); gridQuery.addGridSearchListener(this); Thread t = new Thread(gridQuery); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } fail("Invalid GridLocation."); } //GridManagerImpl - query grid 1E - alternative flow. //CQL statement is null and GridLocation is valid. public void testQueryGridLocation1E() throws org.apache.axis.types.URI.MalformedURIException, ConnectException { GridQuery gridQuery = new GridQuery(null, gridLoc, null, null); gridQuery.addGridSearchListener(this); Thread t = new Thread(gridQuery); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } //assertNull("CQL statement was invalid. Returned result should be null but system did not define it this way.", result); fail("CQL statement is null but system failed to report an error."); } //GridManagerImpl - query grid 1F - alternative flow. //CQL statement is valid but GridLocation is null. public void testQueryGridLocation1F() throws org.apache.axis.types.URI.MalformedURIException, RemoteException, ConnectException { GridQuery gridQuery = new GridQuery(cqlQuery, null, null, null); gridQuery.addGridSearchListener(this); Thread t = new Thread(gridQuery); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } SearchResult result = gridQuery.getSearchResult(); assertNull("GridLocation was null. Returned value should be null but is not.", result); } //GridManagerImpl - query grid 1G - alternative flow. //CQL statement is valid and GridLocation is valid. Test if location desc is not null and not empty string. public void testQueryGridLocation1G() throws org.apache.axis.types.URI.MalformedURIException, RemoteException, ConnectException { GridQuery gridQuery = new GridQuery(cqlQuery, gridLoc, null, null); gridQuery.addGridSearchListener(this); Thread t = new Thread(gridQuery); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } SearchResult result = gridQuery.getSearchResult(); Boolean isLocDescValid = new Boolean(result.toString() != null && !result.toString().isEmpty()); assertTrue("Location description is missing in teh returned value.", isLocDescValid); } @Override public void searchResultAvailable(GridSearchEvent e) { // TODO Auto-generated method stub } @Override public void notifyException(String message) { // TODO Auto-generated method stub } }
package edu.cs4460.msd.visual.maps; import java.awt.Color; import java.util.Collection; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.marker.SimplePointMarker; import de.fhpotsdam.unfolding.utils.MapUtils; import de.fhpotsdam.unfolding.utils.ScreenPosition; import edu.cs4460.msd.backend.database.SongList; import edu.cs4460.msd.backend.genre.GenreFilter; import edu.cs4460.msd.backend.music.Artist; import edu.cs4460.msd.backend.utilities.SongListHelper; import edu.cs4460.msd.backend.visual_abstract.AbstractMap; import edu.cs4460.msd.visual.main.VisBase; public class ArtistLocationMap extends AbstractMap { private VisBase parent; private Collection<Artist> artists; private SongListHelper slh; private static final int EDGE = 10; private int x, y, width, height; private int maxArtistRadius = 30; private double scaleFactor; public ArtistLocationMap(VisBase p, SongList sl, int x, int y, int width, int height) { this.parent = p; this.x = x; this.y = y; this.width = width; this.height = height; artists = sl.getArtists(); slh = new SongListHelper(sl); int artistMax = slh.getMostSongsForArtist(); scaleFactor = maxArtistRadius / artistMax; map = new UnfoldingMap(parent, "detail", x, y, width, height); addArtistsAsMarkers(); MapUtils.createDefaultEventDispatcher(parent, map); } private void addArtistsAsMarkers() { for(Artist a: artists) { Location loc = new Location(a.getArtist_latitude(), a.getArtist_longitude()); SimplePointMarker spm = new SimplePointMarker(loc); } } public void updateFilter(GenreFilter filter) { } public void draw() { map.draw(); for(Artist a: artists) { if(filter == null || filter.artistConforms(a)) { Location loc = new Location(a.getArtist_latitude(), a.getArtist_longitude()); ScreenPosition pos = map.getScreenPosition(loc); double radiusD = (scaleFactor * slh.getSongsCountForArtist(a.getArtist_id())); int radius = (int) radiusD; Color c = getColorForRadius(radiusD); //parent.fill(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); parent.color(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha()); Color cLight = c.brighter(); parent.fill(cLight.getRed(), cLight.getGreen(), cLight.getBlue(), cLight.getAlpha()/2); if((x <= pos.x - radius && pos.x + radius <= x + width) && (y <= pos.y - radius && pos.y + radius <= y + height)) { parent.ellipse(pos.x, pos.y, radius, radius); } } } } private Color getColorForRadius(double radius) { Color out = null; double factor = maxArtistRadius / radius; if(factor > maxArtistRadius * 4/5) { out = new Color(237,248,251); } else if(factor > maxArtistRadius * 3/5) { out = new Color(178, 226, 226); } else if(factor > maxArtistRadius * 2/5) { out = new Color(102, 194, 164); } else if(factor > maxArtistRadius * 1/5) { out = new Color(44, 162, 95); } else if(factor >= 0) { out = new Color(0, 109, 44); } return out; } public void mouseMoved(float x, float y) { // Location location = map.getLocation(x, y); // x = location.x; // y = location.y; //String line = ""; for(Artist a: artists) { ScreenPosition pos = map.getScreenPosition(new Location(a.getArtist_latitude(), a.getArtist_longitude())); if(contains(x,y, pos.x, pos.y, EDGE)) { //line += a.getArtist_continent() + " " + a.getArtist_name() + "\n"; } // close if } // close for } // close mouseMoved }
package com.opengamma.util; import java.io.File; import java.io.InputStream; import org.apache.commons.io.IOUtils; import com.opengamma.OpenGammaRuntimeException; // NOTE kirk 2013-12-10 -- Before adding anything to this, check to see if // the functionality you require is in another class or project // (in particular IOUtils). /** * A collection of utility methods for working with files. */ public final class FileUtils { /** * A convenience reference to the java.io.tmpdir location. */ public static final File TEMP_DIR = new File(System.getProperty("java.io.tmpdir")); private FileUtils() { } public static File copyResourceToTempFile(InputStream resource) { return copyResourceToTempFile(null, resource); } public static File copyResourceToTempFile(InputStream resource, String fileName) { return copyResourceToTempFile((String) null, resource, fileName); } public static File copyResourceToTempFile(String subdirName, InputStream resource) { return copyResourceToTempFile(subdirName, resource, null); } public static File copyResourceToTempFile(String subdirName, InputStream resource, String fileName) { File tempDir = TEMP_DIR; if (!(subdirName == null)) { tempDir = new File(TEMP_DIR, subdirName); if (tempDir.exists()) { if (!tempDir.isDirectory()) { throw new IllegalStateException("" + tempDir + " already exists and is not a directory."); } } else { tempDir.mkdirs(); } } return copyResourceToTempFile(tempDir, resource, fileName); } public static File copyResourceToTempFile(File tempDir, InputStream resource, String fileName) { ArgumentChecker.notNull(resource, "resource"); File tempFile = null; if (fileName == null) { tempFile = new File(tempDir, "test-" + System.nanoTime()); } else { tempFile = new File(tempDir, fileName); } if (tempFile.exists()) { tempFile.delete(); } try { org.apache.commons.io.FileUtils.copyInputStreamToFile(resource, tempFile); IOUtils.closeQuietly(resource); } catch (Exception e) { throw new OpenGammaRuntimeException("Unable to copy resource to " + tempFile, e); } tempFile.deleteOnExit(); return tempFile; } }
package ch.epfl.sweng.project.Database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.location.Location; import java.util.ArrayList; import java.util.List; import ch.epfl.sweng.project.Model.CheckPoint; import ch.epfl.sweng.project.Model.Effort; import ch.epfl.sweng.project.Model.Run; import ch.epfl.sweng.project.Model.Track; public class DBHelper extends SQLiteOpenHelper { private SQLiteDatabase db; private static final String DATABASE_NAME = "efforts.db"; private static final String EFFORTS_TABLE_NAME = "efforts"; private static final String CHECKPOINTS_TABLE_NAME = "checkpoints"; public static final String[] EFFORTS_COLS = {"id", "name", "type", "checkpointsFromId", "checkpointsToId"}; public static final String[] CHECKPOINTS_COLS = {"id", "latitude", "longitude", "altitude", "time"}; public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); db = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { String createEffortsTableQuery = "CREATE TABLE " + EFFORTS_TABLE_NAME + " (" + EFFORTS_COLS[0] + " INTEGER PRIMARY KEY AUTOINCREMENT, " + EFFORTS_COLS[1] + " TEXT, " + EFFORTS_COLS[2] + " TEXT, "+ EFFORTS_COLS[3] + " INTEGER, " + EFFORTS_COLS[4] + " INTEGER)"; String createCheckpointsTableQuery = "CREATE TABLE " + CHECKPOINTS_TABLE_NAME + " (" + CHECKPOINTS_COLS[0] + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CHECKPOINTS_COLS[1] + " DOUBLE, " + CHECKPOINTS_COLS[2] + " DOUBLE, " + CHECKPOINTS_COLS[3] + " DOUBLE, " + CHECKPOINTS_COLS[4] + " INTEGER)"; db.execSQL(createEffortsTableQuery); db.execSQL(createCheckpointsTableQuery); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String dropEffortsTableQuery = "DROP TABLE IF EXISTS " + EFFORTS_TABLE_NAME; String dropCheckpointsTableQuery = "DROP TABLE IF EXISTS " + CHECKPOINTS_TABLE_NAME; db.execSQL(dropEffortsTableQuery); db.execSQL(dropCheckpointsTableQuery); onCreate(db); } public boolean insert(Effort effort) { //insert all checkpoints Track track = effort.getTrack(); List<CheckPoint> checkpoints = track.getCheckpoints(); long checkpointsFromId = -1; long checkpointsToId = -1; for (CheckPoint checkpoint : checkpoints) { checkpointsToId = insert(checkpoint); if (checkpointsToId == -1) { return false; } if (checkpointsFromId == -1) { checkpointsFromId = checkpointsToId; } } //insert Effort String name = effort.getName(); String type = "run"; ContentValues effortContentValues = new ContentValues(); effortContentValues.put(EFFORTS_COLS[1], name); effortContentValues.put(EFFORTS_COLS[2], type); effortContentValues.put(EFFORTS_COLS[3], checkpointsFromId); effortContentValues.put(EFFORTS_COLS[4], checkpointsToId); long insertedEffort = db.insert(EFFORTS_TABLE_NAME, null, effortContentValues); return insertedEffort != -1; } /** * Inserts a checkpoint in the checkpoints table * @param checkpoint the checkpoint to insert * @return the id of the inserted row */ private long insert(CheckPoint checkpoint) { ContentValues contentValues = new ContentValues(); contentValues.put(CHECKPOINTS_COLS[1], checkpoint.getLatitude()); contentValues.put(CHECKPOINTS_COLS[2], checkpoint.getLongitude()); contentValues.put(CHECKPOINTS_COLS[3], checkpoint.getAltitude()); contentValues.put(CHECKPOINTS_COLS[4], checkpoint.getTime()); return db.insert(CHECKPOINTS_TABLE_NAME, null, contentValues); } /** * Delete an effort given its id * @param id the id of the effort to delete * @return true if the deletion was succesfull */ private boolean deleteEffort(long id) { //also needs to delete checkpoints return db.delete(EFFORTS_TABLE_NAME, EFFORTS_COLS[0] + " = " + id, null) > 0; } public List<Run> fetchAllEfforts() { Cursor result = db.query(EFFORTS_TABLE_NAME, EFFORTS_COLS, null, null, null, null, null); List<Run> efforts = new ArrayList<>(); if (result.getCount() > 0) { while (result.moveToNext()) { //long id = result.getLong(0); String name = result.getString(1); //String type = result.getString(2); long fromId = result.getLong(3); long toId = result.getLong(4); Track track = fetchTrack(fromId, toId); Run run = new Run(name); run.setTrack(track); efforts.add(run); } } result.close(); return efforts; } private Track fetchTrack(long fromId, long toId) { System.out.println("_____ String selection = CHECKPOINTS_COLS[0] + " >= " + fromId + " AND " + CHECKPOINTS_COLS[0] + " <= " + toId; Cursor result = db.query(CHECKPOINTS_TABLE_NAME, CHECKPOINTS_COLS, selection, null, null, null, null); Track track = new Track(); if (result.getCount() > 0) { while (result.moveToNext()) { Location location = new Location(""); location.setLatitude(result.getDouble(1)); location.setLongitude(result.getDouble(2)); location.setAltitude(result.getDouble(3)); location.setTime(result.getLong(4)); CheckPoint checkpoint = new CheckPoint(location); boolean isAdded = track.add(checkpoint); System.out.println(isAdded + " " + track.getTotalCheckPoints()); } } result.close(); return track; } }
package cn.ben.tvdemo.mainpage; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import cn.ben.tvdemo.R; import cn.ben.tvdemo.favorite.FavoriteFragment; import cn.ben.tvdemo.favorite.FavoritePresenter; import cn.ben.tvdemo.settings.SettingsFragment; import cn.ben.tvdemo.settings.SettingsPresenter; import cn.ben.tvdemo.shows.ShowsFragment; import cn.ben.tvdemo.shows.ShowsPresenter; import static cn.ben.tvdemo.mainpage.MainPageActivity.FragmentPosition.FAV_FRAGMENT_POS; import static cn.ben.tvdemo.mainpage.MainPageActivity.FragmentPosition.SETTINGS_FRAGMENT_POS; import static cn.ben.tvdemo.mainpage.MainPageActivity.FragmentPosition.SHOWS_FRAGMENT_POS; public class MainPageActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener, ViewPager.OnPageChangeListener { private ViewPager mViewPager; private BottomNavigationView mBottomNavigationView; private int prevSelectedMenuItemPos = -1; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == prevSelectedMenuItemPos) return; if (prevSelectedMenuItemPos >= 0 && prevSelectedMenuItemPos < mBottomNavigationView.getMenu().size()) mBottomNavigationView.getMenu().getItem(prevSelectedMenuItemPos).setChecked(false); if (position >= 0 && position < mBottomNavigationView.getMenu().size()) mBottomNavigationView.getMenu().getItem(position).setChecked(true); prevSelectedMenuItemPos = position; } @Override public void onPageScrollStateChanged(int state) { } enum FragmentPosition { SHOWS_FRAGMENT_POS, FAV_FRAGMENT_POS, SETTINGS_FRAGMENT_POS } private ShowsPresenter mShowsPresenter; private FavoritePresenter mFavoritePresenter; private SettingsPresenter mSettingsPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_page_act); setupActionBar(); setupViewPager(); bindBottomNavigationWithPager(); if (savedInstanceState != null) { // TODO: 2017/2/19 load previously saved state } } private void setupActionBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.mToolbar); setSupportActionBar(toolbar); } private void bindBottomNavigationWithPager() { mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav); mBottomNavigationView.setOnNavigationItemSelectedListener(this); } private void setupViewPager() { mViewPager = (ViewPager) findViewById(R.id.viewpager); MainPagePagerAdapter viewPagerAdapter = new MainPagePagerAdapter(getSupportFragmentManager()); ShowsFragment showsFragment = (ShowsFragment) viewPagerAdapter.getItem(SHOWS_FRAGMENT_POS); if (showsFragment == null) { showsFragment = ShowsFragment.newInstance(); viewPagerAdapter.setFragment(SHOWS_FRAGMENT_POS, showsFragment); } mShowsPresenter = new ShowsPresenter(showsFragment); // TODO: 2017/2/19 FavoriteFragment favoriteFragment = (FavoriteFragment) viewPagerAdapter.getItem(FAV_FRAGMENT_POS); if (favoriteFragment == null) { favoriteFragment = FavoriteFragment.newInstance(); viewPagerAdapter.setFragment(FAV_FRAGMENT_POS, favoriteFragment); } mFavoritePresenter = new FavoritePresenter(favoriteFragment); // TODO: 2017/2/19 SettingsFragment settingsFragment = (SettingsFragment) viewPagerAdapter.getItem(SETTINGS_FRAGMENT_POS); if (settingsFragment == null) { settingsFragment = SettingsFragment.newInstance(); viewPagerAdapter.setFragment(SETTINGS_FRAGMENT_POS, settingsFragment); } mSettingsPresenter = new SettingsPresenter(settingsFragment); // TODO: 2017/2/19 mViewPager.setAdapter(viewPagerAdapter); mViewPager.addOnPageChangeListener(this); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_shows: mViewPager.setCurrentItem(SHOWS_FRAGMENT_POS.ordinal()); break; case R.id.menu_item_fav: mViewPager.setCurrentItem(FAV_FRAGMENT_POS.ordinal()); break; case R.id.menu_item_settings: mViewPager.setCurrentItem(SETTINGS_FRAGMENT_POS.ordinal()); break; default: break; } return true; } }
package com.bedrock.padder.helper; import android.app.Activity; import android.app.ActivityManager; import android.app.Dialog; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.media.SoundPool; import android.os.Build; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SwitchCompat; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.VideoView; import com.bedrock.padder.R; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.NativeExpressAdView; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import static android.content.Context.MODE_PRIVATE; public class WindowService { public static final String APPLICATION_ID = "com.bedrock.padder"; public void setNavigationBar(int colorId, Activity activity) { if (Build.VERSION.SDK_INT >= 16) { if (colorId == R.color.transparent) { activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Window w = activity.getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } Log.i("WindowService", "Transparent navigation bar color applied."); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().setNavigationBarColor(activity.getResources().getColor(colorId)); Log.i("WindowService", "Navigation bar color applied."); } } } else { Log.i("WindowService", "API doesn't match requirement. (API >= 16)"); } } public int getNavigationBar(final int id, final Activity activity) { /* Must be a parent view */ final SharedPreferences prefs = activity.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); final int[] navBarHeight = {-1}; Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { View view = activity.findViewById(id); Rect rect = new Rect(); view.getGlobalVisibleRect(rect); Log.i("Navigation Bar Height", String.valueOf(getWindowHeightPx(activity) + " - " + String.valueOf(rect.bottom) + " = " + String.valueOf(getWindowHeightPx(activity) - rect.bottom))); navBarHeight[0] = getWindowHeightPx(activity) - rect.bottom; prefs.edit().putInt("navBarPX", navBarHeight[0]).apply(); Log.i("SharedPrefs", "navBarPX = " + String.valueOf(prefs.getInt("navBarPX", 144))); } }, 100); return navBarHeight[0]; } public int getNavigationBarFromPrefs(Activity activity) { int navigationHeight; SharedPreferences sharedPreferences = activity.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); navigationHeight = sharedPreferences.getInt("navBarPX", 144); if (navigationHeight >= 540 || navigationHeight < 0) { // something gone wrong navigationHeight = 144; } return navigationHeight; } public void setStatusBar(int colorId, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { Window window = activity.getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(ContextCompat.getColor(activity, colorId)); Log.i("WindowService", "Status bar color applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public int getStatusBar(final int id, final Activity activity) { /* Must be a parent view */ final SharedPreferences prefs = activity.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); final int[] statBarHeight = {-1}; int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { statBarHeight[0] = activity.getResources().getDimensionPixelSize(resourceId); } prefs.edit().putInt("statBarPX", statBarHeight[0]).apply(); Log.i("SharedPrefs", "statBarPX = " + String.valueOf(prefs.getInt("statBarPX", 72))); // Handler handler = new Handler(); // handler.postDelayed(new Runnable() { // @Override // public void run() { //// Rect rectangle = new Rect(); //// Window window = activity.getWindow(); //// window.getDecorView().getWindowVisibleDisplayFrame(rectangle); //// int statusBar = rectangle.top; //// Log.i("Status Bar Height", String.valueOf(statusBar)); //// statBarHeight[0] = statusBar; //// View view = activity.findViewById(id); //// Rect rect = new Rect(); //// view.getGlobalVisibleRect(rect); //// Log.i("Status Bar Height", String.valueOf(rect.top)); //// statBarHeight[0] = rect.top; return statBarHeight[0]; } public int getStatusBarFromPrefs(Activity activity) { int statusHeight; SharedPreferences sharedPreferences = activity.getSharedPreferences(APPLICATION_ID, MODE_PRIVATE); statusHeight = sharedPreferences.getInt("statBarPX", 72); if (statusHeight >= 240 || statusHeight <= 0) { // something gone wrong statusHeight = 72; } return statusHeight; } public void setVisible(final int viewId, final int delay, final Activity activity){ final View view = activity.findViewById(viewId); if (delay > 0) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { view.setVisibility(View.VISIBLE); } }, delay); } else { view.setVisibility(View.VISIBLE); } } public void setInvisible(final int viewId, final int delay, final Activity activity){ final View view = activity.findViewById(viewId); if (delay > 0) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { view.setVisibility(View.INVISIBLE); } }, delay); } else { view.setVisibility(View.INVISIBLE); } } public void setGone(final int viewId, final int delay, final Activity activity){ final View view = activity.findViewById(viewId); if (delay > 0) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { view.setVisibility(View.GONE); } }, delay); } else { view.setVisibility(View.GONE); } } public void setActionBarBack(final boolean backEnable, final Runnable back, final Activity activity) { View backLayout = activity.findViewById(R.id.actionbar_back_layout); View backButton = activity.findViewById(R.id.actionbar_back); if (backEnable == true) { backLayout.setVisibility(View.VISIBLE); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { back.run(); } }); } else { backLayout.setVisibility(View.GONE); } } public void setRecentColor(int titleId, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { if (titleId == 0) { // Default app name titleId = R.string.app_name; } Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher); ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( activity.getResources().getString(titleId), icon, activity.getResources().getColor(R.color.colorPrimary)); activity.setTaskDescription(taskDesc); Log.i("WindowService", "TaskDescription applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public void setRecentColor(int titleId, int color, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { if (titleId == 0) { // Default app name titleId = R.string.app_name; } Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher); // color id - color try { ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( activity.getResources().getString(titleId), icon, activity.getResources().getColor(color)); activity.setTaskDescription(taskDesc); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( activity.getResources().getString(titleId), icon, color); activity.setTaskDescription(taskDesc); } Log.i("WindowService", "TaskDescription applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public void setRecentColor(int titleId, int iconId, int color, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { if (titleId == 0) { // Default app name titleId = R.string.app_name; } Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), iconId); // color id - color try { ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( activity.getResources().getString(titleId), icon, activity.getResources().getColor(color)); activity.setTaskDescription(taskDesc); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( activity.getResources().getString(titleId), icon, color); activity.setTaskDescription(taskDesc); } Log.i("WindowService", "TaskDescription applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public void setRecentColor(String title, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { if (title == null) { // Default app name title = activity.getResources().getString(R.string.app_name); } Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher); ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( title, icon, activity.getResources().getColor(R.color.colorPrimary)); activity.setTaskDescription(taskDesc); Log.i("WindowService", "TaskDescription applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public void setRecentColor(String title, int color, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { if (title == null) { // Default app name title = activity.getResources().getString(R.string.app_name); } Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_launcher); // color id - color try { ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( title, icon, activity.getResources().getColor(color)); activity.setTaskDescription(taskDesc); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription( title, icon, color); activity.setTaskDescription(taskDesc); } Log.i("WindowService", "TaskDescription applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public void setRecentColor(String title, int iconId, int color, Activity activity) { if (Build.VERSION.SDK_INT >= 21) { if (title == null) { // Default app name title = activity.getResources().getString(R.string.app_name); } Bitmap icon = BitmapFactory.decodeResource(activity.getResources(), iconId); // color id - color try { ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription(title, icon, activity.getResources().getColor(color)); activity.setTaskDescription(taskDesc); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); ActivityManager.TaskDescription taskDesc = new ActivityManager.TaskDescription(title, icon, color); activity.setTaskDescription(taskDesc); } Log.i("WindowService", "TaskDescription applied."); } else { Log.i("WindowService", "API doesn't match requirement. (API >= 21)"); } } public void setViewBackgroundColor(int viewId, int colorId, Activity activity) { try { getView(viewId, activity).setBackgroundColor(activity.getResources().getColor(colorId)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); getView(viewId, activity).setBackgroundColor(colorId); } } public void setViewBackgroundColor(int viewId, int colorId, Activity activity, View view) { try { getView(viewId, view).setBackgroundColor(activity.getResources().getColor(colorId)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); getView(viewId, view).setBackgroundColor(colorId); } } public void hideKeyboard(Activity activity) { Log.i("HideKeyboard", "Called"); try { InputMethodManager imm = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } catch (NullPointerException e) { Log.i("HideKeyboard", "NullPointer"); View view = activity.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } } } public int getWindowHeightPx(Activity activity) { Display display = activity.getWindowManager().getDefaultDisplay(); int realHeight; if (Build.VERSION.SDK_INT >= 17) { //new pleasant way to get real metrics DisplayMetrics realMetrics = new DisplayMetrics(); display.getRealMetrics(realMetrics); realHeight = realMetrics.heightPixels; } else if (Build.VERSION.SDK_INT >= 14) { //reflection for this weird in-between time try { Method mGetRawH = Display.class.getMethod("getRawHeight"); realHeight = (Integer) mGetRawH.invoke(display); } catch (Exception e) { //this may not be 100% accurate, but it's all we've got realHeight = display.getHeight(); Log.e("Display Info", "Couldn't use reflection to get the real display metrics."); } } else { //This should be close, as lower API devices should not have window navigation bars realHeight = display.getHeight(); } return realHeight; } public int getWindowWidthPx(Activity activity) { Display display = activity.getWindowManager().getDefaultDisplay(); int realWidth; if (Build.VERSION.SDK_INT >= 17) { //new pleasant way to get real metrics DisplayMetrics realMetrics = new DisplayMetrics(); display.getRealMetrics(realMetrics); realWidth = realMetrics.widthPixels; } else if (Build.VERSION.SDK_INT >= 14) { //reflection for this weird in-between time try { Method mGetRawH = Display.class.getMethod("getRawWidth"); realWidth = (Integer) mGetRawH.invoke(display); } catch (Exception e) { //this may not be 100% accurate, but it's all we've got realWidth = display.getWidth(); Log.e("Display Info", "Couldn't use reflection to get the real display metrics."); } } else { //This should be close, as lower API devices should not have window navigation bars realWidth = display.getWidth(); } return realWidth; } public int getWindowHypot(Activity activity) { int hypot = (int) Math.hypot(getWindowWidthPx(activity), getWindowHeightPx(activity)) + 200; return hypot; } public int convertPXtoDP(int px, Activity activity) { float scale = activity.getResources().getDisplayMetrics().density; return (int) (px / scale); } public int convertDPtoPX(int dp, Activity activity) { float scale = activity.getResources().getDisplayMetrics().density; return (int) (dp * scale); } public Rect getRect(int id, Activity activity) { View view = activity.findViewById(id); Rect rect = new Rect(); view.getGlobalVisibleRect(rect); return rect; } public View getView(int id, Activity activity) { return activity.findViewById(id); } public View getView(int id, View view) { return view.findViewById(id); } public ProgressBar getProgressBar(int id, Activity activity) { return (ProgressBar) activity.findViewById(id); } public Button getButton(int id, Activity activity) { return (Button) activity.findViewById(id); } public Toolbar getToolbar(int id, Activity activity) { return (Toolbar) activity.findViewById(id); } public Toolbar getToolbar(int id, View view) { return (Toolbar) view.findViewById(id); } public ToggleButton getToggleButton(int id, Activity activity) { return (ToggleButton) activity.findViewById(id); } public SwitchCompat getSwitchCompat(int id, Activity activity) { return (SwitchCompat) activity.findViewById(id); } public SwitchCompat getSwitchCompat(int id, View view) { return (SwitchCompat) view.findViewById(id); } public ImageView getImageView(int id, Activity activity) { return (ImageView) activity.findViewById(id); } public ImageView getImageView(int id, View view) { return (ImageView) view.findViewById(id); } public TextView getTextView(int id, Activity activity) { return (TextView) activity.findViewById(id); } public TextView getTextView(int id, View view) { return (TextView) view.findViewById(id); } public AdView getAdView(int id, Activity activity) { return (AdView) activity.findViewById(id); } public NativeExpressAdView getNativeAdView(int id, Activity activity) { return (NativeExpressAdView) activity.findViewById(id); } public RelativeLayout getRelativeLayout(int id, Activity activity) { return (RelativeLayout) activity.findViewById(id); } public LinearLayout getLinearLayout(int id, Activity activity) { return (LinearLayout) activity.findViewById(id); } public CardView getCardView(int id, Activity activity) { return (CardView) activity.findViewById(id); } public VideoView getVideoView(int id, Activity activity) { return (VideoView) activity.findViewById(id); } public View getViewDialog(int id, Dialog dialog) { return dialog.findViewById(id); } public RecyclerView getRecyclerView(int id, Activity activity) { return (RecyclerView) activity.findViewById(id); } public int getBackgroundColor(int id, Activity activity) { View view = getView(id, activity); Drawable drawable = view.getBackground(); if (drawable instanceof ColorDrawable) { ColorDrawable colorDrawable = (ColorDrawable) drawable; if (Build.VERSION.SDK_INT >= 11) { return colorDrawable.getColor(); } try { Field field = colorDrawable.getClass().getDeclaredField("mState"); field.setAccessible(true); Object object = field.get(colorDrawable); field = object.getClass().getDeclaredField("mUseColor"); field.setAccessible(true); return field.getInt(object); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return 0; } public int getId(String id) { try { Class res = R.id.class; Field field = res.getField(id); return field.getInt(null); } catch (Exception e) { Log.e("getId", "Failure to get id.", e); return -1; } } public int getColorId(String id) { try { Class res = R.color.class; Field field = res.getField(id); return field.getInt(null); } catch (Exception e) { Log.e("getColorId", "Failure to get color id.", e); return -1; } } public int getColorFromString(String colorString) { return Color.parseColor(colorString); } public int getStringId(String id) { try { Class res = R.string.class; Field field = res.getField(id); return field.getInt(null); } catch (Exception e) { Log.e("getStringId", "Failure to get string id.", e); return -1; } } public String getStringFromId(String id, Activity activity) { try { Class res = R.string.class; Field field = res.getField(id); return activity.getResources().getString(field.getInt(null)); } catch (Exception e) { Log.e("getStringFromId", "Failure to get string id.", e); return null; } } public int getDrawableId(String id) { try { Class res = R.drawable.class; Field field = res.getField(id); return field.getInt(null); } catch (Exception e) { Log.e("getDrawableId", "Failure to get drawable id.", e); return -1; } } public int getRawId(String id) { //return activity.getResources().getIdentifier(id, "raw", activity.getPackageName()); try { Class res = R.raw.class; Field field = res.getField(id); return field.getInt(null); } catch (Exception e) { Log.e("getRawId", "Failure to get raw id.", e); return -1; } } // public Z getZ(int id, Activity activity) { // Z z = (Z) activity.findViewById(id); // return z; public void setMarginRelativePX(int id, int left, int top, int right, int bottom, Activity activity) { View v = activity.findViewById(id); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v.getLayoutParams(); params.setMargins(left, top, right, bottom); v.setLayoutParams(params); } public void setMarginRelativeDP(int id, int left, int top, int right, int bottom, Activity activity) { View v = activity.findViewById(id); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v.getLayoutParams(); params.setMargins( convertDPtoPX(left, activity), convertDPtoPX(top, activity), convertDPtoPX(right, activity), convertDPtoPX(bottom, activity)); v.setLayoutParams(params); } public void setMarginLinearPX(int id, int left, int top, int right, int bottom, Activity activity) { View v = activity.findViewById(id); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams(); params.setMargins(left, top, right, bottom); v.setLayoutParams(params); } public void setMarginLinearDP(int id, int left, int top, int right, int bottom, Activity activity) { View v = activity.findViewById(id); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams(); params.setMargins( convertDPtoPX(left, activity), convertDPtoPX(top, activity), convertDPtoPX(right, activity), convertDPtoPX(bottom, activity)); v.setLayoutParams(params); } public void setOnTouch(int id, final Runnable touchDown, final Runnable touchUp, Activity activity) { View view = activity.findViewById(id); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { touchDown.run(); } if (event.getAction() == MotionEvent.ACTION_UP) { touchUp.run(); } return false; } }); } public void setOnTouchColor(int id, final int colorDown, final int colorUp, final Activity activity) { final View view = activity.findViewById(id); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { try { view.setBackgroundColor(activity.getResources().getColor(colorDown)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); view.setBackgroundColor(colorDown); } } if (event.getAction() == MotionEvent.ACTION_UP) { view.setBackgroundColor(activity.getResources().getColor(colorUp)); } return false; } }); } public void setOnTouchSoundPattern(int id, final int pattern[][], final int colorDown, final int colorUp, final SoundPool sp, final int soundId[], final int length, final Activity activity) { final View view = activity.findViewById(id); final int idnum[] = {0}; switch (id) { case R.id.btn11: idnum[0] = 0; break; case R.id.btn12: idnum[0] = 1; break; case R.id.btn13: idnum[0] = 2; break; case R.id.btn14: idnum[0] = 3; break; case R.id.btn21: idnum[0] = 4; break; case R.id.btn22: idnum[0] = 5; break; case R.id.btn23: idnum[0] = 6; break; case R.id.btn24: idnum[0] = 7; break; case R.id.btn31: idnum[0] = 8; break; case R.id.btn32: idnum[0] = 9; break; case R.id.btn33: idnum[0] = 10; break; case R.id.btn34: idnum[0] = 11; break; case R.id.btn41: idnum[0] = 12; break; case R.id.btn42: idnum[0] = 13; break; case R.id.btn43: idnum[0] = 14; break; case R.id.btn44: idnum[0] = 15; break; } view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { try { view.setBackgroundColor(activity.getResources().getColor(colorDown)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); view.setBackgroundColor(colorDown); } for (int i = 0; i < pattern[idnum[0]].length; i++) { try { getView(pattern[idnum[0]][i], activity).setBackgroundColor(activity.getResources().getColor(colorDown)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); getView(pattern[idnum[0]][i], activity).setBackgroundColor(colorDown); } } if (soundId.length == 1) { sp.play(soundId[0], 1, 1, 1, 0, 1f); } else { for (int i = 0; i < length; i++) { setSoundPoolDelay(sp, soundId, i, i * 5000); } } } if (event.getAction() == MotionEvent.ACTION_UP) { view.setBackgroundColor(activity.getResources().getColor(colorUp)); for (int i = 0; i < pattern[idnum[0]].length; i++) { getView(pattern[idnum[0]][i], activity).setBackgroundColor(activity.getResources().getColor(colorUp)); } } return false; } }); } private ArrayList<Integer> loopStreamIds = new ArrayList<>(); private void addLoopStreamId(Integer id) { Log.d("addLoopStreamId", "added " + id); loopStreamIds.add(id); } private void removeLoopStreamId(Integer id) { Log.d("removeLoopStreamId", "removed " + id); loopStreamIds.remove(id); } public void clearLoopStreamId() { Log.d("clearLoopStreamId", "cleared"); loopStreamIds.clear(); } public Integer[] getLoopStreamIds() { Log.d("getLoopStreamIds", "length = " + loopStreamIds.size()); return loopStreamIds.toArray(new Integer[loopStreamIds.size()]); } public void setPadColor(View pad, int color, Activity activity) { try { pad.setBackgroundColor(activity.getResources().getColor(color)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); pad.setBackgroundColor(color); } } public void setPadColor(int padId, int color, Activity activity) { View pad = getView(padId, activity); try { pad.setBackgroundColor(activity.getResources().getColor(color)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); pad.setBackgroundColor(color); } } private int getButtonId(int padId) { switch (padId) { case R.id.btn00: return -1; case R.id.btn11: return 0; case R.id.btn12: return 1; case R.id.btn13: return 2; case R.id.btn14: return 3; case R.id.btn21: return 4; case R.id.btn22: return 5; case R.id.btn23: return 6; case R.id.btn24: return 7; case R.id.btn31: return 8; case R.id.btn32: return 9; case R.id.btn33: return 10; case R.id.btn34: return 11; case R.id.btn41: return 12; case R.id.btn42: return 13; case R.id.btn43: return 14; case R.id.btn44: return 15; default: return -1; } } public void setOnTouchSound(final int padId, final int colorDown, final int colorUp, final SoundPool sp, final int spid[], final Activity activity) { // Normal final View pad = activity.findViewById(padId); final int streamId[] = {0}; pad.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // Pressed streamId[0] = sp.play(spid[0], 1, 1, 1, -1, 1); setPadColor(pad, colorDown, activity); Log.d("TouchListener", "TouchDown"); } else if (event.getAction() == MotionEvent.ACTION_UP) { // Released sp.stop(streamId[0]); setPadColor(pad, colorUp, activity); Log.d("TouchListener", "TouchUp"); } return false; } }); } public void setOnTouchSound(final int padId, final int colorDown, final int colorUp, final SoundPool sp, final int spid[], final int patternScheme[][][], final Activity activity) { // Normal Pattern final int btnId[] = {getButtonId(padId)}; final View pad = activity.findViewById(padId); final int streamId[] = {0}; pad.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // Pressed streamId[0] = sp.play(spid[0], 1, 1, 1, -1, 1); setPadColor(pad, colorDown, activity); setButtonPattern(patternScheme, btnId[0], colorDown, colorUp, activity); Log.d("TouchListener", "TouchDown"); } else if (event.getAction() == MotionEvent.ACTION_UP) { // Released sp.stop(streamId[0]); setPadColor(pad, colorUp, activity); setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); Log.d("TouchListener", "TouchUp"); } return false; } }); } public void setOnGestureSound(final int padId, final int colorDown, final int colorUp, final SoundPool sp, final int spid[], final Activity activity) { // Gesture final boolean isLoopEnabled[] = {false}; final View pad = activity.findViewById(padId); final int streamId[] = {0}; final Handler buttonDelay = new Handler(); final Runnable clearPad = new Runnable() { @Override public void run() { if (getBackgroundColor(padId, activity) != colorDown) { setPadColor(pad, colorUp, activity); } } }; pad.setOnTouchListener(new OnSwipeTouchListener(activity) { @Override public void onTouch() { setPadColor(pad, colorDown, activity); if (isLoopEnabled[0] == false) { buttonDelay.postDelayed(clearPad, 500); } } @Override public void onClick() { sp.play(spid[0], 1, 1, 1, 0, 1); if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); } Log.d("TouchListener", "Click"); } @Override public void onDoubleClick() { sp.play(spid[0], 1, 1, 1, 0, 1); Handler backgroundChangeHandler = new Handler(); backgroundChangeHandler.postDelayed(new Runnable() { @Override public void run() { if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } } }, 10); Log.d("TouchListener", "Double Click"); } @Override public void onSingleClickConfirmed() { if (isLoopEnabled[0] == false) { pad.setBackgroundColor(activity.getResources().getColor(colorUp)); } Log.d("TouchListener", "SingleClickConfirmed"); } @Override public void onSwipeUp() { if (spid[1] != 0) { sp.play(spid[1], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } Log.d("TouchListener", "SwipeUp"); } @Override public void onSwipeRight() { if (spid[2] != 0) { sp.play(spid[2], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } Log.d("TouchListener", "SwipeRight"); } @Override public void onSwipeDown() { if (spid[3] != 0) { sp.play(spid[3], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } Log.d("TouchListener", "SwipeDown"); } @Override public void onSwipeLeft() { if (spid[4] != 0) { sp.play(spid[4], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } Log.d("TouchListener", "SwipeLeft"); } @Override public void onLongClick() { if (isLoopEnabled[0] == false) { streamId[0] = sp.play(spid[0], 1, 1, 1, -1, 1); // add item to arraylist to reset loop sounds on deck change addLoopStreamId(streamId[0]); isLoopEnabled[0] = true; setPadColor(pad, colorDown, activity); Log.d("TouchListener", "LongClick, loop on"); } else { sp.stop(streamId[0]); removeLoopStreamId(streamId[0]); isLoopEnabled[0] = false; setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); Log.d("TouchListener", "LongClick, loop off"); } } }); } public void setOnGestureSound(final int padId, final int colorDown, final int colorUp, final SoundPool sp, final int spid[], final int patternScheme[][][], final Activity activity) { // Gesture Pattern final int btnId[] = {getButtonId(padId)}; final boolean isLoopEnabled[] = {false}; final View pad = activity.findViewById(padId); final int streamId[] = {0}; final Handler buttonDelay = new Handler(); final Runnable clearPad = new Runnable() { @Override public void run() { if (getBackgroundColor(padId, activity) != colorDown) { setPadColor(pad, colorUp, activity); } } }; pad.setOnTouchListener(new OnSwipeTouchListener(activity) { @Override public void onTouch() { setPadColor(pad, colorDown, activity); setButtonPattern(patternScheme, btnId[0], colorDown, colorUp, activity); if (isLoopEnabled[0] == false) { buttonDelay.postDelayed(clearPad, 500); } } @Override public void onClick() { sp.play(spid[0], 1, 1, 1, 0, 1); if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); Log.d("TouchListener", "Click"); } @Override public void onDoubleClick() { sp.play(spid[0], 1, 1, 1, 0, 1); Handler backgroundChangeHandler = new Handler(); backgroundChangeHandler.postDelayed(new Runnable() { @Override public void run() { if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); } }, 10); Log.d("TouchListener", "Double Click"); } @Override public void onSwipeUp() { if (spid[1] != 0) { sp.play(spid[1], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); Log.d("TouchListener", "SwipeUp"); } @Override public void onSwipeRight() { if (spid[2] != 0) { sp.play(spid[2], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); Log.d("TouchListener", "SwipeRight"); } @Override public void onSwipeDown() { if (spid[3] != 0) { sp.play(spid[3], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); Log.d("TouchListener", "SwipeDown"); } @Override public void onSwipeLeft() { if (spid[4] != 0) { sp.play(spid[4], 1, 1, 1, 0, 1); } else { sp.play(spid[0], 1, 1, 1, 0, 1); } if (isLoopEnabled[0] == false) { setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); Log.d("TouchListener", "SwipeLeft"); } @Override public void onLongClick() { //pad.setBackgroundColor(activity.getResources().getColor(colorUp)); buttonDelay.removeCallbacks(clearPad); if (isLoopEnabled[0] == false) { streamId[0] = sp.play(spid[0], 1, 1, 1, -1, 1); // add item to arraylist to reset loop sounds on deck change addLoopStreamId(streamId[0]); isLoopEnabled[0] = true; setPadColor(pad, colorDown, activity); Log.d("TouchListener", "LongClick, loop on"); } else { sp.stop(streamId[0]); removeLoopStreamId(streamId[0]); isLoopEnabled[0] = false; setPadColor(pad, colorUp, activity); buttonDelay.postDelayed(clearPad, 500); Log.d("TouchListener", "LongClick, loop off"); } setButtonPatternDefault(patternScheme, btnId[0], colorUp, activity); } }); } // TODO NEXT UPDATE check algorithm // void setButtonPattern(int patternScheme[][], int btnId, int colorDown, int colorUp, int mode, Activity activity) { // boolean wasAlreadyOn[] = { // false, false, false, false, // false, false, false, false, // false, false, false, false, // false, false, false, false // if (mode == 1) { // // button pressed (down) // for (int i = 0; i < buttonIds.length; i++) { // if (getBackgroundColor(buttonIds[btnId], activity) == colorDown) { // wasAlreadyOn[btnId] = true; // for (int i = 0; i < patternScheme[btnId].length; i++) { // try { // getView(patternScheme[btnId][i], activity).setBackgroundColor(activity.getResources().getColor(colorDown)); // } catch (Resources.NotFoundException e) { // Log.i("NotFoundException", "Handling with normal value"); // getView(patternScheme[btnId][i], activity).setBackgroundColor(colorDown); // } else if (mode == 0) { // // button clicked (up) // for (int i = 0; i < patternScheme[btnId].length; i++) { // if (wasAlreadyOn[btnId] == false) { // try { // getView(patternScheme[btnId][i], activity).setBackgroundColor(activity.getResources().getColor(colorUp)); // } catch (Resources.NotFoundException e) { // Log.i("NotFoundException", "Handling with normal value"); // getView(patternScheme[btnId][i], activity).setBackgroundColor(colorUp); // wasAlreadyOn[btnId] = true; // } else { // Log.d("NotFoundException", "Wrong touch mode"); private void setButtonPattern(int patternScheme[][][], int btnId, int colorDown, int colorUp, Activity activity) { if (btnId >= 0) { for (int i = 0; i < patternScheme[btnId].length; i++) { for (int j = 0; j < patternScheme[btnId][i].length; j++) { try { getView(patternScheme[btnId][i][j], activity).setBackgroundColor( getBlendColor( activity.getResources().getColor(colorDown), activity.getResources().getColor(colorUp), (0.8f - (0.3f * i)))); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); getView(patternScheme[btnId][i][j], activity).setBackgroundColor( getBlendColor( colorDown, activity.getResources().getColor(colorUp), (0.8f - (0.3f * i)) ) ); } } } } } private void setButtonPatternDefault(int patternScheme[][][], int btnId, int colorUp, Activity activity) { if (btnId >= 0) { for (int i = 0; i < patternScheme[btnId].length; i++) { for (int j = 0; j < patternScheme[btnId][i].length; j++) { try { getView(patternScheme[btnId][i][j], activity).setBackgroundColor(activity.getResources().getColor(colorUp)); } catch (Resources.NotFoundException e) { Log.i("NotFoundException", "Handling with normal value"); getView(patternScheme[btnId][i][j], activity).setBackgroundColor(colorUp); } } } } } public int getBlendColor(int color0, int color1, float blendPercent) { String colorString0 = String.format("#%06X", (0xFFFFFF & color0)); //Log.d("color0", colorString0); String colorString1 = String.format("#%06X", (0xFFFFFF & color1)); //Log.d("color1", colorString1); int r0 = Integer.parseInt(colorString0.substring(1, 3), 16); int g0 = Integer.parseInt(colorString0.substring(3, 5), 16); int b0 = Integer.parseInt(colorString0.substring(5, 7), 16); int r1 = Integer.parseInt(colorString1.substring(1, 3), 16); int g1 = Integer.parseInt(colorString1.substring(3, 5), 16); int b1 = Integer.parseInt(colorString1.substring(5, 7), 16); String blendColorHex = " getTwoDigitHexString(averageIntegerWithPercent(r0, r1, blendPercent)) + getTwoDigitHexString(averageIntegerWithPercent(g0, g1, blendPercent)) + getTwoDigitHexString(averageIntegerWithPercent(b0, b1, blendPercent)); return Color.parseColor(blendColorHex); } private int averageIntegerWithPercent(int num1, int num2, float percent) { return Math.round((num1 - num2) * percent) + num2; } private String getTwoDigitHexString(int hexValue) { String hexString = Integer.toHexString(hexValue); //Log.d("hexStringCheck", hexString); if (hexString.length() == 1) { hexString = "0" + hexString; } return hexString; } private void setSoundPoolDelay(final SoundPool sp, final int soundId[], final int count, final int delay) { Handler delayHandler = new Handler(); delayHandler.postDelayed(new Runnable() { @Override public void run() { Log.d("SoundPoolDelay", "SoundPool played on " + soundId[count] + " with " + delay + "ms delay"); sp.play(soundId[count], 1, 1, 1, 0, 1f); } }, delay); } public void setOnTouchSound(int id, final SoundPool sp, final int soundId, final Activity activity) { final View view = activity.findViewById(id); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { sp.play(soundId, 1, 1, 1, 0, 1f); } return false; } }); } public void setOnTouch(int id, final Runnable touch, Activity activity) { View view = activity.findViewById(id); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { touch.run(); return false; } }); } public void setOnClick(int id, final Runnable click, Activity activity) { View view = activity.findViewById(id); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { click.run(); } }); } public int getDeviceRam() { RandomAccessFile reader = null; String load = null; double totRam = 0; double totRamMb = 0; try { reader = new RandomAccessFile("/proc/meminfo", "r"); load = reader.readLine(); // Get the Number value from the string Pattern p = Pattern.compile("(\\d+)"); Matcher m = p.matcher(load); String value = ""; while (m.find()) { value = m.group(1); // System.out.println("Ram : " + value); } reader.close(); totRam = Double.parseDouble(value); // totRam = totRam / 1024; totRamMb = totRam / 1024.0; } catch (IOException ex) { ex.printStackTrace(); } finally { // Streams.close(reader); } Log.i("getDeviceRam", "Device Ram requested = returned " + String.valueOf(totRamMb)); return (int) totRamMb; } }
package com.iluwatar.abstractfactory; /** * * The Abstract Factory pattern provides a way to encapsulate a group of individual factories that * have a common theme without specifying their concrete classes. In normal usage, the client * software creates a concrete implementation of the abstract factory and then uses the generic * interface of the factory to create the concrete objects that are part of the theme. The client * does not know (or care) which concrete objects it gets from each of these internal factories, * since it uses only the generic interfaces of their products. This pattern separates the details * of implementation of a set of objects from their general usage and relies on object composition, * as object creation is implemented in methods exposed in the factory interface. * <p> * The essence of the Abstract Factory pattern is a factory interface ({@link KingdomFactory}) and * its implementations ({@link ElfKingdomFactory}, {@link OrcKingdomFactory}). The example uses both * concrete implementations to create a king, a castle and an army. * */ public class App { private King king; private Castle castle; private Army army; /** * Creates kingdom * * @param factory */ public void createKingdom(final KingdomFactory factory) { setKing(factory.createKing()); setCastle(factory.createCastle()); setArmy(factory.createArmy()); } ElfKingdomFactory getElfKingdomFactory() { return new ElfKingdomFactory(); } OrcKingdomFactory getOrcKingdomFactory() { return new OrcKingdomFactory(); } King getKing(final KingdomFactory factory) { return factory.createKing(); } Castle getCastle(final KingdomFactory factory) { return factory.createCastle(); } Army getArmy(final KingdomFactory factory) { return factory.createArmy(); } public King getKing() { return king; } private void setKing(final King king) { this.king = king; } public Castle getCastle() { return castle; } private void setCastle(final Castle castle) { this.castle = castle; } public Army getArmy() { return army; } private void setArmy(final Army army) { this.army = army; } /** * Program entry point * * @param args command line args */ public static void main(String[] args) { App app = new App(); System.out.println("Elf Kingdom"); KingdomFactory elfKingdomFactory; elfKingdomFactory = app.getElfKingdomFactory(); app.createKingdom(elfKingdomFactory); System.out.println(app.getArmy().getDescription()); System.out.println(app.getCastle().getDescription()); System.out.println(app.getKing().getDescription()); System.out.println("\nOrc Kingdom"); KingdomFactory orcKingdomFactory; orcKingdomFactory = app.getOrcKingdomFactory(); app.createKingdom(orcKingdomFactory); System.out.println(app.getArmy().getDescription()); System.out.println(app.getCastle().getDescription()); System.out.println(app.getKing().getDescription()); } }
package com.breadwallet.tools.manager; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.Activity; import android.content.Context; import android.os.Handler; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.util.Log; import android.view.View; import com.breadwallet.R; import com.breadwallet.presenter.activities.BreadActivity; import com.breadwallet.presenter.entities.TxItem; import com.breadwallet.tools.adapter.TransactionListAdapter; import com.breadwallet.tools.animation.BRAnimator; import com.breadwallet.tools.listeners.RecyclerItemClickListener; import com.breadwallet.wallet.BRPeerManager; import com.breadwallet.wallet.BRWalletManager; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class TxManager { private static final String TAG = TxManager.class.getName(); private static TxManager instance; private RecyclerView txList; public TransactionListAdapter adapter; public PromptManager.PromptItem currentPrompt; public PromptManager.PromptInfo promptInfo; public TransactionListAdapter.SyncingHolder syncingHolder; public static TxManager getInstance() { if (instance == null) instance = new TxManager(); return instance; } public void init(final BreadActivity app) { txList = (RecyclerView) app.findViewById(R.id.tx_list); txList.setLayoutManager(new LinearLayoutManager(app)); txList.addOnItemTouchListener(new RecyclerItemClickListener(app, txList, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position, float x, float y) { if (currentPrompt == null || position > 0) BRAnimator.showTransactionPager(app, adapter.getItems(), currentPrompt == null ? position : position - 1); else { //clicked on the x (close) if (x > view.getWidth() - 100 && y < 100) { view.animate().setDuration(150).translationX(BreadActivity.screenParametersPoint.x).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); hidePrompt(app, null); } }); } else { //clicked on the prompt BREventManager.getInstance().pushEvent("prompt." + PromptManager.getInstance().getPromptName(currentPrompt) + ".trigger"); if (currentPrompt != PromptManager.PromptItem.SYNCING) { PromptManager.PromptInfo info = PromptManager.getInstance().promptInfo(app, currentPrompt); if (info != null) info.listener.onClick(view); currentPrompt = null; } } } } @Override public void onLongItemClick(View view, int position) { } })); if (adapter == null) adapter = new TransactionListAdapter(app, null); setupSwipe(app); } private TxManager() { } public void onResume(final Activity app) { new Thread(new Runnable() { @Override public void run() { final double progress = BRPeerManager.syncProgress(BRSharedPrefs.getStartHeight(app)); app.runOnUiThread(new Runnable() { @Override public void run() { if (progress > 0 && progress < 1) { currentPrompt = PromptManager.PromptItem.SYNCING; } else { showNextPrompt(app); } updateCard(app); } }); } }).start(); } public void showPrompt(Activity app, PromptManager.PromptItem item) { if (item == null) throw new RuntimeException("can't be null"); BREventManager.getInstance().pushEvent("prompt." + PromptManager.getInstance().getPromptName(item) + ".displayed"); if (currentPrompt != PromptManager.PromptItem.SYNCING) { currentPrompt = item; } updateCard(app); } public void hidePrompt(final Activity app, final PromptManager.PromptItem item) { currentPrompt = null; updateCard(app); if (item == PromptManager.PromptItem.SYNCING) { app.runOnUiThread(new Runnable() { @Override public void run() { new Handler().postDelayed(new Runnable() { @Override public void run() { showNextPrompt(app); updateCard(app); } }, 1000); } }); } else { if (item != null) BREventManager.getInstance().pushEvent("prompt." + PromptManager.getInstance().getPromptName(item) + ".dismissed"); } } public void showInfoCard(boolean show, PromptManager.PromptInfo info) { if (show) { promptInfo = info; } else { promptInfo = null; } } private void showNextPrompt(Activity app) { PromptManager.PromptItem toShow = PromptManager.getInstance().nextPrompt(app); if (toShow != null) { Log.d(TAG, "showNextPrompt: " + toShow); currentPrompt = toShow; PromptManager.PromptInfo info = PromptManager.getInstance().promptInfo(app, currentPrompt); showInfoCard(true, info); updateCard(app); } else { Log.i(TAG, "showNextPrompt: nothing to show"); } } //BLOCKS public void updateTxList(final Context app) { final TxItem[] arr = BRWalletManager.getInstance().getTransactions(); ((Activity) app).runOnUiThread(new Runnable() { @Override public void run() { List<TxItem> items = arr == null ? null : new LinkedList<>(Arrays.asList(arr)); adapter.setItems(items); txList.swapAdapter(adapter, true); adapter.notifyDataSetChanged(); } }); } public void updateCard(Context app) { // Log.e(TAG, "updateTxList: "); // ((Activity) app).runOnUiThread(new Runnable() { // @Override // public void run() { // adapter.notifyItemChanged(0); // txList.getRecycledViewPool().clear(); updateTxList(app); } private void setupSwipe(final Activity app) { ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { // Toast.makeText(BreadActivity.this, "on Move ", Toast.LENGTH_SHORT).show(); return false; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) { hidePrompt(app, null); //Remove swiped item from list and notify the RecyclerView } @Override public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { if (!(viewHolder instanceof TransactionListAdapter.PromptHolder)) return 0; return super.getSwipeDirs(recyclerView, viewHolder); } }; ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback); itemTouchHelper.attachToRecyclerView(txList); } }
package kg.apc.jmeter.perfmon.agent; import java.util.ArrayList; import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.FileSystemUsage; import org.hyperic.sigar.Mem; import org.hyperic.sigar.NetInterfaceStat; import org.hyperic.sigar.ProcCpu; import org.hyperic.sigar.ProcMem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarProxy; import org.hyperic.sigar.SigarProxyCache; import org.hyperic.sigar.Swap; public class MetricsGetter implements AgentCommandsInterface { /* * The unic instance */ private static MetricsGetter instance = new MetricsGetter(); /* * The hostName where the server is run (retrieved by Sigar) */ private String hostName = null; /* * We need to use the Sigar proxy to ensure high AgentConnector demands can be handled */ private SigarProxy sigarProxy = null; /* * contains the list of drives for I/O metrics */ private FileSystem[] fileSystems = null; private String[] networkInterfaces = null; private long pid = -1; /** * The constructor which instanciates the Sigar service */ private MetricsGetter() { sigarProxy = SigarProxyCache.newInstance(new Sigar(), 500); try { hostName = sigarProxy.getNetInfo().getHostName(); } catch (SigarException ex) { ServerAgent.logMessage(ex.getMessage()); hostName = "unknownHost"; } ServerAgent.logMessage("Server monitored: " + hostName); initFileSystems(); initNetworkInterfaces(); } public void setPidToMonitor(long pid) { this.pid = pid; } /** * The only way to retrieve the object * @return the MetricsGetter instance */ public static MetricsGetter getInstance() { return instance; } public final void initNetworkInterfaces() { try { networkInterfaces = sigarProxy.getNetInterfaceList(); ServerAgent.logMessage(" for(int i=0; i<networkInterfaces.length; i++) { ServerAgent.logMessage("Network interface detected: " + networkInterfaces[i]); } ServerAgent.logMessage(" } catch (SigarException ex) { networkInterfaces = new String[0]; ServerAgent.logMessage("Error while getting network interfaces: " + ex.getMessage()); } } /** * Get list of FileSystems for I/O monitoring */ public final void initFileSystems() { try { ArrayList tmp = new ArrayList(); FileSystem[] fs = sigarProxy.getFileSystemList(); for (int i = 0; i < fs.length; i++) { FileSystem fileSystem = fs[i]; if (fileSystem != null && fileSystem.getType() == FileSystem.TYPE_LOCAL_DISK) { tmp.add(fileSystem); } } fileSystems = new FileSystem[tmp.size()]; for (int i = 0; i < tmp.size(); i++) { fileSystems[i] = (FileSystem) tmp.get(i); } ServerAgent.logMessage(" for(int i=0; i<fileSystems.length; i++) { ServerAgent.logMessage("File System detected: " + fileSystems[i].getDevName()); } ServerAgent.logMessage(" } catch (SigarException ex) { fileSystems = new FileSystem[0]; ServerAgent.logMessage("Error while getting disks: " + ex.getMessage()); } } /** * Get the current cpu load in percent * @return the cpu load, or -1 if a problem occurred */ private double getCpuUsage() { try { if(pid == -1) { CpuPerc cpuPerc = sigarProxy.getCpuPerc(); return cpuPerc != null ? cpuPerc.getCombined() : 0; } else { ProcCpu procCpu = sigarProxy.getProcCpu(pid); return procCpu != null ? procCpu.getPercent() : 0; } } catch (SigarException e) { ServerAgent.logMessage(e.getMessage()); return AGENT_ERROR; } } /** * Get the current memory usage in bytes * @return the memory size or -1 if a problem occurred */ private long getUsedMem() { try { if(pid == -1) { Mem mem = sigarProxy.getMem(); return mem != null ? mem.getUsed() : 0; } else { ProcMem procMem = sigarProxy.getProcMem(pid); return procMem != null ? procMem.getSize() : 0; } } catch (SigarException e) { ServerAgent.logMessage(e.getMessage()); return AGENT_ERROR; } } /** * Get the current swap usage in number of pages in and number of pages out * @return [page in][page out] */ private long[] getSwap() { long[] ret = new long[2]; try { Swap swap = sigarProxy.getSwap(); if(swap != null) { ret[0] = swap.getPageIn(); ret[1] = swap.getPageOut(); } else { ret[0] = 0; ret[1] = 0; } } catch (SigarException e) { ServerAgent.logMessage(e.getMessage()); ret = AGENT_ERROR_ARRAY; } return ret; } private long[] getNetIO() { if (networkInterfaces.length == 0) { return MetricsGetter.SIGAR_ERROR_ARRAY; } long[] ret = { 0L, 0L }; for (int i = 0; i < networkInterfaces.length; i++) { String interfaceName = networkInterfaces[i]; if (interfaceName != null) { try { NetInterfaceStat metrics = sigarProxy.getNetInterfaceStat(interfaceName); long rxBytes = metrics.getRxBytes(); long txBytes = metrics.getTxBytes(); if (rxBytes != -1 && txBytes != -1) { ret[0] = ret[0] + rxBytes; ret[1] = ret[1] + txBytes; } } catch (SigarException ex) { ServerAgent.logMessage("WARNING: " + ex.getMessage() + ". " + networkInterfaces[i] + " is now removed from interface list."); networkInterfaces[i] = null; } } } return ret; } /** * Get the current swap usage in number of pages in and number of pages out * @return [page in][page out] */ private long[] getDisksIO() { if (fileSystems.length == 0) { return SIGAR_ERROR_ARRAY; } long[] ret = { 0L, 0L }; try { for (int i = 0; i < fileSystems.length; i++) { //if sigar failed to get metrics (without exception) FileSystemUsage metrics = sigarProxy.getFileSystemUsage(fileSystems[i].getDevName()); long reads = metrics.getDiskReads(); long writes = metrics.getDiskWrites(); if (reads == -1L || writes == -1L) { return SIGAR_ERROR_ARRAY; } else { ret[0] = ret[0] + reads; ret[1] = ret[1] + writes; } } } catch (SigarException ex) { ServerAgent.logMessage(ex.getMessage()); ret = AGENT_ERROR_ARRAY; } return ret; } public boolean isPidFound(long pid) { try { return (sigarProxy.getProcCpu(pid) != null); } catch (SigarException ex) { String friendlyMsg = ex.getMessage(); if(friendlyMsg.indexOf("Access is denied.")!= -1) friendlyMsg = "Access is denied."; else if(friendlyMsg.indexOf("The parameter is incorrect.")!= -1) friendlyMsg = "PID not found."; ServerAgent.logMessage("Cannot access pid " + pid + ": " + friendlyMsg); return false; } } /** * Get the server name * @return the server name retrieved by Sigar */ private String getServerName() { return hostName; } /** * The main method to get metrics from Sigar * @param value the command to retrieve one metric * @return a String representing the value or badCmd if the command is unknown */ public String getValues(String value) { // NEVER CHANGE to String BUILDER for old jdk compatibility StringBuffer buff = new StringBuffer(); if (value.equals(CPU)) { buff.append(getCpuUsage()); } else if (value.equals(MEMORY)) { buff.append(getUsedMem()); } else if (value.equals(SWAP)) { long[] values = getSwap(); buff.append(values[0]); buff.append(":"); buff.append(values[1]); } else if (value.equals(DISKIO)) { long[] values = getDisksIO(); buff.append(values[0]); buff.append(":"); buff.append(values[1]); } else if (value.equals(NETWORK)) { long[] values = getNetIO(); buff.append(values[0]); buff.append(":"); buff.append(values[1]); } else if (value.equals(NAME)) { buff.append(getServerName()); } else if (value.equals(PID)) { buff.append(pid); } else { buff.append(BADCMD); } return buff.toString(); } }
package com.njnu.kai.practice.ui; import android.os.Bundle; import android.text.Html; import android.text.SpannableString; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.njnu.kai.practice.R; import com.njnu.kai.practice.ui.dividerdrawable.DividerDrawable; import com.njnu.kai.practice.ui.dividerdrawable.DividerLayout; import com.njnu.kai.practice.ui.dividerdrawable.DividerUtils; import com.njnu.kai.support.BaseTestFragment; import com.njnu.kai.support.DisplayUtils; import com.njnu.kai.support.ToastUtils; /** * @author kai * @since 2017/6/1 */ public class UIShowFragment extends BaseTestFragment { @Override protected View onCreateContentView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) { View view = layoutInflater.inflate(R.layout.fragment_ui_show, viewGroup, false); testBadgeDrawable(view); testDividerDrawable(view); return view; } private void testDividerDrawable(View view) { TextView tvHtml = (TextView) view.findViewById(R.id.tv_html); String html="<html><head><title>TextViewHTML</title></head><body><p><strong></strong></p><p><em></em></p>" +"<p><a href=\"http://www.dreamdu.com/xhtml/\">HTML</a>HTML!</p><p><font color=\"#aabb00\" style=\"font-size:40%\">1" +"</p><p><font color=\"#00bbaa\" style=\"font-size:200%\">2</p><h1>1</h1><h3>2</h3><h6>3</h6><p>><</p><p>" + "</body></html>"; tvHtml.setText(Html.fromHtml(html)); DividerDrawable dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setCenter(DividerLayout.CENTER_VERTICAL); DividerUtils.addDividersTo(view.findViewById(R.id.linear1), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setMarginLeftDp(50) .setCenter(DividerLayout.CENTER_VERTICAL); DividerUtils.addDividersTo(view.findViewById(R.id.linear2), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setOrientation(DividerLayout.ORIENTATION_VERTICAL) .setAlign(DividerLayout.ALIGN_PARENT_RIGHT) .setMarginTopDp(16) .setMarginBottomDp(16); DividerUtils.addDividersTo(view.findViewById(R.id.text_3_1), dividerDrawable); DividerUtils.addDividersTo(view.findViewById(R.id.text_3_3), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setOrientation(DividerLayout.ORIENTATION_VERTICAL) .setAlign(DividerLayout.ALIGN_PARENT_RIGHT) .setMarginTopDp(32) .setMarginBottomDp(32); DividerUtils.addDividersTo(view.findViewById(R.id.text_3_2), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setMarginLeftDp(16) .setLengthDp(100); DividerUtils.addDividersTo(view.findViewById(R.id.text_4_1), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setOrientation(DividerLayout.ORIENTATION_VERTICAL) .setCenter(DividerLayout.CENTER_VERTICAL) .setLengthDp(46); DividerUtils.addDividersTo(view.findViewById(R.id.text_4_1), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setCenter(DividerLayout.CENTER_HORIZONTAL) .setLengthDp(100); DividerUtils.addDividersTo(view.findViewById(R.id.text_4_2), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setOrientation(DividerLayout.ORIENTATION_VERTICAL) .setAlign(DividerLayout.ALIGN_PARENT_RIGHT) .setCenter(DividerLayout.CENTER_VERTICAL) .setLengthDp(46); DividerUtils.addDividersTo(view.findViewById(R.id.text_4_2), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setAlign(DividerLayout.ALIGN_PARENT_RIGHT) .setMarginRightDp(16) .setLengthDp(100); DividerUtils.addDividersTo(view.findViewById(R.id.text_4_3), dividerDrawable); dividerDrawable = new DividerDrawable(); dividerDrawable .setStrokeWidth(10) .setColor(0xFFFFFFFF) .getLayout() .setCenter(DividerLayout.CENTER_HORIZONTAL) .setLengthDp(300); DividerUtils.addDividersTo(view.findViewById(R.id.text_4_4), dividerDrawable); } private void testBadgeDrawable(View view) { final TextView textView = (TextView) view.findViewById(R.id.tvHelloWorld); final ImageView imageView = (ImageView) view.findViewById(R.id.imageView); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ToastUtils.showToast("resourceName=" + getResources().getResourceName(v.getId())); } }); final BadgeDrawable drawable = new BadgeDrawable.Builder() .type(BadgeDrawable.TYPE_NUMBER) .number(9) .build(); final BadgeDrawable drawable2 = new BadgeDrawable.Builder() .type(BadgeDrawable.TYPE_ONLY_ONE_TEXT) .badgeColor(0xff336699) .text1("VIP") .build(); final BadgeDrawable drawable3 = new BadgeDrawable.Builder() .type(BadgeDrawable.TYPE_WITH_TWO_TEXT_COMPLEMENTARY) .badgeColor(0xffCC9933) .text1("LEVEL") .text2("10") .build(); final BadgeDrawable drawable4 = new BadgeDrawable.Builder() .type(BadgeDrawable.TYPE_WITH_TWO_TEXT) .badgeColor(0xffCC9999) .text1("TEST") .text2("Pass") .build(); final BadgeDrawable drawable5 = new BadgeDrawable.Builder() .type(BadgeDrawable.TYPE_NUMBER) .number(999) .badgeColor(0xff336699) .build(); SpannableString spannableString = new SpannableString(TextUtils.concat( "TextView: ", drawable.toSpannable(), " ", drawable2.toSpannable(), " ", drawable3.toSpannable(), " ", drawable4.toSpannable(), " ", drawable5.toSpannable() )); if (textView != null) { textView.setText(spannableString); } if (imageView != null) { final BadgeDrawable drawable6 = new BadgeDrawable.Builder() .type(BadgeDrawable.TYPE_WITH_TWO_TEXT_COMPLEMENTARY) .badgeColor(0xff336633) .textSize(DisplayUtils.dp2px(14)) .text1("Author") .text2("Github") // .typeFace(Typeface.createFromAsset(getAssets(), "fonts/code-bold.otf")) .build(); imageView.setImageDrawable(drawable6); } } }
// $Id: DriverTask.java,v 1.2 2001/12/03 08:53:45 mdb Exp $ // viztool - a tool for visualizing collections of java classes // This program is free software; you can redistribute it and/or modify it // option) any later version. // This program is distributed in the hope that it will be useful, but // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // with this program; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.viztool; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import javax.print.attribute.HashPrintRequestAttributeSet; import javax.print.attribute.PrintRequestAttributeSet; import javax.print.attribute.standard.Destination; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.CommandlineJava; import org.apache.tools.ant.types.Path; import com.samskivert.swing.util.SwingUtil; import com.samskivert.viztool.enum.ClassEnumerator; import com.samskivert.viztool.enum.FilterEnumerator; import com.samskivert.viztool.enum.RegexpEnumerator; import com.samskivert.viztool.util.FontPicker; /** * The viztool ant task. It takes the following arguments: * * <pre> * pkgroot = the base package from which names will be shortened * classes = a regular expression matching the classes to be visualized * visualizer = the classname of the visualizer to be used * </pre> * * The task should contain an embedded &lt;classpath&gt; element to * provide the classpath over which we will iterate, looking for matching * classes. */ public class DriverTask extends Task { public void setVisualizer (String vizclass) { _vizclass = vizclass; } public void setPkgroot (String pkgroot) { _pkgroot = pkgroot; } public void setClasses (String classes) { _classes = classes; } public void setOutput (File output) { _output = output; } public Path createClasspath () { return _cmdline.createClasspath(project).createPath(); } /** * Performs the actual work of the task. */ public void execute () throws BuildException { // make sure everything was set up properly ensureSet(_vizclass, "Must specify the visualizer class " + "via the 'visualizer' attribute."); ensureSet(_pkgroot, "Must specify the package root " + "via the 'pkgroot' attribute."); ensureSet(_pkgroot, "Must specify the class regular expression " + "via the 'classes' attribute."); Path classpath = _cmdline.getClasspath(); ensureSet(classpath, "Must provide a <classpath> subelement " + "describing the classpath to be searched for classes."); // initialize the font picker FontPicker.init(_output != null); // create the classloader we'll use to load the visualized classes ClassLoader cl = new AntClassLoader(null, project, classpath, false); // scan the classpath and determine which classes will be // visualized ClassEnumerator enum = new ClassEnumerator(classpath.toString()); FilterEnumerator fenum = null; try { fenum = new RegexpEnumerator(_classes, enum); } catch (Exception e) { throw new BuildException("Invalid package regular expression " + "[classes=" + _classes + "].", e); } ArrayList classes = new ArrayList(); while (fenum.hasNext()) { String cname = (String)fenum.next(); // skip inner classes, the visualizations pick those up // themselves if (cname.indexOf("$") != -1) { continue; } try { classes.add(cl.loadClass(cname)); } catch (Throwable t) { log("Unable to introspect class [class=" + cname + ", error=" + t + "]."); } } // // remove the packages on our exclusion list // String expkg = System.getProperty("exclude"); // if (expkg != null) { // StringTokenizer tok = new StringTokenizer(expkg, ":"); // while (tok.hasMoreTokens()) { // pkgset.remove(tok.nextToken()); // now create our visualizer and go to work Visualizer viz = null; try { viz = (Visualizer)Class.forName(_vizclass).newInstance(); } catch (Throwable t) { throw new BuildException("Unable to instantiate visualizer " + "[vizclass=" + _vizclass + ", error=" + t + "]."); } viz.setPackageRoot(_pkgroot); viz.setClasses(classes.iterator()); // if no output file was specified, pop up a window if (_output == null) { VizFrame frame = new VizFrame(viz); frame.pack(); SwingUtil.centerWindow(frame); frame.setVisible(true); // prevent ant from kicking the JVM out from under us synchronized (this) { while (true) { try { wait(); } catch (InterruptedException ie) { } } } } else { // we use the print system to render things PrinterJob job = PrinterJob.getPrinterJob(); // use sensible margins PageFormat format = job.defaultPage(); Paper paper = new Paper(); paper.setImageableArea(72*0.5, 72*0.5, 72*7.5, 72*10); format.setPaper(paper); // use our configured page format job.setPrintable(viz, format); // tell our printjob to print to a file PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(); String outpath = _output.getPath(); try { URI target = new URI("file:" + outpath); attrs.add(new Destination(target)); } catch (URISyntaxException use) { String errmsg = "Can't create URI for 'output' file path? " + "[output=" + outpath + "]."; throw new BuildException(errmsg, use); } // invoke the printing process try { log("Generating visualization to '" + outpath + "'."); job.print(attrs); } catch (PrinterException pe) { throw new BuildException("Error printing visualization.", pe); } } } protected void ensureSet (Object value, String errmsg) throws BuildException { if (value == null) { throw new BuildException(errmsg); } } protected String _vizclass; protected String _pkgroot; protected String _classes; protected File _output; // use use this for accumulating our classpath protected CommandlineJava _cmdline = new CommandlineJava(); }
package com.paperfly.instantjio; import android.app.Application; import com.facebook.FacebookSdk; import com.firebase.client.Firebase; /** * Initialize Firebase with the application context. This must happen before the client is used. */ public class MainApplication extends Application { @Override public void onCreate() { super.onCreate(); Firebase.setAndroidContext(getApplicationContext()); Firebase.getDefaultConfig().setPersistenceEnabled(true); FacebookSdk.sdkInitialize(getApplicationContext()); } }
package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { throw new UnsupportedOperationException("You can not close the fragment"); } }
package com.schautup.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import com.nineoldandroids.view.ViewHelper; import com.nineoldandroids.view.ViewPropertyAnimator; import com.schautup.R; import com.schautup.adapters.BaseScheduleAdapter; import com.schautup.bus.AddNewScheduleItemEvent; import com.schautup.bus.AllScheduleLoadedEvent; import com.schautup.db.DB; import com.schautup.views.AnimImageButton; import de.greenrobot.event.EventBus; /** * Abstract impl for {@link com.schautup.fragments.BaseFragment}s that hold {@link android.widget.ListView}, {@link * android.widget.GridView}. * * @author Xinyue Zhao */ public abstract class BaseListFragment extends BaseFragment implements AbsListView.OnScrollListener { /** * {@link android.widget.AbsListView} for all schedules. * <p/> * It must be {@link android.widget.ListView}, {@link android.widget.GridView}. */ private AbsListView mLv; /** * {@link com.schautup.adapters.BaseScheduleAdapter} for {@link #mLv}. */ private BaseScheduleAdapter mAdp; /** * Helper value to detect scroll direction of {@link android.widget.ListView} {@link #mLv}. */ private int mLastFirstVisibleItem; /** * {@link android.view.ViewGroup} that holds an "add" {@link android.widget.ImageButton}. */ private ViewGroup mAddNewVG; /** * A button to load data when there's no data. */ private AnimImageButton mNoDataBtn; /** * {@code true} if the adapter has pushed data on to list. */ private boolean mIsShowing = false; //Subscribes, event-handlers /** * Handler for {@link com.schautup.bus.AllScheduleLoadedEvent} * * @param e * Event {@link com.schautup.bus.AllScheduleLoadedEvent}. */ public void onEvent(AllScheduleLoadedEvent e) { // Show data. if (e.getScheduleItemList() != null && e.getScheduleItemList().size() > 0) { mNoDataBtn.setVisibility(View.GONE); mAdp.setItemList(e.getScheduleItemList()); if (mIsShowing) { mAdp.notifyDataSetChanged(); } else { ((AdapterView) getListViewWidget()).setAdapter(mAdp); mIsShowing = true; } } else { mNoDataBtn.setVisibility(View.VISIBLE); } } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mLv.setOnScrollListener(this); // Add new. mAddNewVG = (ViewGroup) view.findViewById(R.id.add_fl); mAddNewVG.getLayoutParams().height = getActionBarHeight(); mAddNewVG.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new AddNewScheduleItemEvent()); } }); // No data. mNoDataBtn = (AnimImageButton) view.findViewById(R.id.no_data_btn); mNoDataBtn.setOnClickListener(new AnimImageButton.OnAnimImageButtonClickedListener() { @Override public void onClick() { EventBus.getDefault().post(new AddNewScheduleItemEvent()); } }); } @Override public void onResume() { super.onResume(); // Description: Test data block. // Will be removed late. // List<ScheduleItem> items = new ArrayList<ScheduleItem>(); // for (int i = 0; i < 100; i++) { // items.add(new ScheduleItem(ScheduleType.MUTE, i, i, System.currentTimeMillis())); // EventBus.getDefault().post(new AllScheduleLoadedEvent(items)); EventBus.getDefault().post(new AllScheduleLoadedEvent(DB.getInstance(getActivity().getApplication()) .getAllSchedules())); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { float translationY = ViewHelper.getTranslationY(mAddNewVG); if (scrollState == 0) { //ListView is idle, user can add item with a button. if (translationY != 0) { ViewPropertyAnimator animator = ViewPropertyAnimator.animate(mAddNewVG); animator.translationY(0).setDuration(700); } } else { //ListView moving, add button can dismiss. if (translationY == 0) { ViewPropertyAnimator animator = ViewPropertyAnimator.animate(mAddNewVG); animator.translationY(getActionBarHeight()).setDuration(700); } } if (view.getId() == view.getId()) { final int currentFirstVisibleItem = view.getFirstVisiblePosition(); if (currentFirstVisibleItem > mLastFirstVisibleItem) { if (getSupportActionBar().isShowing()) { getSupportActionBar().hide(); } } else if (currentFirstVisibleItem < mLastFirstVisibleItem) { if (!getSupportActionBar().isShowing()) { getSupportActionBar().show(); } } mLastFirstVisibleItem = currentFirstVisibleItem; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } /** * Access on a widget extends from {@link android.widget.AbsListView}. * * @return An {@link android.widget.AbsListView} object. */ protected AbsListView getListViewWidget() { return mLv; } /** * Create a {@link android.widget.AbsListView} object. * * @return The {@link android.widget.AbsListView} object. */ protected void setListViewWidget(AbsListView absListView) { mLv = absListView; } /** * Create a {@link com.schautup.adapters.BaseScheduleAdapter} object. * * @return The {@link com.schautup.adapters.BaseScheduleAdapter} object. */ protected void setAdapter(BaseScheduleAdapter adp) { mAdp = adp; } }
package com.tlongdev.bktf.activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.tlongdev.bktf.BptfApplication; import com.tlongdev.bktf.R; import com.tlongdev.bktf.fragment.CalculatorFragment; import com.tlongdev.bktf.fragment.ConverterFragment; import com.tlongdev.bktf.fragment.FavoritesFragment; import com.tlongdev.bktf.fragment.RecentsFragment; import com.tlongdev.bktf.fragment.UnusualFragment; import com.tlongdev.bktf.fragment.UserFragment; import com.tlongdev.bktf.gcm.GcmRegisterPriceUpdatesService; import com.tlongdev.bktf.util.CircleTransform; import com.tlongdev.bktf.util.Profile; import com.tlongdev.bktf.util.Utility; import butterknife.Bind; import butterknife.ButterKnife; /** * Tha main activity if the application. Navigation drawer is used. This is where most of the * fragments are shown. */ public class MainActivity extends AppCompatActivity { /** * Log tag for logging. */ @SuppressWarnings("unused") private static final String LOG_TAG = MainActivity.class.getSimpleName(); /** * Request codes for onActivityResult */ public static final int REQUEST_SETTINGS = 100; public static final int REQUEST_NEW_ITEM = 101; public static final String FRAGMENT_TAG_RECENTS = "recents"; public static final String FRAGMENT_TAG_UNUSUALS = "unusuals"; public static final String FRAGMENT_TAG_USER = "user"; public static final String FRAGMENT_TAG_FAVORITES = "favorites"; public static final String FRAGMENT_TAG_CONVERTER = "converter"; public static final String FRAGMENT_TAG_CALCULATOR = "calculator"; /** * Remember the position of the selected item. */ private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; /** * The {@link Tracker} used to record screen views. */ private Tracker mTracker; /** * Helper component that ties the action bar to the navigation drawer. */ private ActionBarDrawerToggle mDrawerToggle; /** * The drawer layout and the navigation drawer */ @Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout; @Bind(R.id.navigation_view) NavigationView mNavigationView; /** * The index of the current fragment. */ private int mCurrentSelectedPosition = -1; /** * Variables used for managing fragments. */ private boolean userStateChanged = false; /** * Listener to be notified when the drawer opens. Mainly for fragments with toolbars so we can * exapnd the fragment's toolbar when the drawer opens. */ private OnDrawerOpenedListener drawerListener; /** * Views of the navigation header view. */ private TextView name; private TextView backpack; private ImageView avatar; private MenuItem userMenuItem; /** * Listener for the navigation drawer. */ NavigationView.OnNavigationItemSelectedListener navigationListener = new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { //Close the drawers and handle item clicks mDrawerLayout.closeDrawers(); switch (menuItem.getItemId()) { // TODO: 2015. 10. 25. fragment selections in the navigation view is incorrect when selecting the user fragment case R.id.nav_recents: switchFragment(0); break; case R.id.nav_unusuals: switchFragment(1); break; case R.id.nav_user: switchFragment(2); break; case R.id.nav_favorites: switchFragment(3); break; case R.id.nav_converter: switchFragment(4); break; case R.id.nav_calculator: switchFragment(5); break; case R.id.nav_settings: Intent settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); startActivityForResult(settingsIntent, REQUEST_SETTINGS); break; case R.id.nav_about: startActivity(new Intent(MainActivity.this, AboutActivity.class)); break; } return true; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // Obtain the shared Tracker instance. BptfApplication application = (BptfApplication) getApplication(); mTracker = application.getDefaultTracker(); //Set the default values for all preferences when the app is first loaded PreferenceManager.setDefaultValues(this, R.xml.pref_general, false); //Setup the drawer mDrawerLayout.setStatusBarBackgroundColor(Utility.getColor(this, R.color.primary_dark)); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); //The navigation view mNavigationView.setNavigationItemSelectedListener(navigationListener); //User clicked on the header View navigationHeader = mNavigationView.getHeaderView(0); //Find the views of the navigation drawer header name = (TextView) navigationHeader.findViewById(R.id.user_name); backpack = (TextView) navigationHeader.findViewById(R.id.backpack_value); avatar = (ImageView) navigationHeader.findViewById(R.id.avatar); userMenuItem = mNavigationView.getMenu().getItem(2); //Check if there is a fragment to be restored if (savedInstanceState != null) { switchFragment(savedInstanceState.getInt(STATE_SELECTED_POSITION)); mNavigationView.getMenu().getItem(mCurrentSelectedPosition).setChecked(true); } else { mNavigationView.getMenu().getItem(0).setChecked(true); // Select either the default item (0) or the last selected item. switchFragment(0); } } @Override protected void onResume() { mTracker.setScreenName(String.valueOf(getTitle())); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); //If needed (mostly when the steamId was changed) reload a new instance of the UserFragment if (userStateChanged) { FragmentManager fragmentManager = getSupportFragmentManager(); if (Profile.isSignedIn(this)) { fragmentManager.beginTransaction() .replace(R.id.container, new UserFragment()) .commit(); } else { mNavigationView.getMenu().getItem(0).setChecked(true); mCurrentSelectedPosition = 0; fragmentManager.beginTransaction() .replace(R.id.container, new RecentsFragment()) .commit(); } userStateChanged = false; } updateDrawer(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean autoSync = !prefs.getString(getString(R.string.pref_auto_sync), "1").equals("0"); if (prefs.getBoolean(getString(R.string.pref_registered_topic_price_updates), false) != autoSync) { Intent intent = new Intent(this, GcmRegisterPriceUpdatesService.class); intent.putExtra(GcmRegisterPriceUpdatesService.EXTRA_SUBSCRIBE, autoSync); startService(intent); } super.onResume(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Save the current fragment to be restored. outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_SETTINGS) { //User returned from the settings activity if (resultCode == RESULT_OK) { if (mCurrentSelectedPosition == 2) { if (data != null && data.getBooleanExtra("login_changed", false)) { //User fragment needs to be reloaded if the steamId was changed userStateChanged = true; } } } return; } //super call is needed to pass the result to the fragments super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onOptionsItemSelected(MenuItem item) { //Handler the drawer toggle press return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void setSupportActionBar(Toolbar toolbar) { super.setSupportActionBar(toolbar); //Since each fragment has it's own toolbar we need to re add the drawer toggle everytime we //switch fragments restoreNavigationIcon(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. mDrawerToggle.onConfigurationChanged(newConfig); } /** * Switches to another fragment. * * @param position the position of the clicked item in the navigation view */ public void switchFragment(int position) { if (mCurrentSelectedPosition == position) { return; } mCurrentSelectedPosition = position; if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mNavigationView); } //Start handling fragment transactions FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.setCustomAnimations(R.anim.simple_fade_in, R.anim.simple_fade_out); Fragment newFragment; //Initialize fragments and add them is the drawer listener switch (position) { case 0: newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_RECENTS); if (newFragment == null) { newFragment = new RecentsFragment(); } drawerListener = (RecentsFragment) newFragment; transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_RECENTS); break; case 1: newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_UNUSUALS); if (newFragment == null) { newFragment = new UnusualFragment(); } drawerListener = (UnusualFragment) newFragment; transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_UNUSUALS); break; case 2: newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_USER); if (newFragment == null) { newFragment = new UserFragment(); } drawerListener = (UserFragment) newFragment; transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_USER); break; case 3: newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_FAVORITES); if (newFragment == null) { newFragment = new FavoritesFragment(); } drawerListener = (FavoritesFragment) newFragment; transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_FAVORITES); break; case 4: newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_CONVERTER); if (newFragment == null) { newFragment = new ConverterFragment(); } drawerListener = null; transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_CONVERTER); break; case 5: newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_CALCULATOR); if (newFragment == null) { newFragment = new CalculatorFragment(); } drawerListener = (CalculatorFragment) newFragment; transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_CALCULATOR); break; default: throw new IllegalArgumentException("unknown fragment to switch to: " + position); } //Commit the transaction transaction.commit(); } /** * Updates the information in the navigation drawer header. */ public void updateDrawer() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (Profile.isSignedIn(this)) { //Set the name name.setText(prefs.getString(getString(R.string.pref_player_name), null)); //Set the backpack value double bpValue = Utility.getDouble(prefs, getString(R.string.pref_player_backpack_value_tf2), -1); if (bpValue >= 0) { backpack.setText(String.format("Backpack: %s", getString(R.string.currency_metal, String.valueOf(Math.round(bpValue))))); } else { backpack.setText("Private backpack"); } //Download the avatar (if needed) and set it if (prefs.contains(getString(R.string.pref_new_avatar)) && Utility.isNetworkAvailable(this)) { Glide.with(this) .load(PreferenceManager.getDefaultSharedPreferences(this). getString(getString(R.string.pref_player_avatar_url), "")) .diskCacheStrategy(DiskCacheStrategy.ALL) .transform(new CircleTransform(this)) .into(avatar); } userMenuItem.setEnabled(true); } else { Glide.with(this) .load(R.drawable.steam_default_avatar) .diskCacheStrategy(DiskCacheStrategy.ALL) .transform(new CircleTransform(this)) .into(avatar); name.setText(null); backpack.setText(null); userMenuItem.setEnabled(false); } } /** * Restores the navigation icon of the toolbar. */ private void restoreNavigationIcon() { // set up the drawer's list view with items and click listener ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeButtonEnabled(true); } // ActionBarDrawerToggle ties together the the proper interactions // between the navigation drawer and the action bar app icon. mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); //Notify the listeners if (drawerListener != null) { drawerListener.onDrawerOpened(); } } }; // Defer code dependent on restoration of previous instance state. mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } /** * Interface for listening drawer open events. */ public interface OnDrawerOpenedListener { /** * Called when the navigation drawer is opened. */ void onDrawerOpened(); } }
/* * J A V A C O M M U N I T Y P R O C E S S * * J S R 9 4 * * Test Compatability Kit * */ package org.jcp.jsr94.tck; // java imports import junit.framework.Test; import junit.framework.TestSuite; import org.jcp.jsr94.tck.admin.LocalRuleExecutionSetProviderTest; import org.jcp.jsr94.tck.admin.RuleAdministrationExceptionTest; import org.jcp.jsr94.tck.admin.RuleAdministratorTest; import org.jcp.jsr94.tck.admin.RuleExecutionSetCreateExceptionTest; import org.jcp.jsr94.tck.admin.RuleExecutionSetDeregistrationExceptionTest; import org.jcp.jsr94.tck.admin.RuleExecutionSetProviderTest; import org.jcp.jsr94.tck.admin.RuleExecutionSetRegisterExceptionTest; import org.jcp.jsr94.tck.admin.RuleExecutionSetTest; import org.jcp.jsr94.tck.admin.RuleTest; /** * Run all the test suites in the Test Compatability Kit. * Output is directed to System.out (textui). */ public class AllTests extends TestSuite { public static Test suite() { // System.setProperty( "jsr94.tck.configuration", // "src/test/resources/org/drools/jsr94/tck" ); TestSuite suite = new TestSuite( "JSR 94 Test Compatability Kit" ); suite.addTestSuite( ApiSignatureTest.class ); //JBRULES-139 TCK-TestCaseUtil needs to be fixed //suite.addTestSuite( ClassLoaderTest.class ); suite.addTestSuite( ConfigurationExceptionTest.class ); suite.addTestSuite( HandleTest.class ); suite.addTestSuite( InvalidHandleExceptionTest.class ); suite.addTestSuite( InvalidRuleSessionExceptionTest.class ); suite.addTestSuite( ObjectFilterTest.class ); suite.addTestSuite( RuleExceptionTest.class ); suite.addTestSuite( RuleExecutionExceptionTest.class ); suite.addTestSuite( RuleExecutionSetMetadataTest.class ); suite.addTestSuite( RuleExecutionSetNotFoundExceptionTest.class ); suite.addTestSuite( RuleRuntimeTest.class ); suite.addTestSuite( RuleServiceProviderManagerTest.class ); suite.addTestSuite( RuleServiceProviderTest.class ); suite.addTestSuite( RuleSessionCreateExceptionTest.class ); suite.addTestSuite( RuleSessionTest.class ); suite.addTestSuite( RuleSessionTypeUnsupportedExceptionTest.class ); suite.addTestSuite( StatefulRuleSessionTest.class ); suite.addTestSuite( StatelessRuleSessionTest.class ); suite.addTestSuite( LocalRuleExecutionSetProviderTest.class ); suite.addTestSuite( RuleAdministrationExceptionTest.class ); suite.addTestSuite( RuleAdministratorTest.class ); suite.addTestSuite( RuleExecutionSetCreateExceptionTest.class ); // suite.addTestSuite(RuleExecutionSetProviderTest.class); suite.addTestSuite( RuleExecutionSetRegisterExceptionTest.class ); suite.addTestSuite( RuleExecutionSetTest.class ); suite.addTestSuite( RuleExecutionSetDeregistrationExceptionTest.class ); suite.addTestSuite( RuleTest.class ); return suite; } // public static Test suite() // TestSuite suite = new TestSuite( "JSR 94 Test Compatability Kit" ); // System.out.println(System.getProperty("jsr94.tck.configuration")); // suite.addTestSuite(ApiSignatureTest.class); // suite.addTestSuite(ClassLoaderTest.class); // suite.addTestSuite(ConfigurationExceptionTest.class); // suite.addTestSuite(HandleTest.class); // suite.addTestSuite(InvalidHandleExceptionTest.class); // suite.addTestSuite(InvalidRuleSessionExceptionTest.class); // suite.addTestSuite(ObjectFilterTest.class); // suite.addTestSuite(RuleExceptionTest.class); // suite.addTestSuite(RuleExecutionExceptionTest.class); // suite.addTestSuite(RuleExecutionSetMetadataTest.class); // suite.addTestSuite(RuleExecutionSetNotFoundExceptionTest.class); // suite.addTestSuite(RuleRuntimeTest.class); // suite.addTestSuite(RuleServiceProviderManagerTest.class); // suite.addTestSuite(RuleServiceProviderTest.class); // suite.addTestSuite(RuleSessionCreateExceptionTest.class); // suite.addTestSuite(RuleSessionTest.class); // suite.addTestSuite(RuleSessionTypeUnsupportedExceptionTest.class); // suite.addTestSuite(StatefulRuleSessionTest.class); // suite.addTestSuite(StatelessRuleSessionTest.class); // suite.addTestSuite(LocalRuleExecutionSetProviderTest.class); // suite.addTestSuite(RuleAdministrationExceptionTest.class); // suite.addTestSuite(RuleAdministratorTest.class); // suite.addTestSuite(RuleExecutionSetCreateExceptionTest.class); //// suite.addTestSuite(RuleExecutionSetProviderTest.class); // suite.addTestSuite(RuleExecutionSetRegisterExceptionTest.class); // suite.addTestSuite(RuleExecutionSetTest.class); // suite.addTestSuite(RuleExecutionSetDeregistrationExceptionTest.class); // suite.addTestSuite(RuleTest.class); // return suite; }
package com.artwl.update; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.GZIPInputStream; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Looper; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.common.base.Strings; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class UpdateChecker extends Fragment { private static final String NOTICE_TYPE_KEY = "type"; private static final String APP_UPDATE_SERVER_URL = "app_update_server_url"; private static final String APK_IS_AUTO_INSTALL = "apk_is_auto_install"; private static final int NOTICE_NOTIFICATION = 2; private static final int NOTICE_DIALOG = 1; private static final String TAG = "UpdateChecker"; private static final String HTTP_VERB = "httpverb"; private FragmentActivity mContext; private Thread mThread; private int mTypeOfNotice; private boolean mIsAutoInstall; private String mHttpVerb; public static void checkForDialog(FragmentActivity fragmentActivity, String checkUpdateServerUrl, boolean isAutoInstall) { checkForDialog(fragmentActivity, checkUpdateServerUrl, isAutoInstall, "GET"); } /** * Show a Dialog if an update is available for download. Callable in a * FragmentActivity. Number of checks after the dialog will be shown: * default, 5 * * @param fragmentActivity Required. */ public static void checkForDialog(FragmentActivity fragmentActivity, String checkUpdateServerUrl, boolean isAutoInstall, String httpVerb) { checkForAutoUpdate(fragmentActivity, checkUpdateServerUrl, isAutoInstall, httpVerb, NOTICE_DIALOG); } /** * Show a Notification if an update is available for download. Callable in a * FragmentActivity Specify the number of checks after the notification will * be shown. * * @param fragmentActivity Required. */ public static void checkForNotification(FragmentActivity fragmentActivity, String checkUpdateServerUrl, boolean isAutoInstall) { checkForNotification(fragmentActivity, checkUpdateServerUrl, isAutoInstall, "GET"); } /** * Show a Notification if an update is available for download. Callable in a * FragmentActivity Specify the number of checks after the notification will * be shown. * * @param fragmentActivity Required. */ public static void checkForNotification(FragmentActivity fragmentActivity, String checkUpdateServerUrl, boolean isAutoInstall, String httpVerb) { checkForAutoUpdate(fragmentActivity, checkUpdateServerUrl, isAutoInstall, httpVerb, NOTICE_NOTIFICATION); } public static void checkForAutoUpdate(FragmentActivity fragmentActivity, String checkUpdateServerUrl, boolean isAutoInstall, String httpVerb, int typeOfNotice) { FragmentTransaction content = fragmentActivity.getSupportFragmentManager().beginTransaction(); UpdateChecker updateChecker = new UpdateChecker(); Bundle args = new Bundle(); args.putInt(NOTICE_TYPE_KEY, typeOfNotice); args.putString(APP_UPDATE_SERVER_URL, checkUpdateServerUrl); args.putBoolean(APK_IS_AUTO_INSTALL, isAutoInstall); args.putString(HTTP_VERB, httpVerb); updateChecker.setArguments(args); content.add(updateChecker, null).commit(); } /** * This class is a Fragment. Check for the method you have chosen. */ @Override public void onAttach(Activity activity) { super.onAttach(activity); mContext = (FragmentActivity) activity; Bundle args = getArguments(); mTypeOfNotice = args.getInt(NOTICE_TYPE_KEY); mIsAutoInstall = args.getBoolean(APK_IS_AUTO_INSTALL); mHttpVerb = args.getString(HTTP_VERB); String url = args.getString(APP_UPDATE_SERVER_URL); if (Strings.isNullOrEmpty(mHttpVerb)) { mHttpVerb = "POST"; } checkForUpdates(url); } /** * Heart of the library. Check if an update is available for download * parsing the desktop Play Store page of the app */ private void checkForUpdates(final String url) { mThread = new Thread() { @Override public void run() { //if (isNetworkAvailable(mContext)) { String json = sendPost(url); if (json != null) { parseJson(json); } else { Log.e(TAG, "can't get app update json"); } } }; mThread.start(); } private String sendPost(String url) { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } catch (IOException ex) { return ""; } /* HttpURLConnection uRLConnection = null; InputStream is = null; BufferedReader buffer = null; String result = null; try { URL url = new URL(urlStr); uRLConnection = (HttpURLConnection) url.openConnection(); uRLConnection.setDoInput(true); uRLConnection.setDoOutput(true); uRLConnection.setRequestMethod(mHttpVerb); uRLConnection.setUseCaches(false); uRLConnection.setConnectTimeout(10 * 1000); uRLConnection.setReadTimeout(10 * 1000); uRLConnection.setInstanceFollowRedirects(false); uRLConnection.setRequestProperty("Connection", "Keep-Alive"); uRLConnection.setRequestProperty("Charset", "UTF-8"); uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); uRLConnection.setRequestProperty("Content-Type", "application/json"); uRLConnection.connect(); is = uRLConnection.getInputStream(); String content_encode = uRLConnection.getContentEncoding(); if (null != content_encode && !"".equals(content_encode) && content_encode.equals("gzip")) { is = new GZIPInputStream(is); } buffer = new BufferedReader(new InputStreamReader(is)); StringBuilder strBuilder = new StringBuilder(); String line; while ((line = buffer.readLine()) != null) { strBuilder.append(line); } result = strBuilder.toString(); } catch (Exception e) { Log.e(TAG, "http post error", e); } finally { if (buffer != null) { try { buffer.close(); } catch (IOException e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (uRLConnection != null) { uRLConnection.disconnect(); } } return result; */ } private void parseJson(String json) { mThread.interrupt(); Looper.prepare(); try { JSONObject obj = new JSONObject(json); if (!obj.has(Constants.APK_DOWNLOAD_URL)) { Log.e(TAG, "Server response data format error: no " + Constants.APK_DOWNLOAD_URL + " field"); return; } if (!obj.has(Constants.APK_UPDATE_CONTENT)) { Log.e(TAG, "Server response data format error: no " + Constants.APK_UPDATE_CONTENT + " field"); return; } if (!obj.has(Constants.APK_VERSION_CODE)) { Log.e(TAG, "Server response data format error: no " + Constants.APK_VERSION_CODE + " field"); return; } String updateMessage = obj.getString(Constants.APK_UPDATE_CONTENT); String apkUrl = obj.getString(Constants.APK_DOWNLOAD_URL); int apkCode = obj.getInt(Constants.APK_VERSION_CODE); int versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode; if (apkCode > versionCode) { updateMessage += String.format(" [%d --> %d]", versionCode, apkCode); if (mTypeOfNotice == NOTICE_NOTIFICATION) { showNotification(updateMessage, apkUrl, mIsAutoInstall); } else if (mTypeOfNotice == NOTICE_DIALOG) { showDialog(updateMessage, apkUrl, mIsAutoInstall); } } else { Log.i(TAG, mContext.getString(R.string.app_no_new_update)); } } catch (PackageManager.NameNotFoundException ignored) { } catch (JSONException e) { Log.e(TAG, "parse json error", e); } } /** * Show dialog */ private void showDialog(String content, String apkUrl, boolean isAutoInstall) { UpdateDialog d = new UpdateDialog(); Bundle args = new Bundle(); args.putString(Constants.APK_UPDATE_CONTENT, content); args.putString(Constants.APK_DOWNLOAD_URL, apkUrl); args.putBoolean(Constants.APK_IS_AUTO_INSTALL, isAutoInstall); d.setArguments(args); // Don't use default d.show(mContext.getSupportFragmentManager(), null); FragmentTransaction ft = mContext.getSupportFragmentManager().beginTransaction(); ft.add(d, this.getClass().getSimpleName()); ft.commitAllowingStateLoss();//commitAllowingStateLoss() } /** * Show Notification */ private void showNotification(String content, String apkUrl, boolean isAutoInstall) { android.app.Notification noti; Intent myIntent = new Intent(mContext, DownloadService.class); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); myIntent.putExtra(Constants.APK_DOWNLOAD_URL, apkUrl); myIntent.putExtra(Constants.APK_IS_AUTO_INSTALL, isAutoInstall); PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT); int smallIcon = mContext.getApplicationInfo().icon; noti = new NotificationCompat.Builder(mContext).setTicker(getString(R.string.newUpdateAvailable)) .setContentTitle(getString(R.string.newUpdateAvailable)).setContentText(content).setSmallIcon(smallIcon) .setContentIntent(pendingIntent).build(); noti.flags = android.app.Notification.FLAG_AUTO_CANCEL; NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, noti); } /** * Check if a network available */ public static boolean isNetworkAvailable(Context context) { boolean connected = false; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null) { connected = ni.isConnected(); } } return connected; } }
package clc; import im.actor.core.*; import im.actor.core.api.rpc.RequestEditAbout; import im.actor.core.api.rpc.ResponseSeq; import im.actor.core.api.updates.UpdateUserAboutChanged; import im.actor.core.entity.*; import im.actor.core.entity.content.TextContent; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.core.providers.NotificationProvider; import im.actor.core.providers.PhoneBookProvider; import im.actor.core.viewmodel.Command; import im.actor.core.viewmodel.CommandCallback; import im.actor.core.viewmodel.UserVM; import im.actor.runtime.clc.ClcJavaPreferenceStorage; import im.actor.runtime.generic.mvvm.AndroidListUpdate; import im.actor.runtime.generic.mvvm.BindedDisplayList; import im.actor.runtime.generic.mvvm.DisplayList; import im.actor.sdk.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.prefs.BackingStoreException; public class ActorApplication { private String url; private String username; private String password; int myNumber = 1; public ConfigurationBuilder builder; private static final Logger logger = LoggerFactory.getLogger(ClcApplication.class); private static int randomSeed; static ClcMessenger messenger; public ActorApplication(String url,String username,String password,ConfigurationBuilder builder) { this.url = url; this.username = username; this.password = password; this.builder = builder; builder.setDeviceCategory(DeviceCategory.DESKTOP); builder.setPlatformType(PlatformType.GENERIC); builder.setApiConfiguration(new ApiConfiguration( "cli", 1, "4295f9666fad3faf2d04277fe7a0c40ff39a85d313de5348ad8ffa650ad71855", "najva00000000000000000123-" + myNumber, "najva00000000000000000000-v1-" + myNumber)); messenger = new ClcMessenger(builder.build(),Integer.toString(myNumber)); // messenger.resetAuth(); sendUserName("wangc","111"); } public void sendUserName(String username,String password) { messenger.requestStartUserNameAuth(username).start(new CommandCallback<AuthState>() { @Override public void onResult(AuthState res) { logger.info(res.toString()); sendPassword(password); } @Override public void onError(Exception e) { logger.error(e.getMessage(),e); } }); } public void sendPassword(String password) { try { messenger.validatePassword(password).start(new CommandCallback<AuthState>() { @Override public void onResult(AuthState res) { randomSeed = new Random().nextInt(); if (res == AuthState.SIGN_UP) { logger.info("SIGN_UP"); signUp(username, Sex.MALE,null, password); } else if(res == AuthState.LOGGED_IN){ logger.info("LOGGED_IN"); } } @Override public void onError(Exception e) { } }); } catch (Exception e) { logger.error(e.getMessage(),e); } } public void signUp(final String name, Sex sex, String avatarPath, String password) { messenger.signUp(name, sex, avatarPath,password).start(new CommandCallback<AuthState>() { @Override public void onResult(AuthState res) { if (res == AuthState.LOGGED_IN){ logger.info("LOGGED_IN"); // sendMessage("+989150000" + (myNumber + 20), "seed: " + randomSeed + "," + myNumber); }else if(res == AuthState.SIGN_UP){ logger.info("SIGN_UP"); } } @Override public void onError(Exception e) { } }); } }
package com.xlythe.sms.drawable; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; import android.util.TypedValue; import com.xlythe.sms.R; import com.xlythe.sms.util.ColorUtils; import com.xlythe.textmanager.text.Contact; import com.xlythe.textmanager.text.Receive; import java.io.IOException; import java.util.ArrayList; import java.util.Set; public class ProfileDrawable extends Drawable { private static final String TAG = ProfileDrawable.class.getSimpleName(); private final Paint mPaint; private final Context mContext; private final float mDrawableSizeInPx; private final float mFontSizeInSp; private final Bitmap[] mBitmaps; private final int mBitmapSize; public ProfileDrawable(Context context, Set<Contact> contacts) { mContext = context; mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Paint.Style.FILL); mDrawableSizeInPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, mContext.getResources().getDisplayMetrics()); mFontSizeInSp = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 24, mContext.getResources().getDisplayMetrics()); // Create an array of bitmaps (min 1, max 4) that hold the profile picture of a contact mBitmaps = new Bitmap[Math.min(4, contacts.size())]; Contact[] contactsArray = contacts.toArray(new Contact[contacts.size()]); for (int i = 0; i < mBitmaps.length; i++) { mBitmaps[i] = drawableToBitmap(contactsArray[i]); } // Resize the bitmaps so they'll all fit within the confines of our drawable mBitmapSize = getBitmapSize(mBitmaps[0].getWidth(), mBitmaps.length); for (int i = 0; i < mBitmaps.length; i++) { mBitmaps[i] = Bitmap.createScaledBitmap(mBitmaps[i], mBitmapSize, mBitmapSize, false); } } private int getBitmapSize(int width, int numberOfContacts) { double size; switch (numberOfContacts) { case 1: size = width; break; case 2: size = Math.sqrt(2) * width / (Math.sqrt(2) + 1); break; case 3: size = width / 2; break; default: size = width / 2; break; } return (int) size; } @Override public int getIntrinsicHeight() { return (int) mDrawableSizeInPx; } @Override public int getIntrinsicWidth() { return (int) mDrawableSizeInPx; } @Override public void draw(Canvas canvas) { switch (mBitmaps.length) { case 1: canvas.drawBitmap(mBitmaps[0], 0, 0, null); break; case 2: canvas.drawBitmap(mBitmaps[0], 0, 0, null); canvas.drawBitmap(mBitmaps[1], mDrawableSizeInPx - mBitmapSize, mDrawableSizeInPx - mBitmapSize, null); break; case 3: canvas.drawBitmap(mBitmaps[0], mBitmapSize / 2, 0, null); canvas.drawBitmap(mBitmaps[1], 0, mBitmapSize, null); canvas.drawBitmap(mBitmaps[2], mBitmapSize, mBitmapSize, null); break; default: canvas.drawBitmap(mBitmaps[0], 0, 0, null); canvas.drawBitmap(mBitmaps[1], mBitmapSize, 0, null); canvas.drawBitmap(mBitmaps[2], 0, mBitmapSize, null); canvas.drawBitmap(mBitmaps[3], mBitmapSize, mBitmapSize, null); break; } } protected Bitmap drawableToBitmap(Contact contact) { Bitmap profileBitmap = Bitmap.createBitmap((int) mDrawableSizeInPx, (int) mDrawableSizeInPx, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(profileBitmap); char initial = contact.getDisplayName().charAt(0); Uri uri = contact.getPhotoUri(); int color = ColorUtils.getColor(contact.getIdAsLong()); if (contact.getIdAsLong() < 0) { color = ColorUtils.getColor(Receive.getOrCreateThreadId(mContext, contact.getNumber())); } mPaint.setColor(color); canvas.drawCircle(mDrawableSizeInPx / 2, mDrawableSizeInPx / 2, mDrawableSizeInPx / 2, mPaint); mPaint.setColor(mContext.getResources().getColor(R.color.text)); if (uri != null) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri); bitmap = Bitmap.createScaledBitmap(bitmap, (int) mDrawableSizeInPx, (int) mDrawableSizeInPx, false); mPaint.setColor(Color.WHITE); canvas.drawBitmap(clip(bitmap), 0, 0, mPaint); } catch (IOException e){ Log.e(TAG, "Failed to load bitmap", e); } } else if (Character.isLetter(initial)) { mPaint.setTextSize(mFontSizeInSp); mPaint.setTextAlign(Paint.Align.CENTER); String text = initial + ""; Rect r = new Rect(); mPaint.getTextBounds(text, 0, text.length(), r); int y = (int) mDrawableSizeInPx /2 + (Math.abs(r.height()))/2; canvas.drawText(text, mDrawableSizeInPx /2, y, mPaint); } else { Bitmap bmp1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_profile); canvas.drawBitmap(bmp1, 0, 0, mPaint); } return profileBitmap; } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter colorFilter) { mPaint.setColorFilter(colorFilter); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } protected Bitmap clip(Bitmap bitmap) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } }
package fi.jumi.test; import fi.luontola.buildtest.*; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import javax.annotation.concurrent.*; import java.io.*; import java.util.*; import static fi.luontola.buildtest.AsmMatchers.*; import static fi.luontola.buildtest.AsmUtils.annotatedWithOneOf; import static java.util.Arrays.asList; import static org.fest.assertions.Assertions.assertThat; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assume.assumeTrue; @RunWith(Parameterized.class) public class BuildTest { private static final String MANIFEST = "META-INF/MANIFEST.MF"; private static final String POM_FILES = "META-INF/maven/fi.jumi.actors/"; private static final String BASE_PACKAGE = "fi/jumi/"; private static final String[] DOES_NOT_NEED_JSR305_ANNOTATIONS = { // ignore, because the ThreadSafetyAgent anyways won't check itself "fi/jumi/threadsafetyagent/", }; private final String artifactId; private final Integer[] expectedClassVersion; private final List<String> expectedDependencies; private final List<String> expectedContents; private final Deprecations expectedDeprecations; public BuildTest(String artifactId, List<Integer> expectedClassVersion, List<String> expectedDependencies, List<String> expectedContents, Deprecations expectedDeprecations) { this.artifactId = artifactId; this.expectedClassVersion = expectedClassVersion.toArray(new Integer[expectedClassVersion.size()]); this.expectedDependencies = expectedDependencies; this.expectedContents = expectedContents; this.expectedDeprecations = expectedDeprecations; } @Parameters(name = "{0}") public static Collection<Object[]> data() { return asList(new Object[][]{ {"jumi-actors", asList(Opcodes.V1_6), asList(), asList( MANIFEST, POM_FILES, BASE_PACKAGE + "actors/"), new Deprecations() }, {"thread-safety-agent", asList(Opcodes.V1_5, Opcodes.V1_6), asList(), asList( MANIFEST, POM_FILES, BASE_PACKAGE + "threadsafetyagent/"), new Deprecations() }, }); } @Test public void pom_contains_only_allowed_dependencies() throws Exception { List<String> dependencies = MavenUtils.getRuntimeDependencies(getProjectPom()); assertThat("dependencies of " + artifactId, dependencies, is(expectedDependencies)); } @Test public void jar_contains_only_allowed_files() throws Exception { File jarFile = getProjectJar(); JarUtils.assertContainsOnly(jarFile, expectedContents); } @Test public void jar_contains_a_pom_properties_with_the_maven_artifact_identifiers() throws IOException { Properties p = getPomProperties(); assertThat("groupId", p.getProperty("groupId"), is("fi.jumi.actors")); assertThat("artifactId", p.getProperty("artifactId"), is(artifactId)); assertThat("version", p.getProperty("version"), is(TestEnvironment.VERSION_NUMBERING)); } @Test public void release_jar_contains_build_properties_with_the_Git_revision_ID() throws IOException { assumeReleaseBuild(); Properties p = getBuildProperties(); assertThat(p.getProperty("revision")).as("revision").matches("[0-9a-f]{40}"); } @Test public void none_of_the_artifacts_may_have_dependencies_to_external_libraries() { for (String dependency : expectedDependencies) { assertThat("artifact " + artifactId, dependency, startsWith("fi.jumi.actors:")); } } @Test public void none_of_the_artifacts_may_contain_classes_from_external_libraries_without_shading_them() { for (String content : expectedContents) { assertThat("artifact " + artifactId, content, Matchers.<String> either(startsWith(BASE_PACKAGE)) .or(startsWith(POM_FILES)) .or(startsWith(MANIFEST))); } } @Test public void all_classes_must_use_the_specified_bytecode_version() throws IOException { CompositeMatcher<ClassNode> matcher = newClassNodeCompositeMatcher() .assertThatIt(hasClassVersion(isOneOf(expectedClassVersion))); JarUtils.checkAllClasses(getProjectJar(), matcher); } @Test public void all_classes_must_be_annotated_with_JSR305_concurrent_annotations() throws Exception { CompositeMatcher<ClassNode> matcher = newClassNodeCompositeMatcher() .excludeIf(is(anInterface())) .excludeIf(is(syntheticClass())) .excludeIf(nameStartsWithOneOf(DOES_NOT_NEED_JSR305_ANNOTATIONS)) .assertThatIt(is(annotatedWithOneOf(Immutable.class, NotThreadSafe.class, ThreadSafe.class))); JarUtils.checkAllClasses(getProjectJar(), matcher); } @Test public void deprecated_methods_are_removed_after_the_transition_period() throws IOException { expectedDeprecations.verify(new ClassesInJarFile(getProjectJar())); } // helper methods private File getProjectPom() throws IOException { return TestEnvironment.ARTIFACTS.getProjectPom(artifactId); } private File getProjectJar() throws IOException { return TestEnvironment.ARTIFACTS.getProjectJar(artifactId); } private void assumeReleaseBuild() throws IOException { String version = getPomProperties().getProperty("version"); assumeTrue(TestEnvironment.VERSION_NUMBERING.isRelease(version)); } private Properties getBuildProperties() throws IOException { return getMavenArtifactProperties(getProjectJar(), "build.properties"); } private Properties getPomProperties() throws IOException { return getMavenArtifactProperties(getProjectJar(), "pom.properties"); } private Properties getMavenArtifactProperties(File jarFile, String filename) { return JarUtils.getProperties(jarFile, POM_FILES + artifactId + "/" + filename); } }
package fr.neamar.kiss.loader; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import fr.neamar.kiss.normalizer.PhoneNormalizer; import fr.neamar.kiss.normalizer.StringNormalizer; import fr.neamar.kiss.pojo.ContactsPojo; public class LoadContactsPojos extends LoadPojos<ContactsPojo> { public LoadContactsPojos(Context context) { super(context, "contact: } @Override protected ArrayList<ContactsPojo> doInBackground(Void... params) { long start = System.nanoTime(); // Run query Cursor cur = context.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.STARRED, ContactsContract.CommonDataKinds.Phone.IS_PRIMARY, ContactsContract.Contacts.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, null, null, ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED + " DESC"); // Prevent duplicates by keeping in memory encountered phones. // The string key is "phone" + "|" + "name" (so if two contacts // with distinct name share same number, they both get displayed) Map<String, ArrayList<ContactsPojo>> mapContacts = new HashMap<>(); if (cur != null) { if (cur.getCount() > 0) { int lookupIndex = cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY); int timesContactedIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED); int displayNameIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); int numberIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); int starredIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED); int isPrimaryIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.IS_PRIMARY); int photoIdIndex = cur.getColumnIndex(ContactsContract.Contacts.PHOTO_ID); while (cur.moveToNext()) { ContactsPojo contact = new ContactsPojo(); contact.lookupKey = cur.getString(lookupIndex); contact.timesContacted = cur.getInt(timesContactedIndex); contact.setName(cur.getString(displayNameIndex)); contact.phone = cur.getString(numberIndex); if (contact.phone == null) { contact.phone = ""; } contact.phoneSimplified = PhoneNormalizer.simplifyPhoneNumber(contact.phone); contact.starred = cur.getInt(starredIndex) != 0; contact.primary = cur.getInt(isPrimaryIndex) != 0; String photoId = cur.getString(photoIdIndex); if (photoId != null) { contact.icon = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, Long.parseLong(photoId)); } contact.id = pojoScheme + contact.lookupKey + contact.phone; if (contact.name != null) { contact.nameNormalized = StringNormalizer.normalize(contact.name); if (mapContacts.containsKey(contact.lookupKey)) mapContacts.get(contact.lookupKey).add(contact); else { ArrayList<ContactsPojo> phones = new ArrayList<>(); phones.add(contact); mapContacts.put(contact.lookupKey, phones); } } } } cur.close(); } // Retrieve contacts' nicknames Cursor nickCursor = context.getContentResolver().query( ContactsContract.Data.CONTENT_URI, new String[]{ ContactsContract.CommonDataKinds.Nickname.NAME, ContactsContract.Data.LOOKUP_KEY}, ContactsContract.Data.MIMETYPE + "= ?", new String[]{ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE}, null); if (nickCursor != null) { if (nickCursor.getCount() > 0) { int lookupKeyIndex = nickCursor.getColumnIndex(ContactsContract.Data.LOOKUP_KEY); int nickNameIndex = nickCursor.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME); while (nickCursor.moveToNext()) { String lookupKey = nickCursor.getString(lookupKeyIndex); String nick = nickCursor.getString(nickNameIndex); if (nick != null && lookupKey != null && mapContacts.containsKey(lookupKey)) { for (ContactsPojo contact : mapContacts.get(lookupKey)) { contact.setNickname(nick); } } } } nickCursor.close(); } ArrayList<ContactsPojo> contacts = new ArrayList<>(); Pattern phoneFormatter = Pattern.compile("[ \\.\\(\\)]"); for (List<ContactsPojo> phones : mapContacts.values()) { // Find primary phone and add this one. Boolean hasPrimary = false; for (ContactsPojo contact : phones) { if (contact.primary) { contacts.add(contact); hasPrimary = true; break; } } // If not available, add all (excluding duplicates). if (!hasPrimary) { Map<String, Boolean> added = new HashMap<>(); for (ContactsPojo contact : phones) { String uniqueKey = phoneFormatter.matcher(contact.phone).replaceAll(""); // TODO: what's this supposed to do? //uniqueKey = uniqueKey.replaceAll("^\\+33", "0"); //uniqueKey = uniqueKey.replaceAll("^\\+1", "0"); if (!added.containsKey(uniqueKey)) { added.put(uniqueKey, true); contacts.add(contact); } } } } long end = System.nanoTime(); Log.i("time", Long.toString((end - start) / 1000000) + " milliseconds to list contacts"); return contacts; } }
package com.jetbrains.env; import com.intellij.execution.process.ProcessHandler; import com.intellij.ide.util.projectWizard.EmptyModuleBuilder; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.module.ModuleTypeManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.RefreshQueueImpl; import com.intellij.testFramework.EdtTestUtil; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.PsiTestUtil; import com.intellij.testFramework.builders.ModuleFixtureBuilder; import com.intellij.testFramework.fixtures.*; import com.intellij.testFramework.fixtures.impl.ModuleFixtureBuilderImpl; import com.intellij.testFramework.fixtures.impl.ModuleFixtureImpl; import com.intellij.util.ui.UIUtil; import com.jetbrains.extensions.ModuleExtKt; import com.jetbrains.python.PyNames; import com.jetbrains.python.PythonModuleTypeBase; import com.jetbrains.python.PythonTestUtil; import com.jetbrains.python.packaging.PyCondaPackageManagerImpl; import com.jetbrains.python.packaging.PyPackageManager; import com.jetbrains.python.psi.LanguageLevel; import com.jetbrains.python.sdk.InvalidSdkException; import com.jetbrains.python.sdk.PythonSdkType; import com.jetbrains.python.tools.sdkTools.PySdkTools; import com.jetbrains.python.tools.sdkTools.SdkCreationType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * <h1>Task to execute code using {@link CodeInsightTestFixture}</h1> * <h2>How to use it</h2> * <p> * Each test may have some test data somewhere in VCS (like <strong>testData</strong> folder). * It is called <strong>test data path</strong>. * This task copies test data to some temporary location, and launches your test against it. * To get this location, use {@link CodeInsightTestFixture#getTempDirFixture()} * or {@link CodeInsightTestFixture#getTempDirPath()}. * </p> * <p> * You provide path to test data using 2 parts: base ({@link #getTestDataPath()} and relative * path as argument to {@link PyExecutionFixtureTestTask#PyExecutionFixtureTestTask(String)}. * Path is merged then, and data copied to temporary location, available with {@link CodeInsightTestFixture#getTempDirFixture()}. * You may provide <strong>null</strong> to argument if you do not want to copy anything. * </p> * <h2>Things to check to make sure you use this code correctly</h2> * <ol> * <li> * You never access {@link #getTestDataPath()} or {@link CodeInsightTestFixture#getTempDirPath()} in tests. * <strong>Always</strong> work with {@link CodeInsightTestFixture#getTempDirFixture()} * </li> * <li> * When overwriting {@link #getTestDataPath()} you return path to your <strong>testData</strong> (see current impl.) * </li> * </ol> * * @author traff * @author Ilya.Kazakevich */ public abstract class PyExecutionFixtureTestTask extends PyTestTask { public static final int NORMAL_TIMEOUT = 30000; public static final int LONG_TIMEOUT = 120000; protected int myTimeout = NORMAL_TIMEOUT; protected CodeInsightTestFixture myFixture; @Nullable private final String myRelativeTestDataPath; /** * @param relativeTestDataPath path that will be added to {@link #getTestDataPath()} to obtain test data path (the one * that will be copied to temp folder. See class doc.). * Pass null if you do not want to copy anything. */ protected PyExecutionFixtureTestTask(@Nullable final String relativeTestDataPath) { myRelativeTestDataPath = relativeTestDataPath; } @Nullable protected String getRelativeTestDataPath() { return myRelativeTestDataPath; } /** * Debug output of this classes will be captured and reported in case of test failure */ @NotNull public Iterable<Class<?>> getClassesToEnableDebug() { return Collections.emptyList(); } public Project getProject() { return myFixture.getProject(); } @Override public void useNormalTimeout() { myTimeout = NORMAL_TIMEOUT; } @Override public void useLongTimeout() { myTimeout = LONG_TIMEOUT; } /** * Returns virt file by path. May be relative or not. * * @return file or null if file does not exist */ @Nullable protected VirtualFile getFileByPath(@NotNull final String path) { final File fileToWorkWith = new File(path); return (fileToWorkWith.isAbsolute() ? LocalFileSystem.getInstance().findFileByIoFile(fileToWorkWith) : myFixture.getTempDirFixture().getFile(path)); } @Override public void setUp(final String testName) throws Exception { final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory(); fixtureFactory.registerFixtureBuilder(MyModuleFixtureBuilder.class, MyModuleFixtureBuilderImpl.class); final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = fixtureFactory.createFixtureBuilder(testName); fixtureBuilder.addModule(MyModuleFixtureBuilder.class); myFixture = fixtureFactory.createCodeInsightFixture(fixtureBuilder.getFixture()); myFixture.setTestDataPath(getTestDataPath()); myFixture.setUp(); final Module module = myFixture.getModule(); assert module != null; PlatformPythonModuleType.ensureModuleRegistered(); if (StringUtil.isNotEmpty(myRelativeTestDataPath)) { // Without performing the copy deliberately in the EDT, this code may stuck in a livelock for unclear reason. EdtTestUtil.runInEdtAndWait(() -> myFixture.copyDirectoryToProject(myRelativeTestDataPath, ".").getPath()); } final VirtualFile projectRoot = myFixture.getTempDirFixture().getFile("."); PsiTestUtil.addSourceRoot(module, projectRoot); PsiTestUtil.addContentRoot(module, projectRoot); for (final String contentRoot : getContentRoots()) { final VirtualFile file = myFixture.getTempDirFixture().getFile(contentRoot); assert file != null && file.exists() : String.format("Content root does not exist %s", file); PsiTestUtil.addContentRoot(module, file); } } @NotNull public LanguageLevel getLevelForSdk() { return PythonSdkType.getLanguageLevelForSdk(ModuleExtKt.getSdk(myFixture.getModule())); } /** * @return additional content roots */ @NotNull protected List<String> getContentRoots() { return new ArrayList<>(); } protected String getFilePath(@NotNull final String path) { final VirtualFile virtualFile = myFixture.getTempDirFixture().getFile(path); assert virtualFile != null && virtualFile.exists() : String.format("No file '%s' in %s", path, myFixture.getTempDirPath()); return virtualFile.getPath(); } /** * @return root of your test data path on filesystem (this is base folder: class will add its relative path from ctor * to create full path and copy it to temp folder, see class doc.) */ @NotNull protected String getTestDataPath() { return PythonTestUtil.getTestDataPath(); } @Override public void tearDown() throws Exception { if (myFixture != null) { EdtTestUtil.runInEdtAndWait(() -> { UIUtil.dispatchAllInvocationEvents(); while (RefreshQueueImpl.isRefreshInProgress()) { UIUtil.dispatchAllInvocationEvents(); } for (Sdk sdk : ProjectJdkTable.getInstance().getSdksOfType(PythonSdkType.getInstance())) { WriteAction.run(() -> ProjectJdkTable.getInstance().removeJdk(sdk)); } }); // Teardown should be called on main thread because fixture teardown checks for // thread leaks, and blocked main thread is considered as leaked Project project = myFixture.getProject(); myFixture.tearDown(); if (project != null && !project.isDisposed()) { ProjectManagerEx.getInstanceEx().forceCloseProject(project); } myFixture = null; } super.tearDown(); } @Nullable protected LightProjectDescriptor getProjectDescriptor() { return null; } protected boolean waitFor(ProcessHandler p) { return p.waitFor(myTimeout); } protected boolean waitFor(@NotNull Semaphore s) throws InterruptedException { return waitFor(s, myTimeout); } protected static boolean waitFor(@NotNull Semaphore s, long timeout) throws InterruptedException { return s.tryAcquire(timeout, TimeUnit.MILLISECONDS); } public static class MyModuleFixtureBuilderImpl extends ModuleFixtureBuilderImpl<ModuleFixture> implements MyModuleFixtureBuilder { public MyModuleFixtureBuilderImpl(TestFixtureBuilder<? extends IdeaProjectTestFixture> fixtureBuilder) { super(new PlatformPythonModuleType(), fixtureBuilder); } @NotNull @Override protected ModuleFixture instantiateFixture() { return new ModuleFixtureImpl(this); } } public static class PlatformPythonModuleType extends PythonModuleTypeBase<EmptyModuleBuilder> { private static final String MODULE_ID = PyNames.PYTHON_MODULE_ID; @NotNull public static PlatformPythonModuleType getInstance() { ensureModuleRegistered(); return (PlatformPythonModuleType)ModuleTypeManager.getInstance().findByID(PyNames.PYTHON_MODULE_ID); } static void ensureModuleRegistered() { ModuleTypeManager moduleManager = ModuleTypeManager.getInstance(); if (!(moduleManager.findByID(MODULE_ID) instanceof PythonModuleTypeBase)) { moduleManager.registerModuleType(new PlatformPythonModuleType()); } } @NotNull @Override public EmptyModuleBuilder createModuleBuilder() { return new EmptyModuleBuilder() { @Override public ModuleType getModuleType() { return getInstance(); } }; } } /** * Creates SDK by its path * * @param sdkHome path to sdk (probably obtained by {@link PyTestTask#runTestOn(String, Sdk)}) * @param sdkCreationType SDK creation strategy (see {@link sdkTools.SdkCreationType} doc) * @return sdk */ @NotNull protected Sdk createTempSdk(@NotNull final String sdkHome, @NotNull final SdkCreationType sdkCreationType) throws InvalidSdkException { final VirtualFile sdkHomeFile = LocalFileSystem.getInstance().findFileByPath(sdkHome); Assert.assertNotNull("Interpreter file not found: " + sdkHome, sdkHomeFile); final Sdk sdk = PySdkTools.createTempSdk(sdkHomeFile, sdkCreationType, myFixture.getModule()); // We use gradle script to create environment. This script utilizes Conda. // Conda supports 2 types of package installation: conda native and pip. We use pip. // PyCharm Conda support ignores packages installed via pip ("conda list -e" does it, see PyCondaPackageManagerImpl) // So we need to either fix gradle (PythonEnvsPlugin.groovy on github) or use helper instead of "conda list" to get all packages // We do the latter. final PyPackageManager packageManager = PyPackageManager.getInstance(sdk); if (packageManager instanceof PyCondaPackageManagerImpl) { ((PyCondaPackageManagerImpl)packageManager).useConda = false; } return sdk; } public interface MyModuleFixtureBuilder extends ModuleFixtureBuilder<ModuleFixture> { } }
package fr.openium.blinkiumandroid; import android.content.Intent; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.WindowManager; import android.widget.EditText; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends AppCompatActivity implements OnClickListener { private EditText mEditTextIdentifier; private EditText mEditTextPassword; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEditTextIdentifier = (EditText) findViewById(R.id.idField); mEditTextPassword = (EditText) findViewById(R.id.passField); Button loginButton = (Button) findViewById(R.id.loginButton); loginButton.setOnClickListener(this); mHandler = new Handler(getMainLooper()); WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.screenBrightness = 0.1F; getWindow().setAttributes(layout); mHandler.postDelayed(new Runnable() { @Override public void run() { WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.screenBrightness = 0.5F; getWindow().setAttributes(layout); } },2000); mHandler.postDelayed(new Runnable() { @Override public void run() { WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.screenBrightness = 1F; getWindow().setAttributes(layout); } },4000); } @Override public void onClick(View v) { if (v.getId() == R.id.loginButton) { String login = mEditTextIdentifier.getText().toString(); String password = mEditTextPassword.getText().toString(); Intent intent = Blink_Activity.getIntent(this, login, password); startActivity(intent); } } }